Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
762989b39f | ||
|
|
1767df4747 | ||
|
|
055526057a | ||
|
|
5af52898d3 | ||
|
|
34dc2466e4 | ||
|
|
fad48c401f | ||
|
|
215229c28f | ||
|
|
1ea09243c5 | ||
|
|
96c9500afd | ||
|
|
b6ea714339 | ||
|
|
ffe7a577cc | ||
|
|
a2f14bd007 | ||
|
|
66ac6a3d8a | ||
|
|
50caa25d41 | ||
|
|
92af3fdf0f | ||
|
|
c443cdee36 | ||
|
|
8ca3876b10 | ||
|
|
c7e822345b | ||
|
|
b43a6a923e | ||
|
|
e60fe36740 | ||
|
|
f5735eb697 | ||
|
|
7002554a47 | ||
|
|
660a09b3af | ||
|
|
79388035f5 | ||
|
|
edc204f0b2 | ||
|
|
7d2cee20f6 | ||
|
|
a58a924e10 | ||
|
|
e0a9b4b476 | ||
|
|
eb8121c790 | ||
|
|
3f0608bdc3 | ||
|
|
9797a466fc | ||
|
|
418c277dfb | ||
|
|
580bd764f7 | ||
|
|
49dec48926 | ||
|
|
c8c7663c83 | ||
|
|
4e6261a392 | ||
|
|
f10cf8bdc8 | ||
|
|
75313ababc | ||
|
|
570d44b502 | ||
|
|
71c335ac26 | ||
|
|
02f5d57871 | ||
|
|
6c16486b4a | ||
|
|
bfa5d6d23c | ||
|
|
c30b6d675b | ||
|
|
b59937b80f | ||
|
|
5b0f17130f | ||
|
|
2548965a1e | ||
|
|
09c01da205 | ||
|
|
9ed78dea24 | ||
|
|
e5888e7b93 | ||
|
|
13af842c66 | ||
|
|
a211223810 | ||
|
|
8bc3c826b1 | ||
|
|
7a3d6ec928 | ||
|
|
9b2e7892ca | ||
|
|
04794d5dfd | ||
|
|
36c2787fc6 | ||
|
|
2bafa0b50b | ||
|
|
c953de0036 | ||
|
|
aad7aa4d22 | ||
|
|
ebe23614f7 | ||
|
|
d8d6ab48c8 |
@@ -0,0 +1,18 @@
|
||||
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
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
env:
|
||||
CIRRUS_CLONE_DEPTH: 50
|
||||
ELIXIR_ASSERT_TIMEOUT: 2000
|
||||
ELIXIRC_OPTS: "--warnings-as-errors"
|
||||
ERLC_OPTS: "warnings_as_errors"
|
||||
LANG: C.UTF-8
|
||||
|
||||
test_template: &DEFAULT_TEST_SETTINGS
|
||||
# don't cancel the task execution if it's master or a release branch
|
||||
auto_cancellation: $CIRRUS_BRANCH != 'master' && $CIRRUS_BRANCH !=~ 'v\d+\.\d+.*'
|
||||
|
||||
test_freebsd_task:
|
||||
<<: *DEFAULT_TEST_SETTINGS
|
||||
|
||||
name: FreeBSD 12.1
|
||||
alias: FreeBSD Stable
|
||||
|
||||
freebsd_instance:
|
||||
image_family: freebsd-12-1
|
||||
cpu: 8
|
||||
memory: 7424Mi
|
||||
|
||||
env:
|
||||
CHECK_REPRODUCIBLE: true
|
||||
LC_ALL: en_US.UTF-8
|
||||
|
||||
install_script:
|
||||
- pkg install -y erlang git gmake
|
||||
- rm -rf .git
|
||||
- gmake compile
|
||||
|
||||
build_info_script: bin/elixir --version
|
||||
|
||||
test_formatted_script:
|
||||
- gmake test_formatted &&
|
||||
echo "All Elixir source code files are properly formatted."
|
||||
|
||||
dialyzer_script: dialyzer -pa lib/elixir/ebin --build_plt --output_plt elixir.plt --apps lib/elixir/ebin/elixir.beam lib/elixir/ebin/Elixir.Kernel.beam
|
||||
|
||||
test_erlang_script: gmake test_erlang
|
||||
|
||||
test_elixir_script: gmake test_elixir
|
||||
|
||||
check_reproducible_script: |
|
||||
if [ -n "$CHECK_REPRODUCIBLE" ]; then
|
||||
gmake check_reproducible
|
||||
else
|
||||
echo "The reproducibility of the build is only checked in the last stable Erlang/OTP version."
|
||||
fi
|
||||
@@ -1,3 +1 @@
|
||||
lib/elixir/test/elixir/fixtures/*.txt text eol=lf
|
||||
*.ex diff=elixir
|
||||
*.exs diff=elixir
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on: [pull_request, push]
|
||||
|
||||
env:
|
||||
ELIXIR_ASSERT_TIMEOUT: 2000
|
||||
ELIXIRC_OPTS: "--warnings-as-errors"
|
||||
ERLC_OPTS: "warnings_as_errors"
|
||||
LANG: C.UTF-8
|
||||
|
||||
jobs:
|
||||
test_linux:
|
||||
name: Linux, ${{ matrix.otp_release }}, Ubuntu 16.04
|
||||
continue-on-error: ${{ matrix.development }}
|
||||
strategy:
|
||||
matrix:
|
||||
otp_release: ['OTP-23.0', 'OTP-22.3', 'OTP-22.0', 'OTP-21.3.8', 'OTP-21.0']
|
||||
development: [false]
|
||||
include:
|
||||
- otp_release: master
|
||||
development: true
|
||||
- otp_release: maint
|
||||
development: true
|
||||
runs-on: ubuntu-16.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Install Erlang/OTP
|
||||
run: |
|
||||
cd $RUNNER_TEMP
|
||||
wget -O otp.tar.gz https://repo.hex.pm/builds/otp/ubuntu-14.04/${{ matrix.otp_release }}.tar.gz
|
||||
mkdir -p otp
|
||||
tar zxf otp.tar.gz -C otp --strip-components=1
|
||||
otp/Install -minimal $(pwd)/otp
|
||||
echo "::add-path::$(pwd)/otp/bin"
|
||||
- name: Compile Elixir
|
||||
run: |
|
||||
rm -rf .git
|
||||
make compile
|
||||
- name: Build info
|
||||
run: bin/elixir --version
|
||||
- name: Check format
|
||||
run: make test_formatted && echo "All Elixir source code files are properly formatted."
|
||||
- name: Dyalizer
|
||||
run: dialyzer -pa lib/elixir/ebin --build_plt --output_plt elixir.plt --apps lib/elixir/ebin/elixir.beam lib/elixir/ebin/Elixir.Kernel.beam
|
||||
- name: Erlang test suite
|
||||
run: make test_erlang
|
||||
- name: Elixir test suite
|
||||
run: make test_elixir
|
||||
- name: Check reproducible builds
|
||||
run: taskset 1 make check_reproducible
|
||||
if: matrix.otp_release == 'OTP-23.0'
|
||||
|
||||
test_windows:
|
||||
name: Windows, OTP-${{ matrix.otp_release }}, Windows Server 2019
|
||||
strategy:
|
||||
matrix:
|
||||
otp_release: ['22.0']
|
||||
runs-on: windows-2019
|
||||
steps:
|
||||
- name: Configure Git
|
||||
run: git config --global core.autocrlf input
|
||||
- uses: actions/checkout@v1
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Cache Erlang/OTP package
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: C:\Users\runneradmin\AppData\Local\Temp\chocolatey\erlang
|
||||
key: OTP-${{ matrix.otp_release }}-windows-2019
|
||||
- name: Install Erlang/OTP
|
||||
run: choco install -y erlang --version ${{ matrix.otp_release }}
|
||||
- name: Compile Elixir
|
||||
run: |
|
||||
remove-item '.git' -recurse -force
|
||||
make compile
|
||||
- name: Build info
|
||||
run: bin/elixir --version
|
||||
- name: Check format
|
||||
run: make test_formatted && echo "All Elixir source code files are properly formatted."
|
||||
- name: Erlang test suite
|
||||
run: make --keep-going test_erlang
|
||||
- name: Elixir test suite
|
||||
run: make --keep-going test_elixir
|
||||
|
||||
check_posix_compliant:
|
||||
name: Check POSIX-compliant
|
||||
runs-on: ubuntu-16.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Install Shellcheck
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y shellcheck
|
||||
- name: Check POSIX-compliant
|
||||
run: |
|
||||
shellcheck -e SC2039,2086 bin/elixir && echo "bin/elixir is POSIX compliant"
|
||||
shellcheck bin/elixirc && echo "bin/elixirc is POSIX compliant"
|
||||
shellcheck bin/iex && echo "bin/iex is POSIX compliant"
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
language: bash
|
||||
sudo: false
|
||||
|
||||
env:
|
||||
global:
|
||||
- ELIXIR_ASSERT_TIMEOUT=2000
|
||||
matrix:
|
||||
- OTP_RELEASE=OTP-22.0 CHECK_REPRODUCIBLE=true CHECK_POSIX_COMPLIANT=true
|
||||
- OTP_RELEASE=OTP-21.3.8
|
||||
- OTP_RELEASE=OTP-21.2
|
||||
- OTP_RELEASE=OTP-21.1
|
||||
- OTP_RELEASE=OTP-21.0
|
||||
- OTP_RELEASE=OTP-20.3
|
||||
- OTP_RELEASE=OTP-20.2
|
||||
- OTP_RELEASE=OTP-20.1
|
||||
- OTP_RELEASE=OTP-20.0
|
||||
- OTP_RELEASE=maint
|
||||
- OTP_RELEASE=master
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
allow_failures:
|
||||
- env: OTP_RELEASE=maint
|
||||
- env: OTP_RELEASE=master
|
||||
|
||||
install:
|
||||
- wget -O otp.tar.gz https://repo.hex.pm/builds/otp/ubuntu-14.04/${OTP_RELEASE}.tar.gz
|
||||
- mkdir -p otp
|
||||
- tar zxf otp.tar.gz -C otp --strip-components=1
|
||||
- otp/Install -minimal $(pwd)/otp
|
||||
- PATH=$(pwd)/otp/bin:$PATH
|
||||
|
||||
script:
|
||||
- rm -rf .git
|
||||
- ELIXIRC_OPTS="--warnings-as-errors" ERLC_OPTS="+warning_as_errors" make compile
|
||||
- make test
|
||||
- dialyzer -pa lib/elixir/ebin --build_plt --output_plt elixir.plt --apps lib/elixir/ebin/elixir.beam lib/elixir/ebin/Elixir.Kernel.beam
|
||||
|
||||
# Check for reproducible builds only in the latest OTP release
|
||||
- if [ -n "$CHECK_REPRODUCIBLE" ]; then make check_reproducible; fi
|
||||
|
||||
# Check for POSIX compliant shell scripts
|
||||
- if [ -n "$CHECK_POSIX_COMPLIANT" ]; then
|
||||
shellcheck -e SC2039,2086 bin/elixir && echo "bin/elixir is POSIX compliant";
|
||||
shellcheck bin/elixirc && echo "bin/elixirc is POSIX compliant";
|
||||
shellcheck bin/iex && echo "bin/iex is POSIX compliant";
|
||||
fi
|
||||
+196
-350
@@ -1,449 +1,295 @@
|
||||
# Changelog for Elixir v1.11
|
||||
# Changelog for Elixir v1.9
|
||||
|
||||
Over the last releases, the Elixir team has been focusing on the compiler, both in terms of catching more mistakes at compilation time and making it faster. Elixir v1.11 has made excellent progress on both fronts. This release also includes many other goodies, such as tighter Erlang integration, support for more guard expressions, built-in datetime formatting, and other calendar enhancements.
|
||||
## Releases
|
||||
|
||||
## Tighter Erlang integration
|
||||
The main feature in Elixir v1.9 is the addition of releases. A release is a self-contained directory that consists of your application code, all of its dependencies, plus the whole Erlang Virtual Machine (VM) and runtime. Once a release is assembled, it can be packaged and deployed to a target as long as the target runs on the same operating system (OS) distribution and version as the machine running the `mix release` command.
|
||||
|
||||
Following Elixir v1.10, we have further integrated with Erlang's new logger by adding four new log levels: `notice`, `critical`, `alert`, and `emergency`, matching all log levels found in the Syslog standard. The `Logger` module now supports structured logging by passing maps and keyword lists to its various functions. It is also possible to specify the log level per module, via the `Logger.put_module_level/2` function. Log levels per application will be added in future releases.
|
||||
You can start a new project and assemble a release for it in three easy steps:
|
||||
|
||||
IEx also has been improved to show the documentation for Erlang modules directly from your Elixir terminal. This works with Erlang/OTP 23+ and requires Erlang modules to have been compiled with documentation chunks.
|
||||
$ mix new my_app
|
||||
$ cd my_app
|
||||
$ MIX_ENV=prod mix release
|
||||
|
||||
## Compiler checks: application boundaries
|
||||
A release will be assembled in `_build/prod/rel/my_app`. Inside the release, there will be a `bin/my_app` file which is the entry point to your system. It supports multiple commands, such as:
|
||||
|
||||
Elixir v1.11 builds on top of the recently added compilation tracers to track application boundaries. From this release, Elixir will warn if you invoke a function from an existing module but this module does not belong to any of your listed dependencies.
|
||||
* `bin/my_app start`, `bin/my_app start_iex`, `bin/my_app restart`, and `bin/my_app stop` - for general management of the release
|
||||
|
||||
These two conditions may seem contradictory. After all, if a module is available, it must have come from a dependency. This is not true in two scenarios:
|
||||
* `bin/my_app rpc COMMAND` and `bin/my_app remote` - for running commands on the running system or to connect to the running system
|
||||
|
||||
* Modules from Elixir and Erlang/OTP are always available - even if their applications are not listed as a dependency
|
||||
* `bin/my_app eval COMMAND` - to start a fresh system that runs a single command and then shuts down
|
||||
|
||||
* In an umbrella project, because all child applications are compiled within the same VM, you may have a module from a sibling project available, even if you don't depend on said sibling
|
||||
* `bin/my_app daemon` and `bin/my_app daemon_iex` - to start the system as a daemon on Unix-like systems
|
||||
|
||||
This new compiler check makes sure that all modules that you invoke are listed as part of your dependencies, emitting a warning like below otherwise:
|
||||
* `bin/my_app install` - to install the system as a service on Windows machines
|
||||
|
||||
```text
|
||||
:ssl.connect/2 defined in application :ssl is used by the current
|
||||
application but the current application does not directly depend
|
||||
on :ssl. To fix this, you must do one of:
|
||||
### Why releases?
|
||||
|
||||
1. If :ssl is part of Erlang/Elixir, you must include it under
|
||||
:extra_applications inside "def application" in your mix.exs
|
||||
Releases allow developers to precompile and package all of their code and the runtime into a single unit. The benefits of releases are:
|
||||
|
||||
2. If :ssl is a dependency, make sure it is listed under "def deps"
|
||||
in your mix.exs
|
||||
* Code preloading. The VM has two mechanisms for loading code: interactive and embedded. By default, it runs in the interactive mode which dynamically loads modules when they are used for the first time. The first time your application calls `Enum.map/2`, the VM will find the `Enum` module and load it. There’s a downside. When you start a new server in production, it may need to load many other modules, causing the first requests to have an unusual spike in response time. Releases run in embedded mode, which loads all available modules upfront, guaranteeing your system is ready to handle requests after booting.
|
||||
|
||||
3. In case you don't want to add a requirement to :ssl, you may
|
||||
optionally skip this warning by adding [xref: [exclude: :ssl]
|
||||
to your "def project" in mix.exs
|
||||
```
|
||||
* Configuration and customization. Releases give developers fine grained control over system configuration and the VM flags used to start the system.
|
||||
|
||||
This comes with extra benefits in umbrella projects, as it requires applications to depend on the siblings they depend on, which will fail if there are any cyclic dependencies.
|
||||
* Self-contained. A release does not require the source code to be included in your production artifacts. All of the code is precompiled and packaged. Releases do not even require Erlang or Elixir in your servers, as they include the Erlang VM and its runtime by default. Furthermore, both Erlang and Elixir standard libraries are stripped to bring only the parts you are actually using.
|
||||
|
||||
## Compiler checks: data constructors
|
||||
* Multiple releases. You can assemble different releases with different configuration per application or even with different applications altogether.
|
||||
|
||||
In Elixir v1.11, the compiler also tracks structs and maps fields across a function body. For example, imagine you wanted to write this code:
|
||||
### Hooks and Configuration
|
||||
|
||||
def drive?(%User{age: age}), do: age >= 18
|
||||
Releases also provide built-in hooks for configuring almost every need of the production system:
|
||||
|
||||
If there is either a typo on the `:age` field or the `:age` field was not yet defined, the compiler will fail accordingly. However, if you wrote this code:
|
||||
* `config/config.exs` (and `config/prod.exs`) - provides build-time application configuration, which is executed when the release is assembled
|
||||
|
||||
def drive?(%User{} = user), do: user.age >= 18
|
||||
* `config/releases.exs` - provides runtime application configuration. It is executed every time the release boots and is further extensible via config providers
|
||||
|
||||
The compiler would not catch the missing field and an error would only be raised at runtime. With v1.11, Elixir will track the usage of all maps and struct fields within the same function, emitting warnings for cases like above:
|
||||
* `rel/vm.args.eex` - a template file that is copied into every release and provides static configuration of the Erlang Virtual Machine and other runtime flags
|
||||
|
||||
```text
|
||||
warning: undefined field `age` in expression:
|
||||
* `rel/env.sh.eex` and `rel/env.bat.eex` - template files that are copied into every release and executed on every command to set up environment variables, including ones specific to the VM, and the general environment
|
||||
|
||||
# example.exs:7
|
||||
user.age
|
||||
We have written extensive documentation on releases, so we recommend checking it out for more information.
|
||||
|
||||
expected one of the following fields: name, address
|
||||
## Configuration overhaul
|
||||
|
||||
where "user" was given the type %User{} in:
|
||||
A new `Config` module has been added to Elixir. The previous configuration API, `Mix.Config`, was part of the Mix build tool. But since releases provide runtime configuration and Mix is not included in releases, we ported the `Mix.Config` API to Elixir. In other words, `use Mix.Config` has been soft-deprecated in favor of `import Config`.
|
||||
|
||||
# example.exs:7
|
||||
%User{} = user
|
||||
Another important change related to configuration is that `mix new` will no longer generate a `config/config.exs` file. [Relying on configuration is undesired for most libraries](https://hexdocs.pm/elixir/library-guidelines.html#avoid-application-configuration) and the generated config files pushed library authors in the wrong direction. Furthermore, `mix new --umbrella` will no longer generate a configuration for each child app, instead all configuration should be declared in the umbrella root. That's how it has always behaved, we are now making it explicit.
|
||||
|
||||
Conflict found at
|
||||
example.exs:7: Check.drive?/1
|
||||
```
|
||||
## Other enhancements
|
||||
|
||||
The compiler also checks binary constructors. Consider you have to send a string over the wire with length-based encoding, where the string is prefixed by its length, up to 4MBs. Your initial attempt may be this:
|
||||
There are many other enhancements. The Elixir CLI got a handful of new options in order to best support releases. `Logger` now computes its sync/async/discard thresholds in a decentralized fashion, reducing contention. `EEx` templates support more complex expressions than before. Finally, there is a new `~U` sigil for working with UTC DateTimes as well as new functions in the `File`, `Registry`, and `System` modules.
|
||||
|
||||
def run_length(string) when is_binary(string) do
|
||||
<<byte_size(string)::32, string>>
|
||||
end
|
||||
|
||||
However, the code above has a bug. Each segment given between `<<>>` must be an integer, unless specified otherwise. With Elixir v1.11, the compiler will let you know so:
|
||||
|
||||
```text
|
||||
warning: incompatible types:
|
||||
|
||||
binary() !~ integer()
|
||||
|
||||
in expression:
|
||||
|
||||
<<byte_size(string)::integer()-size(32), string>>
|
||||
|
||||
where "string" was given the type integer() in:
|
||||
|
||||
# foo.exs:4
|
||||
<<byte_size(string)::integer()-size(32), string>>
|
||||
|
||||
where "string" was given the type binary() in:
|
||||
|
||||
# foo.exs:3
|
||||
is_binary(string)
|
||||
|
||||
HINT: all expressions given to binaries are assumed to be of type integer()
|
||||
unless said otherwise. For example, <<expr>> assumes "expr" is an integer.
|
||||
Pass a modifier, such as <<expr::float>> or <<expr::binary>>, to change the
|
||||
default behaviour.
|
||||
|
||||
Conflict found at
|
||||
foo.exs:4: Check.run_length/1
|
||||
```
|
||||
|
||||
Which can be fixed by adding `::binary` to the second component:
|
||||
|
||||
def run_length(string) when is_binary(string) do
|
||||
<<byte_size(string)::32, string::binary>>
|
||||
end
|
||||
|
||||
While some of those warnings could be automatically fixed by the compiler, future versions will also perform those checks across functions and potentially across modules, where automatic fixes wouldn't be desired (nor possible).
|
||||
|
||||
## Compilation time improvements
|
||||
|
||||
Elixir v1.11 features many improvements to how the compiler tracks file dependencies, such that touching one file causes less files to be recompiled. In previous versions, Elixir tracked three types of dependencies:
|
||||
|
||||
* compile time dependencies - if A depends on B at compile time, such as by using a macro, whenever B changes, A is recompiled
|
||||
* struct dependencies - if A depends on B's struct, whenever B's struct definition changed, A is recompiled
|
||||
* runtime dependencies - if A depends on B at runtime, A is never recompiled
|
||||
|
||||
However, because dependencies are transitive, if A depends on B at compile time and B depends on C at runtime, A would depend on C at compile time. Therefore, it is very important to reduce the amount of compile time dependencies.
|
||||
|
||||
Elixir v1.11 replaces "struct dependencies" by "exports dependencies". In other words, if A depends on B, whenever B public's interface changes, A is recompiled. B's public interface is made by its struct definition and all of its public functions and macros.
|
||||
|
||||
This change allows us to mark `import`s and `require`s as "exports dependencies" instead of "compile time" dependencies. This simplifies the dependency graph considerably. For example, [in the Hex.pm project](https://github.com/hexpm/hexpm), changing the `user.ex` file in Elixir v1.10 would emit this:
|
||||
|
||||
```text
|
||||
$ touch lib/hexpm/accounts/user.ex && mix compile
|
||||
Compiling 90 files (.ex)
|
||||
```
|
||||
|
||||
In Elixir v1.11, we now get:
|
||||
|
||||
```text
|
||||
$ touch lib/hexpm/accounts/user.ex && mix compile
|
||||
Compiling 16 files (.ex)
|
||||
```
|
||||
|
||||
To make things even better, Elixir v1.11 also introduces a more granular file tracking for path dependencies. In previous versions, a module from a path dependency would always be treated as a compile time dependency. This often meant that if you have an umbrella project, changing an application would cause many modules in sibling applications to recompile. Fortunately, Elixir v1.11 will tag modules from dependencies as exports if appropriate, yielding dramatic improvements to those using path dependencies.
|
||||
|
||||
To round up the list of compiler enhancements, the `--profile=time` option added in Elixir v1.10 now also includes the time to compile each individual file. For example, in the Plug project, one can now get:
|
||||
|
||||
```text
|
||||
[profile] lib/plug/conn.ex compiled in 935ms
|
||||
[profile] lib/plug/ssl.ex compiled in 147ms (plus 744ms waiting)
|
||||
[profile] lib/plug/static.ex compiled in 238ms (plus 654ms waiting)
|
||||
[profile] lib/plug/csrf_protection.ex compiled in 237ms (plus 790ms waiting)
|
||||
[profile] lib/plug/debugger.ex compiled in 719ms (plus 947ms waiting)
|
||||
[profile] Finished compilation cycle of 60 modules in 1802ms
|
||||
[profile] Finished group pass check of 60 modules in 75ms
|
||||
```
|
||||
|
||||
While implementing those features, we have also made the `--long-compilation-threshold` flag more precise. In previous versions, `--long-compilation-threshold` would consider both the time a file spent to compile and the time spent waiting on other files. In Elixir v1.11, it considers only the compilation time. This means less false positives and you can now effectively get all files that take longer than 2s to compile by passing `--long-compilation-threshold 2`.
|
||||
|
||||
## `mix xref graph` improvements
|
||||
|
||||
To bring visibility to the compiler tracking improvements described in the previous section, we have also added new features to `mix xref`. `mix xref` is a task that describes cross-references between files in your projects. The `mix xref graph` subsection focuses on the dependency graph between them.
|
||||
|
||||
First we have made the existing `--label` flag to consider transitive dependencies. Using `--sink FILE` and `--label compile` can be a powerful combo to find out which files will change whenever the given `FILE` changes. For example, in the Hex.pm project, we get:
|
||||
|
||||
```text
|
||||
$ mix xref graph --sink lib/hexpm/accounts/user.ex --label compile
|
||||
lib/hexpm/billing/hexpm.ex
|
||||
└── lib/hexpm/billing/billing.ex (compile)
|
||||
lib/hexpm/billing/local.ex
|
||||
└── lib/hexpm/billing/billing.ex (compile)
|
||||
lib/hexpm/emails/bamboo.ex
|
||||
├── lib/hexpm/accounts/email.ex (compile)
|
||||
└── lib/hexpm/accounts/user.ex (compile)
|
||||
lib/hexpm/emails/emails.ex
|
||||
└── lib/hexpm_web/views/email_view.ex (compile)
|
||||
lib/hexpm_web/controllers/api/docs_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/key_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/organization_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/organization_user_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/owner_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/package_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/release_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/repository_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/api/retirement_controller.ex
|
||||
└── lib/hexpm_web/controllers/auth_helpers.ex (compile)
|
||||
lib/hexpm_web/controllers/blog_controller.ex
|
||||
└── lib/hexpm_web/views/blog_view.ex (compile)
|
||||
lib/hexpm_web/endpoint.ex
|
||||
├── lib/hexpm_web/plug_parser.ex (compile)
|
||||
└── lib/hexpm_web/session.ex (compile)
|
||||
```
|
||||
|
||||
All the files at the root will recompile if `lib/hexpm/accounts/user.ex` changes. Their children describe the *why*. For example, the `repository_controller.ex` file will recompile if user changes because it has a compile time dependency on `auth_helpers.ex`, which depends on `user.ex`. This indirect compile time dependency is often the source of recompilations and Elixir v1.11 now makes it trivial to spot them, so they can be eventually addressed.
|
||||
|
||||
Another improvement to `mix xref graph` is the addition of `--format cycles`, which will print all cycles in your compilation dependency graph. A `--min-cycle-size` flag can be used if you want to discard short cycles.
|
||||
|
||||
## `config/runtime.exs` and `mix app.config`
|
||||
|
||||
Elixir v1.9 introduced a new configuration file, specific to releases, called `config/releases.exs`. A release is a self-contained artifact with the Erlang VM, Elixir and your application, ready to run in production.
|
||||
|
||||
The addition of `config/releases.exs` has been a very useful one but, unfortunately, it applies only to releases. Developers not using releases must use the `config/config.exs` file, which often loaded too early at compilation time. For any dynamic configuration, developers had to resort to third-party tools or workarounds to achieve the desired results.
|
||||
|
||||
Elixir v1.11 addresses this issue by introducing a new configuration file, called `config/runtime.exs`. This new configuration file is loaded exactly before your application starts, when the code is already fully compiled. It is loaded in development, test, and production, regardless if you are using Mix or releases. Therefore it provides a unified API for runtime configuration in Elixir.
|
||||
|
||||
`config/runtime.exs` works the same as any other configuration file. However, given `config/runtime.exs` is meant to run with or without Mix, developers must not use `Mix.env()` or `Mix.target()` in `config/runtime.exs`. Instead, they must use the new `config_env()` and `config_target()`, which have been added to the `Config` module.
|
||||
|
||||
While `config/releases.exs` will continue to be supported, developers can migrate to `config/runtime.exs` without loss of functionality. For example, a `config/releases.exs` file such as this one
|
||||
|
||||
```elixir
|
||||
# config/releases.exs
|
||||
import Config
|
||||
|
||||
config :foo, ...
|
||||
config :bar, ...
|
||||
```
|
||||
|
||||
could run as is as `config/runtime.exs`. However, given `config/runtime.exs` runs in all environments, you may want to restrict part of your configuration to the `:prod` environment:
|
||||
|
||||
```elixir
|
||||
# config/runtime.exs
|
||||
import Config
|
||||
|
||||
if config_env() == :prod do
|
||||
config :foo, ...
|
||||
config :bar, ...
|
||||
end
|
||||
```
|
||||
|
||||
If both files are available, releases will pick the now preferred `config/runtime.exs` instead of `config/releases.exs`.
|
||||
|
||||
To wrap it all up, `Mix` also includes a new task called `mix app.config`. This task loads all applications and configures them, without starting them. Whenever you write your own Mix tasks, you will typically want to invoke either `mix app.start` or `mix app.config` before running your own code. Which one is better depends if you want your applications running or only configured.
|
||||
|
||||
## Other improvements
|
||||
|
||||
Elixir v1.11 adds the `is_struct/2`, `is_exception/1`, and `is_exception/2` guards. It also adds support for the `map.field` syntax in guards.
|
||||
|
||||
The Calendar module ships with a new `Calendar.strftime/3` function, which provides datetime formatting based on the `strftime` format. The `Date` module got new functions for working with weeks and months, such as `Date.beginning_of_month/1` and `Date.end_of_week/2`. Finally, all calendar types got conversion functions from and to gregorian timestamps, such as `Date.from_gregorian_days/2` and `NaiveDateTime.to_gregorian_seconds/1`.
|
||||
|
||||
Mix also includes two new tasks: `mix app.config`, for application runtime configuration, and `mix test.coverage`, which generates aggregated coverage reports for umbrella projects and for test suites partitioned across processes.
|
||||
|
||||
## v1.11.2 (2020-11-03)
|
||||
## v1.9.4 (2019-11-05)
|
||||
|
||||
### 1. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Do not crash when getting docs for missing `erts` appdir
|
||||
* [Kernel] Raise meaningful error if `:erlang.is_record` is used in guards
|
||||
* [Kernel] Prune tracers when fetching `__ENV__` inside functions
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix] Fix regression where aliases could not call themselves recursively
|
||||
* [mix compile] Do not discard tracers that are set programatically
|
||||
* [mix local.hex] Remove invalid deprecation warning on `mix local.hex` command
|
||||
|
||||
## v1.11.1 (2020-10-16)
|
||||
## v1.9.3 (2019-11-05)
|
||||
|
||||
### 1. Bug fixes
|
||||
Note this release deprecates the use of URLs on `mix archive.install`, `mix escript.install`, and `mix local.rebar`. Support for passing URLs to said commands will be fully removed on Elixir v1.10, as they are unsafe. Thanks to Bram Verburg for the report and for providing a fix.
|
||||
|
||||
The alternative is straight-forward: you can simply download the artifact via the command line and then invoke the command with a file system path. For example, instead of:
|
||||
|
||||
$ mix archive.install https://example.org/installer.ez
|
||||
|
||||
You can execute on Unix (Linux, MacOS X):
|
||||
|
||||
$ wget https://example.org/installer.ez
|
||||
$ mix archive.install installer.ez
|
||||
|
||||
or
|
||||
|
||||
$ curl -o installer.ez https://example.org/installer.ez
|
||||
$ mix archive.install installer.ez
|
||||
|
||||
On Windows (Win7 or later):
|
||||
|
||||
> powershell -Command "Invoke-WebRequest https://example.org/installer.ez -OutFile installer.ez"
|
||||
> mix archive.install installer.ez
|
||||
|
||||
or
|
||||
|
||||
> powershell -Command "(New-Object Net.WebClient).DownloadFile('https://example.org/installer.ez', 'installer.ez')"
|
||||
> mix archive.install installer.ez
|
||||
|
||||
Note that, if you are a library author, consider providing installable escripts and archives through Hex, such as Phoenix:
|
||||
|
||||
$ mix archive.install hex phx_new
|
||||
|
||||
Installations through Hex are always safe and they come with version management and all other benefits from Hex too.
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix release] Add :tar option for releases to create a tarball
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix release] Use `default_release` option when name is not given
|
||||
* [mix release] Make release's boot script contents deterministic
|
||||
|
||||
### 3. Deprecations
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix archive.install] Warn when installing from URI
|
||||
* [mix escript.install] Warn when installing from URI
|
||||
* [mix local.rebar] Warn when installing from URI
|
||||
|
||||
## v1.9.2 (2019-10-12)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix release] Allow `{:from_app, app_name}` as a version for releases
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Ignore tracers if lexical tracker is dead or explicitly nil when evaling code with an environment
|
||||
* [GenServer] Do not show warning when using `super` in `GenServer.child_spec/1`
|
||||
* [Kernel] Do not crash when :reduce is set to `nil` in comprehensions
|
||||
* [Kernel] Fix a scenario where undefined function warnings were not being emitted
|
||||
* [Kernel] Ensure compilation works for a variable named `super`
|
||||
* [Kernel] Ensure capture operator of a local function expands correctly inside a macro
|
||||
* [Regex] Ensure dynamic recompilation of regexes considers options. This fixes an issue where parsing the protocol in `URI.parse/1` seemingly looked case sensitive when running Elixir precompiled on another machine
|
||||
|
||||
#### IEx
|
||||
#### Mix
|
||||
|
||||
* [IEx.Helpers] Properly handle tags inside typespec when showing Erlang docs
|
||||
* [mix release] Use `Base.encode32` when generating cookie to avoid unsafe chars
|
||||
* [mix release] Fix `install` command on Windows
|
||||
* [mix release] Quote executable path on Windows to ensure it works on directories with spaces
|
||||
|
||||
## v1.9.1 (2019-07-18)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix format] Print relative paths in `--check-formatted` output
|
||||
* [mix release] Support included applications
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Fix formatter wrongly removing nested parens in nested calls
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Do not deadlock Logger if handler crashes on sync mode
|
||||
* [Logger] Do not crash translator on poorly formatted supervisor names
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix] Add inet6 fallback to Mix usage of httpc
|
||||
* [mix compile.app] Do not list apps that do not match the current target
|
||||
* [mix compile] Raise readable error for mismatched sources during compilation
|
||||
* [mix release] Preserve UTF8 encoding in release config files
|
||||
|
||||
## v1.11.0 (2020-10-06)
|
||||
## v1.9.0 (2019-06-24)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### EEx
|
||||
|
||||
* [EEx] Track column information in EEx templates when enabled in the compiler
|
||||
* [EEx] Show column information in EEx error messages
|
||||
* [EEx] Support `:indentation` option when compiling EEx templates for proper column tracking
|
||||
* [EEx] Allow more complex mixed expressions when tokenizing
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Access] Add `Access.at!/1`
|
||||
* [Calendar] Add `Calendar.strftime/3` for datetime formatting
|
||||
* [Calendar] Add linear integer representations to Calendar modules: `Date.from_gregorian_days/2`, `Date.to_gregorian_days/1`, `NaiveDateTime.from_gregorian_seconds/3`, `NaiveDateTime.to_gregorian_seconds/1`, `Time.from_seconds_after_midnight/1`, and `Time.to_seconds_after_midnight/1`
|
||||
* [Calendar] Add `new!` to Date/Time/NaiveDateTime/DateTime (`new` has also been added to `DateTime` for completeness)
|
||||
* [Calendar] Support custom starting day of the week in `Date.day_of_week/2`
|
||||
* [Calendar] Add `Date.beginning_of_month/1` and `Date.end_of_month/1`
|
||||
* [Calendar] Add `Date.beginning_of_week/2` and `Date.end_of_week/2`
|
||||
* [Code] Add `:column` to `Code.string_to_quoted*/2`
|
||||
* [Code] Add `Code.can_await_module_compilation?/0` to check if the parallel compiler is enabled and it can await for other modules to be compiled
|
||||
* [Config] Support `config_env/0` and `config_target/0` in `config` files
|
||||
* [Config] Allow `import_config` to be disabled for some configuration files
|
||||
* [Enum] Allow a sorting function on `Enum.min_max_by/3,4`, including the new `compare/2` conventions
|
||||
* [Kernel] Add `is_struct/2` guard
|
||||
* [Kernel] Add `is_exception/1` and `is_exception/2` guards
|
||||
* [Kernel] Support `map.field` syntax in guards
|
||||
* [Kernel] Add `+++` and `---` with right associativity to the list of custom operators
|
||||
* [Kernel] Warn if a variable that looks like a compiler variable (such as `__MODULE__`) is unused
|
||||
* [Kernel.ParallelCompiler] Report individual file compilation times when `profile: :time` is given
|
||||
* [Kernel.ParallelCompiler] Improve precision of `:long_compilation_threshold` so it takes only compilation times into account (and not waiting times)
|
||||
* [Registry] Add `Registry.delete_meta/2`
|
||||
* [Task] Add `Task.await_many/2`
|
||||
* [Access] Allow `Access.at/1` to handle negative index
|
||||
* [CLI] Add support for `--boot`, `--boot-var`, `--erl-config`, `--pipe-to`, `--rpc-eval`, and `--vm-args` options
|
||||
* [Code] Add `static_atom_encoder` option to `Code.string_to_quoted/2`
|
||||
* [Code] Support `:force_do_end_blocks` on `Code.format_string!/2` and `Code.format_file!/2`
|
||||
* [Code] Do not raise on deadlocks on `Code.ensure_compiled/1`
|
||||
* [Config] Add `Config`, `Config.Reader`, and `Config.Provider` modules for working with configuration
|
||||
* [File] Add `File.rename!/2`
|
||||
* [Inspect] Add `:inspect_fun` and `:custom_options` to `Inspect.Opts`
|
||||
* [Kernel] Add `~U` sigil for UTC date times
|
||||
* [Kernel] Optimize `&super/arity` and `&super(&1)`
|
||||
* [Kernel] Optimize generated code for `with` with a catch-all clause
|
||||
* [Kernel] Validate `__struct__` key in map returned by `__struct__/0,1`
|
||||
* [Module] Add `Module.get_attribute/3`
|
||||
* [Protocol] Improve `Protocol.UndefinedError` messages to also include the type that was attempted to dispatch on
|
||||
* [Protocol] Optimize performance of dynamic dispatching for non-consolidated protocols
|
||||
* [Record] Include field names in generated type for records
|
||||
* [Regex] Automatically recompile regexes
|
||||
* [Registry] Add `Registry.select/2`
|
||||
* [System] Add `System.restart/0`, `System.pid/0` and `System.no_halt/1`
|
||||
* [System] Add `System.get_env/2`, `System.fetch_env/1`, and `System.fetch_env!/1`
|
||||
* [System] Support `SOURCE_DATE_EPOCH` for reproducible builds
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit] Add support for coloring on Windows 10 consoles/shells
|
||||
* [ExUnit] Add `ExUnit.fetch_test_supervisor/0`
|
||||
* [ExUnit] Add `@tag :tmp_dir` support to ExUnit. The temporary directory is automatically created and pruned before each test
|
||||
* [ExUnit] Add file and line to ExUnit's `--trace`
|
||||
* [ExUnit.Assertion] Allow receive timeouts to be computed at runtime
|
||||
* [ExUnit.Case] Add `register_test/6` to speed up compilation of custom tests
|
||||
* [ExUnit.Doctest] Allow users to add tags to doctests
|
||||
* [ExUnit] Allow multiple `:exclude` on configuration/CLI
|
||||
* [ExUnit.DocTest] No longer wrap doctest errors in custom exceptions. They ended-up hiding more information than showing
|
||||
* [ExUnit.DocTest] Display the actual doctest code when doctest fails
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx] Add support for coloring on Windows 10 consoles/shells
|
||||
* [IEx.Helpers] Show docs from Erlang modules that have been compiled with the docs chunk
|
||||
* [IEx.CLI] Copy ticktime from remote node on IEx `--remsh`
|
||||
* [IEx.CLI] Automatically add a host on node given to `--remsh`
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Add `notice`, `critical`, `alert`, and `emergency` log levels
|
||||
* [Logger] Support structured logging by logging maps or keyword lists
|
||||
* [Logger] Allow level to be set per module with `Logger.put_module_level/2`
|
||||
* [Logger] Include `erl_level` in Logger's metadata
|
||||
* [Logger] Use a decentralized mode computation for Logger which allows overloads to be detected more quickly
|
||||
* [Logger] Use `persistent_term` to store configuration whenever available for performance
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix] Add `MIX_BUILD_ROOT` to config `_build` dir
|
||||
* [mix] Introduce `MIX_XDG` as a simpler mechanism to opt-in to the XDG specification
|
||||
* [mix] Allow requirements for a Mix task to be listed via the `@requirements` module attribute
|
||||
* [mix] Allow optional dependencies to be defined in `:extra_applications` and `:applications`
|
||||
* [mix app.config] Add new `mix app.config` task that compiles applications and loads runtime configuration
|
||||
* [mix archive.install] Support `--repo` option on Hex packages
|
||||
* [mix compile] Support the `__mix_recompile__?/0` callback for custom behaviour on when Mix should recompile a given module
|
||||
* [mix compile.elixir] Mark modules for path dependencies as "Export dependencies" if they changed but their public interface is the same
|
||||
* [mix compile.elixir] Track application boundaries in the Elixir compiler. If you invoke code from Erlang or Elixir standard libraries and you don't depend on the proper applications, a warning will be emitted. A warning will also be emitted if you invoke code from an umbrella sibling that you don't depend on - effectively forbidding cyclic dependencies between apps
|
||||
* [mix deps] Sort the dependencies alphabetically before printing
|
||||
* [mix deps] Use `origin/HEAD` as the default Git ref in dependencies
|
||||
* [mix deps] Redact Git `username`/`password` in output log
|
||||
* [mix deps] Support rebar3's `git_subdir` resource type
|
||||
* [mix deps.compile] Allow local deps to be skipped on `mix deps.compile`
|
||||
* [mix deps.unlock] Print which dependencies get unlocked when using the `--unused` flag
|
||||
* [mix escript.install] Support `--repo` option on Hex packages
|
||||
* [mix new] Add `@impl` to application generated by `mix new --sup`
|
||||
* [mix release] Enable overriding `sys.config` location via `RELEASE_SYS_CONFIG` env var
|
||||
* [mix release] Boot a release under configuration in interactive mode and then swap to embedded mode (if running on Erlang/OTP 23+)
|
||||
* [mix release] Add `rel_templates_path` to configure the source of template files such as "env.sh.eex", "vm.args.eex" and "overlays"
|
||||
* [mix release] Allow some chunks to be kept in the `:strip_beams` config
|
||||
* [mix test] Allow `:ignore_modules` inside `:test_coverage` option
|
||||
* [mix test.coverage] Add `mix test.coverage` that aggregates coverage results from umbrellas and OS partitioning
|
||||
* [mix xref] Make the `--label` option for `mix xref graph` transitive by default and add `--only-direct` for only direct dependencies
|
||||
* [mix xref] Add `--format cycles` support for `mix xref graph`
|
||||
* [mix xref] Add support to `mix xref graph` for using `--source` and `--sink` at the same time
|
||||
* [Mix] Follow XDG base dir specification in Mix for temporary and configuration files
|
||||
* [Mix.Generator] Add `copy_file/3`, `copy_template/4`, and `overwite?/2`
|
||||
* [Mix.Project] Add `preferred_cli_target` that works like `preferred_cli_env`
|
||||
* [mix archive.uninstall] Allow `mix archive.uninstall APP` to uninstall any installed version of APP
|
||||
* [mix new] No longer generate a `config/` directory for mix new
|
||||
* [mix release] Add support for releases
|
||||
* [mix release.init] Add templates for release configuration
|
||||
* [mix test] Allow running tests for a given umbrella app from the umbrella root with `mix test apps/APP/test`. Test failures also include the `apps/APP` prefix in the test location
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### EEx
|
||||
|
||||
* [EEx] Make trimming behaviour via the `:trim` option more consistent
|
||||
* [EEx] Consistently trim newlines when you have a single EEx expression per line on multiple lines
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Application] Warn if non-atom keys are given to `put_env`, `get_env`, `fetch_env`, and `delete_env`
|
||||
* [Code] Do not send language keyword through the `:static_atoms_encoder` in `Code.string_to_quoted`
|
||||
* [Kernel] Validate values given to `:line` in quote to avoid emitting invalid ASTs
|
||||
* [Kernel] Report the correct line number when raising inside a macro
|
||||
* [Kernel] Fix an issue where `elixirc` would not accept paths with backslash (`\`) separators on Windows
|
||||
* [Kernel] Properly parse `&//2` (i.e. the capture of the division operator)
|
||||
* [Kernel] Raise `CompileError` when trying to define reserved types
|
||||
* [Kernel] Improve compiler error message when using `|` in a `def` signature
|
||||
* [Kernel] Improve error message when trying to use invalid list operators in guards
|
||||
* [Kernel.SpecialForms] Add `|/2` to the list of special forms to avoid inconsistent behaviour on overrides
|
||||
* [Keyword] Enforce keys to be atoms in `Keyword.keys/1`
|
||||
* [Record] Keep lexical ordering when creating records
|
||||
* [Registry] Do not crash when a process with key-value has been registered using `:via` and it fails to start on `init`
|
||||
* [URI] `URI.decode_query/2` emits an empty string for parameters without values, according to [URL's living standard](https://url.spec.whatwg.org/#application/x-www-form-urlencoded) - note this behaviour is not specified in the spec implemented by the URI module, so the living standard was chosen
|
||||
* [Version] Add defaults and enforce keys in `Version` struct
|
||||
* [Code] Quote `::` in `Code.format_string!/1` to avoid ambiguity
|
||||
* [Code] Do not crash formatter on false positive sigils
|
||||
* [Enum] Ensure the first equal entry is returned by `Enum.min/2` and `Enum.max/2`
|
||||
* [Kernel] Improve error message when string interpolation is used in a guard
|
||||
* [Kernel] Properly merge and handle docs for callbacks with multiple clauses
|
||||
* [Kernel] Guarantee reproducible builds on modules with dozens of specs
|
||||
* [Kernel] Resolve `__MODULE__` accordingly in nested `defmodule` to avoid double nesting
|
||||
* [Kernel] Type variables starting with an underscore (`_foo`) should not raise compile error
|
||||
* [Kernel] Keep order of elements when macro `in/2` is expanded with a literal list on the right-hand side
|
||||
* [Kernel] Print proper location on undefined function error from dynamically generated functions
|
||||
* [Kernel] **Potentially breaking** Do not leak aliases when nesting module definitions that are fully namespaced modules. If you defined `defmodule Elixir.Foo.Bar` inside `defmodule Foo`, previous Elixir versions would automatically define an alias, but fully namespaced modules such as `Elixir.Foo.Bar` should never define or require an alias. If you were accidentally relying on this broken behaviour, your code may no longer work
|
||||
* [System] Make sure `:init.get_status/0` is set to `{:started, :started}` once the system starts
|
||||
* [Path] Do not expand `~` in `Path.expand/2` when not followed by a path separator
|
||||
* [Protocol] Ensure `debug_info` is kept in protocols
|
||||
* [Regex] Ensure inspect returns valid `~r//` expressions when they are manually compiled with backslashes
|
||||
* [Registry] Fix ETS leak in `Registry.register/2` for already registered calls in unique registries while the process is still alive
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.CaptureIO] Fix race condition where a dead capture would still be considered as active
|
||||
* [ExUnit.Diff] Do not crash when failing to eval/inspect struct
|
||||
* [ExUnit.Diff] Properly diff numbers in respect to `==` and `===` operators
|
||||
* [ExUnit] Raise error if attempting to run single line tests on multiple files
|
||||
* [ExUnit] Return proper error on duplicate child IDs on `start_supervised`
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx] Fix tokenizer emitting repeated warnings in the REPL
|
||||
* [IEx] Ensure `--dot-iex` is preserved when restarting the evaluator and after shell respawn
|
||||
* [IEx.Pry] Ensure `IEx.pry` can be triggered more than twice when invoked from the same process
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix cmd] Fix a bug where only the first --app option would be executed
|
||||
* [mix compile] Fix an issue where new protocol implementations would not propagate when running `mix compile` from an umbrella root
|
||||
* [mix deps.compile] Use `gmake` instead of `make` when compiling deps on NetBSD/DragonFlyBSD
|
||||
* [mix release] Load `.app` from dependencies path when it is a project dependency
|
||||
* [mix release] Always include "rel/overlays" in the list of overlays directories if available
|
||||
* [mix release] Change `erts/bin/erl` binary mode to `0o755`
|
||||
* [mix test] Compare to test coverage threshold inclusively
|
||||
* [IEx] Automatically shut down IEx if we receive EOF
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Print metadata for all types that implement String.Chars
|
||||
* [Logger] Don't discard Logger messages from other nodes as to leave a trail on both systems
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix compile] Ensure Erlang-based Mix compilers (erlang, leex, yecc) set valid position on diagnostics
|
||||
* [mix compile] Ensure compilation halts in an umbrella project if one of the siblings fail to compile
|
||||
* [mix deps] Raise an error if the umbrella app's dir name and `mix.exs` app name don't match
|
||||
* [mix deps.compile] Fix subcommand splitting bug in rebar3
|
||||
* [mix test] Do not consider modules that are no longer cover compiled when computing coverage report, which could lead to flawed reports
|
||||
|
||||
### 3. Soft-deprecations (no warnings emitted)
|
||||
|
||||
### Elixir
|
||||
#### Mix
|
||||
|
||||
* [Exception] `Exception.exception?/1` is deprecated in favor of `Kernel.is_exception/1`
|
||||
* [Regex] `Regex.regex?/1` is deprecated in favor of `Kernel.is_struct/2`
|
||||
|
||||
### Logger
|
||||
|
||||
* [Logger] `warn` log level is deprecated in favor of `warning`
|
||||
|
||||
### Mix
|
||||
|
||||
* [mix release] `config/releases.exs` is deprecated in favor of a more general purpose `config/runtime.exs`
|
||||
* [Mix.Config] `Mix.Config` has been deprecated in favor of the `Config` module that now ships as part of Elixir itself. Reading configuration files should now be done by the `Config.Reader` module
|
||||
|
||||
### 4. Hard-deprecations
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Supervisor] Deprecate `Supervisor.start_child/2` and `Supervisor.terminate_child/2` in favor of `DynamicSupervisor`
|
||||
* [Supervisor.Spec] Deprecate `Supervisor.Spec.worker/3` and `Supervisor.Spec.supervisor/3` in favor of the new typespecs
|
||||
* [System] Deprecate `System.stacktrace/0` in favor of `__STACKTRACE__`
|
||||
* [CLI] Deprecate `--detached` option, use `--erl "-detached"` instead
|
||||
* [Map] Deprecate Enumerable keys in `Map.drop/2`, `Map.split/2`, and `Map.take/2`
|
||||
* [String] The `:insert_replaced` option in `String.replace/4` has been deprecated. Instead you may pass a function as a replacement or use `:binary.replace/4` if you need to support earlier Elixir versions
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix.Project] Deprecate `Mix.Project.compile/2` in favor of `Mix.Task.run("compile", args)`
|
||||
* [Mix.Project] Deprecate `Mix.Project.load_paths/1` in favor of `Mix.Project.compile_path/1`
|
||||
|
||||
## v1.10
|
||||
## v1.8
|
||||
|
||||
The CHANGELOG for v1.10 releases can be found [in the v1.10 branch](https://github.com/elixir-lang/elixir/blob/v1.10/CHANGELOG.md).
|
||||
The CHANGELOG for v1.8 releases can be found [in the v1.8 branch](https://github.com/elixir-lang/elixir/blob/v1.8/CHANGELOG.md).
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
PREFIX ?= /usr/local
|
||||
TEST_FILES ?= "*_test.exs"
|
||||
SHARE_PREFIX ?= $(PREFIX)/share
|
||||
MAN_PREFIX ?= $(SHARE_PREFIX)/man
|
||||
CANONICAL := v1.11/
|
||||
ELIXIRC := bin/elixirc --ignore-module-conflict $(ELIXIRC_OPTS)
|
||||
ERLC := erlc -I lib/elixir/include
|
||||
ERL_MAKE := if [ -n "$(ERLC_OPTS)" ]; then ERL_COMPILER_OPTIONS=$(ERLC_OPTS) erl -make; else erl -make; fi
|
||||
CANONICAL := v1.9/ # master/ or vMAJOR.MINOR/
|
||||
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict $(ELIXIRC_OPTS)
|
||||
ERLC := erlc -I lib/elixir/include $(ERLC_OPTS)
|
||||
ERL := erl -I lib/elixir/include -noshell -pa lib/elixir/ebin
|
||||
GENERATE_APP := $(CURDIR)/lib/elixir/generate_app.escript
|
||||
VERSION := $(strip $(shell cat VERSION))
|
||||
@@ -21,15 +19,15 @@ GIT_TAG = $(strip $(shell head="$(call GIT_REVISION)"; git tag --points-at $$hea
|
||||
SOURCE_DATE_EPOCH_PATH = lib/elixir/tmp/ebin_reproducible
|
||||
SOURCE_DATE_EPOCH_FILE = $(SOURCE_DATE_EPOCH_PATH)/SOURCE_DATE_EPOCH
|
||||
|
||||
.PHONY: install compile erlang elixir unicode app build_plt clean_plt dialyze test check_reproducible clean clean_residual_files format install_man clean_man docs Docs.zip Precompiled.zip zips
|
||||
.PHONY: install compile erlang elixir unicode app build_plt clean_plt dialyze test check_reproducible clean clean_residual_files 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 >= 21)])' -s erlang halt | grep -q '^true'; \
|
||||
erl -noshell -eval '{V,_} = string:to_integer(erlang:system_info(otp_release)), io:fwrite("~s", [is_integer(V) and (V >= 20)])' -s erlang halt | grep -q '^true'; \
|
||||
if [ $$? != 0 ]; then \
|
||||
echo "At least Erlang/OTP 21.0 is required to build Elixir"; \
|
||||
echo "At least Erlang/OTP 20.0 is required to build Elixir"; \
|
||||
exit 1; \
|
||||
fi
|
||||
endef
|
||||
@@ -47,7 +45,7 @@ lib/$(1)/ebin/Elixir.$(2).beam: $(wildcard lib/$(1)/lib/*.ex) $(wildcard lib/$(1
|
||||
|
||||
test_$(1): compile $(1)
|
||||
@ echo "==> $(1) (ex_unit)"
|
||||
$(Q) cd lib/$(1) && ../../bin/elixir -r "test/test_helper.exs" -pr "test/**/$(TEST_FILES)";
|
||||
$(Q) cd lib/$(1) && ../../bin/elixir -r "test/test_helper.exs" -pr "test/**/*_test.exs";
|
||||
endef
|
||||
|
||||
define WRITE_SOURCE_DATE_EPOCH
|
||||
@@ -75,7 +73,7 @@ compile: erlang $(APP) elixir
|
||||
|
||||
erlang: $(PARSER)
|
||||
$(Q) if [ ! -f $(APP) ]; then $(call CHECK_ERLANG_RELEASE); fi
|
||||
$(Q) cd lib/elixir && mkdir -p ebin && $(ERL_MAKE)
|
||||
$(Q) cd lib/elixir && mkdir -p ebin && erl -make
|
||||
|
||||
$(PARSER): lib/elixir/src/elixir_parser.yrl
|
||||
$(Q) erlc -o $@ +'{verbose,true}' +'{report,true}' $<
|
||||
@@ -91,9 +89,10 @@ $(KERNEL): lib/elixir/lib/*.ex lib/elixir/lib/*/*.ex lib/elixir/lib/*/*/*.ex
|
||||
echo "==> bootstrap (compile)"; \
|
||||
$(ERL) -s elixir_compiler bootstrap -s erlang halt; \
|
||||
fi
|
||||
$(Q) $(MAKE) unicode
|
||||
@ 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) $(MAKE) app
|
||||
|
||||
app: $(APP)
|
||||
@@ -134,24 +133,21 @@ check_reproducible: compile
|
||||
$(call WRITE_SOURCE_DATE_EPOCH)
|
||||
$(Q) mkdir -p lib/elixir/tmp/ebin_reproducible/ \
|
||||
lib/eex/tmp/ebin_reproducible/ \
|
||||
lib/ex_unit/tmp/ebin_reproducible/ \
|
||||
lib/iex/tmp/ebin_reproducible/ \
|
||||
lib/logger/tmp/ebin_reproducible/ \
|
||||
lib/mix/tmp/ebin_reproducible/
|
||||
$(Q) mv lib/elixir/ebin/* lib/elixir/tmp/ebin_reproducible/
|
||||
$(Q) mv lib/eex/ebin/* lib/eex/tmp/ebin_reproducible/
|
||||
$(Q) mv lib/ex_unit/ebin/* lib/ex_unit/tmp/ebin_reproducible/
|
||||
$(Q) mv lib/iex/ebin/* lib/iex/tmp/ebin_reproducible/
|
||||
$(Q) mv lib/logger/ebin/* lib/logger/tmp/ebin_reproducible/
|
||||
$(Q) mv lib/mix/ebin/* lib/mix/tmp/ebin_reproducible/
|
||||
SOURCE_DATE_EPOCH=$(call READ_SOURCE_DATE_EPOCH) $(MAKE) compile
|
||||
$(Q) echo "Diffing..."
|
||||
$(Q) bin/elixir lib/elixir/diff.exs lib/elixir/ebin/ lib/elixir/tmp/ebin_reproducible/
|
||||
$(Q) bin/elixir lib/elixir/diff.exs lib/eex/ebin/ lib/eex/tmp/ebin_reproducible/
|
||||
$(Q) bin/elixir lib/elixir/diff.exs lib/ex_unit/ebin/ lib/ex_unit/tmp/ebin_reproducible/
|
||||
$(Q) bin/elixir lib/elixir/diff.exs lib/iex/ebin/ lib/iex/tmp/ebin_reproducible/
|
||||
$(Q) bin/elixir lib/elixir/diff.exs lib/logger/ebin/ lib/logger/tmp/ebin_reproducible/
|
||||
$(Q) bin/elixir lib/elixir/diff.exs lib/mix/ebin/ lib/mix/tmp/ebin_reproducible/
|
||||
$(Q) diff -r lib/elixir/ebin/ lib/elixir/tmp/ebin_reproducible/
|
||||
$(Q) diff -r lib/eex/ebin/ lib/eex/tmp/ebin_reproducible/
|
||||
$(Q) diff -r lib/iex/ebin/ lib/iex/tmp/ebin_reproducible/
|
||||
$(Q) diff -r lib/logger/ebin/ lib/logger/tmp/ebin_reproducible/
|
||||
$(Q) diff -r lib/mix/ebin/ lib/mix/tmp/ebin_reproducible/
|
||||
$(Q) echo "Builds are reproducible"
|
||||
|
||||
clean:
|
||||
@@ -177,16 +173,16 @@ clean_residual_files:
|
||||
#==> Documentation tasks
|
||||
|
||||
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}")
|
||||
SOURCE_REF = $(shell tag="$(call GIT_TAG)" revision="$(call GIT_REVISION)"; echo "$${tag:-$$revision}\c")
|
||||
DOCS_FORMAT = html
|
||||
COMPILE_DOCS = bin/elixir ../ex_doc/bin/ex_doc "$(1)" "$(VERSION)" "lib/$(2)/ebin" --main "$(3)" --source-url "https://github.com/elixir-lang/elixir" --source-ref "$(call SOURCE_REF)" $(call LOGO_PATH) --output doc/$(2) --canonical "https://hexdocs.pm/$(2)/$(CANONICAL)" --homepage-url "https://elixir-lang.org/docs.html" --formatter "$(DOCS_FORMAT)" $(4)
|
||||
COMPILE_DOCS = bin/elixir ../ex_doc/bin/ex_doc "$(1)" "$(VERSION)" "lib/$(2)/ebin" -m "$(3)" -u "https://github.com/elixir-lang/elixir" --source-ref "$(call SOURCE_REF)" $(call LOGO_PATH) -o doc/$(2) -n https://hexdocs.pm/$(2)/$(CANONICAL) -p https://elixir-lang.org/docs.html -f "$(DOCS_FORMAT)" $(4)
|
||||
|
||||
docs: compile ../ex_doc/bin/ex_doc docs_elixir docs_eex docs_mix docs_iex docs_ex_unit docs_logger
|
||||
|
||||
docs_elixir: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (elixir)"
|
||||
$(Q) rm -rf doc/elixir
|
||||
$(call COMPILE_DOCS,Elixir,elixir,Kernel,--config "lib/elixir/docs.exs")
|
||||
$(call COMPILE_DOCS,Elixir,elixir,Kernel,-c lib/elixir/docs.exs)
|
||||
|
||||
docs_eex: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (eex)"
|
||||
@@ -241,7 +237,6 @@ zips: Precompiled.zip Docs.zip
|
||||
|
||||
#==> Test tasks
|
||||
|
||||
# If you modify this task, please update .cirrus.yml accordingly
|
||||
test: test_formatted test_erlang test_elixir
|
||||
|
||||
test_windows: test test_taskkill
|
||||
@@ -254,19 +249,8 @@ 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)))))
|
||||
|
||||
define FORMAT
|
||||
$(Q) if [ "$(OS)" = "Windows_NT" ]; then \
|
||||
cmd //C call ./bin/mix.bat format $(1); \
|
||||
else \
|
||||
bin/elixir bin/mix format $(1); \
|
||||
fi
|
||||
endef
|
||||
|
||||
format: compile
|
||||
$(call FORMAT)
|
||||
|
||||
test_formatted: compile
|
||||
$(call FORMAT,--check-formatted)
|
||||
bin/elixir bin/mix format --check-formatted
|
||||
|
||||
test_erlang: compile $(TEST_ERLS)
|
||||
@ echo "==> elixir (eunit)"
|
||||
@@ -283,9 +267,9 @@ test_stdlib: compile
|
||||
@ echo "==> elixir (ex_unit)"
|
||||
$(Q) exec epmd & exit
|
||||
$(Q) if [ "$(OS)" = "Windows_NT" ]; then \
|
||||
cd lib/elixir && cmd //C call ../../bin/elixir.bat -r "test/elixir/test_helper.exs" -pr "test/elixir/**/$(TEST_FILES)"; \
|
||||
cd lib/elixir && cmd //C call ../../bin/elixir.bat -r "test/elixir/test_helper.exs" -pr "test/elixir/**/*_test.exs"; \
|
||||
else \
|
||||
cd lib/elixir && ../../bin/elixir -r "test/elixir/test_helper.exs" -pr "test/elixir/**/$(TEST_FILES)"; \
|
||||
cd lib/elixir && ../../bin/elixir -r "test/elixir/test_helper.exs" -pr "test/elixir/**/*_test.exs"; \
|
||||
fi
|
||||
|
||||
#==> Dialyzer tasks
|
||||
@@ -295,7 +279,7 @@ PLT = .elixir.plt
|
||||
|
||||
$(PLT):
|
||||
@ echo "==> Building PLT with Elixir's dependencies..."
|
||||
$(Q) dialyzer --output_plt $(PLT) --build_plt --apps erts kernel stdlib compiler syntax_tools parsetools tools ssl inets crypto runtime_tools ftp tftp mnesia public_key asn1 hipe sasl
|
||||
$(Q) dialyzer --output_plt $(PLT) --build_plt --apps erts kernel stdlib compiler syntax_tools parsetools tools ssl inets
|
||||
|
||||
clean_plt:
|
||||
$(Q) rm -f $(PLT)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# 
|
||||
|
||||
[](https://github.com/elixir-lang/elixir/actions?query=branch%3Amaster+workflow%3ACI) [](https://cirrus-ci.com/github/elixir-lang/elixir)
|
||||

|
||||
=========
|
||||
[](https://travis-ci.org/elixir-lang/elixir)
|
||||
[](https://ci.appveyor.com/project/josevalim/elixir)
|
||||
|
||||
Elixir is a dynamic, functional language designed for building scalable
|
||||
and maintainable applications.
|
||||
@@ -48,10 +50,10 @@ If Elixir fails to build (specifically when pulling in a new version via
|
||||
If tests pass, you can use Interactive Elixir by running `bin/iex` in your terminal.
|
||||
|
||||
However, if tests fail, it is likely that you have an outdated Erlang/OTP version
|
||||
(Elixir requires Erlang/OTP 21.0 or later). You can check your Erlang/OTP version
|
||||
by calling `erl` in the command line. You will see some information similar to:
|
||||
(Elixir requires Erlang/OTP 20.0 or later). You can check your Erlang/OTP version
|
||||
by calling `erl` in the command line. You will see some information as follows:
|
||||
|
||||
Erlang/OTP 21 [erts-9.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
|
||||
Erlang/OTP 20 [erts-9.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
|
||||
|
||||
If you have properly set up your dependencies and tests still fail,
|
||||
you may want to open up a bug report, as explained next.
|
||||
@@ -110,7 +112,7 @@ To recompile (including Erlang modules):
|
||||
make compile
|
||||
```
|
||||
|
||||
After your changes are done, please remember to run `make format` to guarantee
|
||||
After your changes are done, please remember to run `mix format` to guarantee
|
||||
all files are properly formatted and then run the full suite with
|
||||
`make test`.
|
||||
|
||||
@@ -123,7 +125,7 @@ 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 Cirrus CI](https://cirrus-ci.com/github/elixir-lang/elixir).
|
||||
[the official build status on Travis-CI](https://travis-ci.org/elixir-lang/elixir).
|
||||
More tasks can be found by reading the [Makefile](Makefile).
|
||||
|
||||
With tests running and passing, you are ready to contribute to Elixir and
|
||||
@@ -177,8 +179,8 @@ make docs # to generate HTML pages
|
||||
make docs DOCS_FORMAT=epub # to generate EPUB documents
|
||||
```
|
||||
|
||||
This will produce documentation sets for `elixir`, `eex`, `ex_unit`, `iex`, `logger`,
|
||||
and `mix` under the `doc` directory. If you are planning to contribute documentation,
|
||||
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).
|
||||
|
||||
## Development links
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@
|
||||
|
||||
9. Publish new zips with `make zips`, upload `Precompiled.zip` and `Docs.zip` to GitHub Releases, and include SHAs+CHANGELOG
|
||||
|
||||
10. Add the release to `elixir.csv` (all releases), update `erlang.csv` to the precompiled OTP version, and `_data/elixir-versions.yml` (except for RCs) files in `elixir-lang/elixir-lang.github.com`
|
||||
10. Add the release to `elixir.csv` (all releases) and `_data/elixir-versions.yml` (except for RCs) files in `elixir-lang/elixir-lang.github.com`
|
||||
|
||||
11. Send an e-mail to elixir-lang-ann@googlegroups.com with title "Elixir vVERSION released". The body should be a link to the Release page on GitHub and the checksums. If it is a security release, prefix the title with the `[security]` tag
|
||||
|
||||
@@ -40,6 +40,6 @@
|
||||
|
||||
2. Start new /CHANGELOG.md
|
||||
|
||||
3. Update tables in /SECURITY.md in "Compatibility and Deprecations"
|
||||
3. Update tables in "Compatibility and Deprecations"
|
||||
|
||||
4. Commit "Start vMAJOR.MINOR+1"
|
||||
|
||||
+3
-3
@@ -6,11 +6,11 @@ Elixir applies bug fixes only to the latest minor branch. Security patches are a
|
||||
|
||||
| Elixir version | Support
|
||||
| -------------- | ------------------------------
|
||||
| 1.11 | Bug fixes and security patches
|
||||
| 1.10 | Security patches only
|
||||
| 1.9 | Security patches only
|
||||
| 1.9 | Bug fixes and security patches
|
||||
| 1.8 | Security patches only
|
||||
| 1.7 | Security patches only
|
||||
| 1.6 | Security patches only
|
||||
| 1.5 | Security patches only
|
||||
|
||||
## Announcements
|
||||
|
||||
|
||||
+18
-20
@@ -2,23 +2,22 @@
|
||||
set -e
|
||||
|
||||
if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
cat <<USAGE >&2
|
||||
Usage: $(basename "$0") [options] [.exs file] [data]
|
||||
echo "Usage: $(basename "$0") [options] [.exs file] [data]
|
||||
|
||||
## General options
|
||||
|
||||
-e "COMMAND" Evaluates the given command (*)
|
||||
-e \"COMMAND\" Evaluates the given command (*)
|
||||
-h, --help Prints this message and exits
|
||||
-r "FILE" Requires the given files/patterns (*)
|
||||
-r \"FILE\" Requires the given files/patterns (*)
|
||||
-S SCRIPT Finds and executes the given script in \$PATH
|
||||
-pr "FILE" Requires the given files/patterns in parallel (*)
|
||||
-pa "PATH" Prepends the given path to Erlang code path (*)
|
||||
-pz "PATH" Appends the given path to Erlang code path (*)
|
||||
-pr \"FILE\" Requires the given files/patterns in parallel (*)
|
||||
-pa \"PATH\" Prepends the given path to Erlang code path (*)
|
||||
-pz \"PATH\" Appends the given path to Erlang code path (*)
|
||||
-v, --version Prints Elixir version and exits
|
||||
|
||||
--app APP Starts the given app and its dependencies (*)
|
||||
--erl "SWITCHES" Switches to be passed down to Erlang (*)
|
||||
--eval "COMMAND" Evaluates the given command, same as -e (*)
|
||||
--erl \"SWITCHES\" Switches to be passed down to Erlang (*)
|
||||
--eval \"COMMAND\" Evaluates the given command, same as -e (*)
|
||||
--logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
--logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
--no-halt Does not halt the Erlang VM after execution
|
||||
@@ -34,25 +33,24 @@ The following options are related to node distribution.
|
||||
--cookie COOKIE Sets a cookie for this distributed node
|
||||
--hidden Makes a hidden node
|
||||
--name NAME Makes and assigns a name to the distributed node
|
||||
--rpc-eval NODE "COMMAND" Evaluates the given command on the given remote node (*)
|
||||
--rpc-eval NODE \"COMMAND\" Evaluates the given command on the given remote node (*)
|
||||
--sname NAME Makes and assigns a short name to the distributed node
|
||||
|
||||
## Release options
|
||||
|
||||
The following options are generally used under releases.
|
||||
|
||||
--boot "FILE" Uses the given FILE.boot to start the system
|
||||
--boot-var VAR "VALUE" Makes \$VAR available as VALUE to FILE.boot (*)
|
||||
--erl-config "FILE" Loads configuration in FILE.config written in Erlang (*)
|
||||
--pipe-to "PIPEDIR" "LOGDIR" Starts the Erlang VM as a named PIPEDIR and LOGDIR
|
||||
--vm-args "FILE" Passes the contents in file as arguments to the VM
|
||||
--boot \"FILE\" Uses the given FILE.boot to start the system
|
||||
--boot-var VAR \"VALUE\" Makes \$VAR available as VALUE to FILE.boot (*)
|
||||
--erl-config \"FILE\" Loads configuration in FILE.config written in Erlang (*)
|
||||
--pipe-to \"PIPEDIR\" \"LOGDIR\" Starts the Erlang VM as a named PIPEDIR and LOGDIR
|
||||
--vm-args \"FILE\" Passes the contents in file as arguments to the VM
|
||||
|
||||
--pipe-to starts Elixir detached from console (Unix-like only).
|
||||
It will attempt to create PIPEDIR and LOGDIR if they don't exist.
|
||||
See run_erl to learn more. To reattach, run: to_erl PIPEDIR.
|
||||
|
||||
** Options marked with (*) can be given more than once.
|
||||
USAGE
|
||||
** Options marked with (*) can be given more than once." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -66,7 +64,7 @@ readlink_f () {
|
||||
fi
|
||||
}
|
||||
|
||||
# Stores static Erlang arguments and --erl (which is passed as is)
|
||||
# Stores static erlang arguments and --erl (which is passed as is)
|
||||
ERL=""
|
||||
|
||||
# Stores erl arguments preserving spaces/quotes (mimics an array)
|
||||
@@ -206,7 +204,7 @@ SCRIPT_PATH=$(dirname "$SELF")
|
||||
if [ "$OSTYPE" = "cygwin" ]; then SCRIPT_PATH=$(cygpath -m "$SCRIPT_PATH"); fi
|
||||
if [ "$MODE" != "iex" ]; then ERL="-noshell -s elixir start_cli $ERL"; fi
|
||||
|
||||
if [ "$OS" != "Windows_NT" ] && [ -z "$NO_COLOR" ]; then
|
||||
if [ "$OS" != "Windows_NT" ]; then
|
||||
if test -t 1 -a -t 2; then ERL="-elixir ansi_enabled true $ERL"; fi
|
||||
fi
|
||||
|
||||
@@ -228,4 +226,4 @@ if [ -n "$ELIXIR_CLI_DRY_RUN" ]; then
|
||||
echo "$@"
|
||||
else
|
||||
exec "$@"
|
||||
fi
|
||||
fi
|
||||
@@ -152,10 +152,6 @@ for /d %%d in ("!SCRIPT_PATH!..\lib\*.") do (
|
||||
)
|
||||
|
||||
:run
|
||||
reg query HKCU\Console /v VirtualTerminalLevel 2>nul | findstr /e "0x1" >nul 2>nul
|
||||
if %errorlevel% == 0 (
|
||||
set beforeExtra=-elixir ansi_enabled true !beforeExtra!
|
||||
)
|
||||
if not !runMode! == "iex" (
|
||||
set beforeExtra=-noshell -s elixir start_cli !beforeExtra!
|
||||
)
|
||||
|
||||
+2
-4
@@ -2,8 +2,7 @@
|
||||
set -e
|
||||
|
||||
if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
cat <<USAGE >&2
|
||||
Usage: $(basename "$0") [elixir switches] [compiler switches] [.ex files]
|
||||
echo "Usage: $(basename "$0") [elixir switches] [compiler switches] [.ex files]
|
||||
|
||||
-h, --help Prints this message and exits
|
||||
-o The directory to output compiled files
|
||||
@@ -17,8 +16,7 @@ Usage: $(basename "$0") [elixir switches] [compiler switches] [.ex files]
|
||||
|
||||
Options given after -- are passed down to the executed code.
|
||||
Options can be passed to the Erlang runtime using \$ELIXIR_ERL_OPTIONS.
|
||||
Options can be passed to the Erlang compiler using \$ERL_COMPILER_OPTIONS.
|
||||
USAGE
|
||||
Options can be passed to the Erlang compiler using \$ERL_COMPILER_OPTIONS." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
@@ -2,17 +2,15 @@
|
||||
set -e
|
||||
|
||||
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
cat <<USAGE >&2
|
||||
Usage: $(basename "$0") [options] [.exs file] [data]
|
||||
echo "Usage: $(basename "$0") [options] [.exs file] [data]
|
||||
|
||||
The following options are exclusive to IEx:
|
||||
|
||||
--dot-iex "PATH" Overrides default .iex.exs file and uses path instead;
|
||||
--dot-iex \"PATH\" Overrides default .iex.exs file and uses path instead;
|
||||
path can be empty, then no file will be loaded
|
||||
--remsh NAME Connects to a node using a remote shell
|
||||
|
||||
It accepts all other options listed by "elixir --help".
|
||||
USAGE
|
||||
It accepts all other options listed by \"elixir --help\"." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/usr/bin/env elixir
|
||||
Mix.start()
|
||||
Mix.CLI.main()
|
||||
Mix.start
|
||||
Mix.CLI.main
|
||||
|
||||
+11
-19
@@ -1,9 +1,9 @@
|
||||
defmodule EEx.SyntaxError do
|
||||
defexception [:message, :file, :line, :column]
|
||||
defexception [:message, :file, :line]
|
||||
|
||||
@impl true
|
||||
def message(exception) do
|
||||
"#{exception.file}:#{exception.line}:#{exception.column}: #{exception.message}"
|
||||
"#{exception.file}:#{exception.line}: #{exception.message}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -19,17 +19,17 @@ defmodule EEx do
|
||||
|
||||
This module provides 3 main APIs for you to use:
|
||||
|
||||
1. Evaluate a string (`eval_string/3`) or a file (`eval_file/3`)
|
||||
1. Evaluate a string (`eval_string`) or a file (`eval_file`)
|
||||
directly. This is the simplest API to use but also the
|
||||
slowest, since the code is evaluated and not compiled before.
|
||||
|
||||
2. Define a function from a string (`function_from_string/5`)
|
||||
or a file (`function_from_file/5`). This allows you to embed
|
||||
2. Define a function from a string (`function_from_string`)
|
||||
or a file (`function_from_file`). This allows you to embed
|
||||
the template as a function inside a module which will then
|
||||
be compiled. This is the preferred API if you have access
|
||||
to the template at compilation time.
|
||||
|
||||
3. Compile a string (`compile_string/2`) or a file (`compile_file/2`)
|
||||
3. Compile a string (`compile_string`) or a file (`compile_file`)
|
||||
into Elixir syntax tree. This is the API used by both functions
|
||||
above and is available to you if you want to provide your own
|
||||
ways of handling the compiled template.
|
||||
@@ -39,14 +39,12 @@ defmodule EEx do
|
||||
All functions in this module accept EEx-related options.
|
||||
They are:
|
||||
|
||||
* `:line` - the line to be used as the template start. Defaults to 1.
|
||||
* `:file` - the file to be used in the template. Defaults to the given
|
||||
file the template is read from or to "nofile" when compiling from a string.
|
||||
* `:line` - the line to be used as the template start. Defaults to 1.
|
||||
* `:indentation` - (since v1.11.0) an integer added to the column after every
|
||||
new line. Defaults to 0.
|
||||
* `:engine` - the EEx engine to be used for compilation.
|
||||
* `:trim` - if true, trims whitespace left/right of quotation tags up until
|
||||
newlines. At least one newline is retained. Defaults to false.
|
||||
* `:trim` - trims whitespace left/right of quotation tags. If a quotation
|
||||
tag appears on its own in a given line, line endings are also removed.
|
||||
|
||||
## Engine
|
||||
|
||||
@@ -69,7 +67,7 @@ defmodule EEx do
|
||||
**must** use the equals sign (`=`). Since everything in
|
||||
Elixir is an expression, there are no exceptions for this rule.
|
||||
For example, while some template languages would special-case
|
||||
`if` clauses, they are treated the same in EEx and
|
||||
`if/2` clauses, they are treated the same in EEx and
|
||||
also require `=` in order to have their result printed:
|
||||
|
||||
<%= if true do %>
|
||||
@@ -78,13 +76,7 @@ defmodule EEx do
|
||||
This will never appear
|
||||
<% end %>
|
||||
|
||||
To escape an EEx expression in EEx use `<%% content %>`. For example:
|
||||
|
||||
<%%= x + 3 %>
|
||||
|
||||
will be rendered as `<%= x + 3 %>`.
|
||||
|
||||
Note that different engines may have different rules
|
||||
Notice that different engines may have different rules
|
||||
for each tag. Other tags may be added in future versions.
|
||||
|
||||
### Macros
|
||||
|
||||
+26
-58
@@ -13,28 +13,23 @@ defmodule EEx.Compiler do
|
||||
def compile(source, opts) when is_binary(source) and is_list(opts) do
|
||||
file = opts[:file] || "nofile"
|
||||
line = opts[:line] || 1
|
||||
column = 1
|
||||
indentation = opts[:indentation] || 0
|
||||
trim = opts[:trim] || false
|
||||
tokenizer_options = %{trim: trim, indentation: indentation}
|
||||
|
||||
case EEx.Tokenizer.tokenize(source, line, column, tokenizer_options) do
|
||||
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,
|
||||
start_column: nil,
|
||||
parser_options: Code.get_compiler_option(:parser_options)
|
||||
start_line: nil
|
||||
}
|
||||
|
||||
init = state.engine.init(opts)
|
||||
generate_buffer(tokens, init, [], state)
|
||||
|
||||
{:error, line, column, message} ->
|
||||
raise EEx.SyntaxError, file: file, line: line, column: column, message: message
|
||||
{:error, line, message} ->
|
||||
raise EEx.SyntaxError, line: line, file: file, message: message
|
||||
end
|
||||
end
|
||||
|
||||
@@ -46,19 +41,13 @@ defmodule EEx.Compiler do
|
||||
generate_buffer(rest, buffer, scope, state)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:expr, line, column, mark, chars} | rest], buffer, scope, state) do
|
||||
options = [file: state.file, line: line, column: column(column, mark)] ++ state.parser_options
|
||||
expr = Code.string_to_quoted!(chars, options)
|
||||
defp generate_buffer([{:expr, line, mark, chars, _} | rest], 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)
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:start_expr, start_line, start_column, mark, chars} | rest],
|
||||
buffer,
|
||||
scope,
|
||||
state
|
||||
) do
|
||||
defp generate_buffer([{:start_expr, start_line, mark, chars, _} | rest], buffer, scope, state) do
|
||||
{contents, line, rest} = look_ahead_middle(rest, start_line, chars)
|
||||
|
||||
{contents, rest} =
|
||||
@@ -66,13 +55,7 @@ defmodule EEx.Compiler do
|
||||
rest,
|
||||
state.engine.handle_begin(buffer),
|
||||
[contents | scope],
|
||||
%{
|
||||
state
|
||||
| quoted: [],
|
||||
line: line,
|
||||
start_line: start_line,
|
||||
start_column: column(start_column, mark)
|
||||
}
|
||||
%{state | quoted: [], line: line, start_line: start_line}
|
||||
)
|
||||
|
||||
buffer = state.engine.handle_expr(buffer, IO.chardata_to_string(mark), contents)
|
||||
@@ -80,7 +63,7 @@ defmodule EEx.Compiler do
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:middle_expr, line, _column, '', chars} | rest],
|
||||
[{:middle_expr, line, '', chars, _} | rest],
|
||||
buffer,
|
||||
[current | scope],
|
||||
state
|
||||
@@ -91,7 +74,7 @@ defmodule EEx.Compiler do
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:middle_expr, line, column, modifier, chars} | t],
|
||||
[{:middle_expr, line, modifier, chars, trimmed?} | t],
|
||||
buffer,
|
||||
[_ | _] = scope,
|
||||
state
|
||||
@@ -101,35 +84,27 @@ defmodule EEx.Compiler do
|
||||
"please remove \"#{modifier}\" accordingly"
|
||||
|
||||
:elixir_errors.erl_warn(line, state.file, message)
|
||||
generate_buffer([{:middle_expr, line, column, '', chars} | t], buffer, scope, state)
|
||||
generate_buffer([{:middle_expr, line, '', chars, trimmed?} | 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, column, _, chars} | _], _buffer, [], state) do
|
||||
defp generate_buffer([{:middle_expr, line, _, chars, _} | _], _buffer, [], state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected middle of expression <%#{chars}%>",
|
||||
file: state.file,
|
||||
line: line,
|
||||
column: column
|
||||
line: line
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:end_expr, line, _column, '', chars} | rest],
|
||||
buffer,
|
||||
[current | _],
|
||||
state
|
||||
) do
|
||||
defp generate_buffer([{:end_expr, line, '', chars, _} | rest], buffer, [current | _], state) do
|
||||
{wrapped, state} = wrap_expr(current, line, buffer, chars, state)
|
||||
column = state.start_column
|
||||
options = [file: state.file, line: state.start_line, column: column] ++ state.parser_options
|
||||
tuples = Code.string_to_quoted!(wrapped, options)
|
||||
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, column, modifier, chars} | t],
|
||||
[{:end_expr, line, modifier, chars, trimmed?} | t],
|
||||
buffer,
|
||||
[_ | _] = scope,
|
||||
state
|
||||
@@ -139,29 +114,27 @@ defmodule EEx.Compiler do
|
||||
"expression \"<%#{modifier}#{chars}%>\", please remove \"#{modifier}\" accordingly"
|
||||
|
||||
:elixir_errors.erl_warn(line, state.file, message)
|
||||
generate_buffer([{:end_expr, line, column, '', chars} | t], buffer, scope, state)
|
||||
generate_buffer([{:end_expr, line, '', chars, trimmed?} | 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, column: column
|
||||
# raise EEx.SyntaxError, message: message, file: state.file, line: line
|
||||
end
|
||||
|
||||
defp generate_buffer([{:end_expr, line, column, _, chars} | _], _buffer, [], state) do
|
||||
defp generate_buffer([{:end_expr, line, _, chars, _} | _], _buffer, [], state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected end of expression <%#{chars}%>",
|
||||
file: state.file,
|
||||
line: line,
|
||||
column: column
|
||||
line: line
|
||||
end
|
||||
|
||||
defp generate_buffer([{:eof, _, _}], buffer, [], state) do
|
||||
defp generate_buffer([], buffer, [], state) do
|
||||
state.engine.handle_body(buffer)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:eof, line, column}], _buffer, _scope, state) do
|
||||
defp generate_buffer([], _buffer, _scope, state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected end of string, expected a closing '<% end %>'",
|
||||
file: state.file,
|
||||
line: line,
|
||||
column: column
|
||||
line: state.line
|
||||
end
|
||||
|
||||
# Creates a placeholder and wrap it inside the expression block
|
||||
@@ -176,10 +149,10 @@ defmodule EEx.Compiler do
|
||||
{count, new_state}
|
||||
end
|
||||
|
||||
# Look middle expressions that immediately follow a start_expr
|
||||
# Look middle expressions that immediatelly follow a start_expr
|
||||
|
||||
defp look_ahead_middle(
|
||||
[{:text, text}, {:middle_expr, line, _column, _, chars} | rest] = tokens,
|
||||
[{:text, text}, {:middle_expr, line, _, chars, _} | rest] = tokens,
|
||||
start,
|
||||
contents
|
||||
) do
|
||||
@@ -190,7 +163,7 @@ defmodule EEx.Compiler do
|
||||
end
|
||||
end
|
||||
|
||||
defp look_ahead_middle([{:middle_expr, line, _column, _, chars} | rest], _start, contents) do
|
||||
defp look_ahead_middle([{:middle_expr, line, _, chars, _} | rest], _start, contents) do
|
||||
{contents ++ chars, line, rest}
|
||||
end
|
||||
|
||||
@@ -224,9 +197,4 @@ defmodule EEx.Compiler do
|
||||
defp insert_quoted(other, _quoted) do
|
||||
other
|
||||
end
|
||||
|
||||
defp column(column, mark) do
|
||||
# length('<%') == 2
|
||||
column + 2 + length(mark)
|
||||
end
|
||||
end
|
||||
|
||||
+147
-117
@@ -3,14 +3,14 @@ defmodule EEx.Tokenizer do
|
||||
|
||||
@type content :: IO.chardata()
|
||||
@type line :: non_neg_integer
|
||||
@type column :: non_neg_integer
|
||||
@type marker :: '=' | '/' | '|' | ''
|
||||
@type trimmed? :: boolean
|
||||
@type token ::
|
||||
{:text, content}
|
||||
| {:expr | :start_expr | :middle_expr | :end_expr, line, column, marker, content}
|
||||
| {:eof, line, column}
|
||||
| {:expr | :start_expr | :middle_expr | :end_expr, line, marker, content, trimmed?}
|
||||
|
||||
@spaces [?\s, ?\t]
|
||||
@closing_brackets ')]}'
|
||||
|
||||
@doc """
|
||||
Tokenizes the given charlist or binary.
|
||||
@@ -18,79 +18,67 @@ defmodule EEx.Tokenizer do
|
||||
It returns {:ok, list} with the following tokens:
|
||||
|
||||
* `{:text, content}`
|
||||
* `{:expr, line, column, marker, content}`
|
||||
* `{:start_expr, line, column, marker, content}`
|
||||
* `{:middle_expr, line, column, marker, content}`
|
||||
* `{:end_expr, line, column, marker, content}`
|
||||
* `{:eof, line, column}`
|
||||
* `{:expr, line, marker, content, trimmed?}`
|
||||
* `{:start_expr, line, marker, content, trimmed?}`
|
||||
* `{:middle_expr, line, marker, content, trimmed?}`
|
||||
* `{:end_expr, line, marker, content, trimmed?}`
|
||||
|
||||
Or `{:error, line, column, message}` in case of errors.
|
||||
Or `{:error, line, error}` in case of errors.
|
||||
"""
|
||||
@spec tokenize(binary | charlist, line, column, map) ::
|
||||
{:ok, [token]} | {:error, line, column, String.t()}
|
||||
@spec tokenize(binary | charlist, line, keyword) :: {:ok, [token]} | {:error, line, String.t()}
|
||||
def tokenize(bin, line, opts \\ [])
|
||||
|
||||
def tokenize(bin, line, column, opts) when is_binary(bin) do
|
||||
tokenize(String.to_charlist(bin), line, column, opts)
|
||||
def tokenize(bin, line, opts)
|
||||
when is_binary(bin) and is_integer(line) and line >= 0 and is_list(opts) do
|
||||
tokenize(String.to_charlist(bin), line, opts)
|
||||
end
|
||||
|
||||
def tokenize(list, line, column, opts)
|
||||
when is_list(list) and is_integer(line) and line >= 0 and is_integer(column) and column >= 0 do
|
||||
column = opts.indentation + column
|
||||
{list, line, column} = (opts.trim && trim_init(list, line, column)) || {list, line, column}
|
||||
tokenize(list, line, column, opts, [], [])
|
||||
def tokenize(list, line, opts)
|
||||
when is_list(list) and is_integer(line) and line >= 0 and is_list(opts) do
|
||||
tokenize(list, line, opts, [], [])
|
||||
end
|
||||
|
||||
defp tokenize('<%%' ++ t, line, column, opts, buffer, acc) do
|
||||
tokenize(t, line, column + 3, opts, [?%, ?< | buffer], acc)
|
||||
defp tokenize('<%%' ++ t, line, opts, buffer, acc) do
|
||||
tokenize(t, line, opts, [?%, ?< | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize('<%#' ++ t, line, column, opts, buffer, acc) do
|
||||
case expr(t, line, column + 3, opts, []) do
|
||||
{:error, _, _, _} = error ->
|
||||
defp tokenize('<%#' ++ t, line, opts, buffer, acc) do
|
||||
case expr(t, line, []) do
|
||||
{:error, _, _} = error ->
|
||||
error
|
||||
|
||||
{:ok, _, new_line, new_column, rest} ->
|
||||
{rest, new_line, new_column, buffer} =
|
||||
trim_if_needed(rest, new_line, new_column, opts, buffer)
|
||||
|
||||
tokenize(rest, new_line, new_column, opts, buffer, acc)
|
||||
{:ok, _, new_line, rest} ->
|
||||
{_, rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
|
||||
tokenize(rest, new_line, opts, buffer, acc)
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('<%' ++ t, line, column, opts, buffer, acc) do
|
||||
defp tokenize('<%' ++ t, line, opts, buffer, acc) do
|
||||
{marker, t} = retrieve_marker(t)
|
||||
|
||||
case expr(t, line, column + 2 + length(marker), opts, []) do
|
||||
{:error, _, _, _} = error ->
|
||||
case expr(t, line, []) do
|
||||
{:error, _, _} = error ->
|
||||
error
|
||||
|
||||
{:ok, expr, new_line, new_column, rest} ->
|
||||
{key, expr} =
|
||||
case :elixir_tokenizer.tokenize(expr, 1, file: "eex", check_terminators: false) do
|
||||
{:ok, tokens} -> token_key(tokens, expr)
|
||||
{:error, _, _, _} -> {:expr, expr}
|
||||
end
|
||||
|
||||
{rest, new_line, new_column, buffer} =
|
||||
trim_if_needed(rest, new_line, new_column, opts, buffer)
|
||||
|
||||
{:ok, expr, new_line, rest} ->
|
||||
token = token_name(expr)
|
||||
{trimmed?, rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
|
||||
acc = tokenize_text(buffer, acc)
|
||||
final = {key, line, column, marker, expr}
|
||||
tokenize(rest, new_line, new_column, opts, [], [final | acc])
|
||||
final = {token, line, marker, Enum.reverse(expr), trimmed?}
|
||||
tokenize(rest, new_line, opts, [], [final | acc])
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('\n' ++ t, line, _column, opts, buffer, acc) do
|
||||
tokenize(t, line + 1, opts.indentation + 1, opts, [?\n | buffer], acc)
|
||||
defp tokenize('\n' ++ t, line, opts, buffer, acc) do
|
||||
tokenize(t, line + 1, opts, [?\n | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize([h | t], line, column, opts, buffer, acc) do
|
||||
tokenize(t, line, column + 1, opts, [h | buffer], acc)
|
||||
defp tokenize([h | t], line, opts, buffer, acc) do
|
||||
tokenize(t, line, opts, [h | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize([], line, column, _opts, buffer, acc) do
|
||||
eof = {:eof, line, column}
|
||||
{:ok, Enum.reverse([eof | tokenize_text(buffer, acc)])}
|
||||
defp tokenize([], _line, _opts, buffer, acc) do
|
||||
{:ok, Enum.reverse(tokenize_text(buffer, acc))}
|
||||
end
|
||||
|
||||
# Retrieve marker for <%
|
||||
@@ -105,61 +93,102 @@ defmodule EEx.Tokenizer do
|
||||
|
||||
# Tokenize an expression until we find %>
|
||||
|
||||
defp expr([?%, ?> | t], line, column, _opts, buffer) do
|
||||
{:ok, Enum.reverse(buffer), line, column + 2, t}
|
||||
defp expr([?%, ?> | t], line, buffer) do
|
||||
{:ok, buffer, line, t}
|
||||
end
|
||||
|
||||
defp expr('\n' ++ t, line, _column, opts, buffer) do
|
||||
expr(t, line + 1, opts.indentation + 1, opts, [?\n | buffer])
|
||||
defp expr('\n' ++ t, line, buffer) do
|
||||
expr(t, line + 1, [?\n | buffer])
|
||||
end
|
||||
|
||||
defp expr([h | t], line, column, opts, buffer) do
|
||||
expr(t, line, column + 1, opts, [h | buffer])
|
||||
defp expr([h | t], line, buffer) do
|
||||
expr(t, line, [h | buffer])
|
||||
end
|
||||
|
||||
defp expr([], line, column, _opts, _buffer) do
|
||||
{:error, line, column, "missing token '%>'"}
|
||||
defp expr([], line, _buffer) do
|
||||
{:error, line, "missing token '%>'"}
|
||||
end
|
||||
|
||||
# Receives tokens and check if it is a start, middle or an end token.
|
||||
defp token_key(tokens, expr) do
|
||||
case {tokens, Enum.reverse(tokens)} do
|
||||
{[{:end, _} | _], [{:do, _} | _]} ->
|
||||
{:middle_expr, expr}
|
||||
# Receive an expression content and check
|
||||
# if it is a start, middle or an end token.
|
||||
#
|
||||
# Start tokens finish with "do" and "fn ->"
|
||||
# Middle tokens are marked with "->" or keywords
|
||||
# End tokens contain only the end word and optionally
|
||||
# combinations of ")", "]" and "}".
|
||||
|
||||
{_, [{:do, _} | _]} ->
|
||||
{:start_expr, maybe_append_space(expr)}
|
||||
defp token_name([h | t]) when h in @spaces do
|
||||
token_name(t)
|
||||
end
|
||||
|
||||
{_, [{:block_identifier, _, _} | _]} ->
|
||||
{:middle_expr, maybe_append_space(expr)}
|
||||
|
||||
{[{:end, _} | _], [{:stab_op, _, _} | _]} ->
|
||||
{:middle_expr, expr}
|
||||
|
||||
{_, [{:stab_op, _, _} | reverse_tokens]} ->
|
||||
fn_index = Enum.find_index(reverse_tokens, &match?({:fn, _}, &1)) || :infinity
|
||||
end_index = Enum.find_index(reverse_tokens, &match?({:end, _}, &1)) || :infinity
|
||||
|
||||
if end_index > fn_index do
|
||||
{:start_expr, expr}
|
||||
else
|
||||
{:middle_expr, expr}
|
||||
end
|
||||
|
||||
{tokens, _} ->
|
||||
case Enum.drop_while(tokens, &closing_bracket?/1) do
|
||||
[{:end, _} | _] -> {:end_expr, expr}
|
||||
_ -> {:expr, expr}
|
||||
end
|
||||
defp token_name('od' ++ [h | rest]) when h in @spaces or h in @closing_brackets do
|
||||
case tokenize_rest(rest) do
|
||||
{:ok, [{:end, _} | _]} -> :middle_expr
|
||||
_ -> :start_expr
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_append_space([?\s]), do: [?\s]
|
||||
defp maybe_append_space([h]), do: [h, ?\s]
|
||||
defp maybe_append_space([h | t]), do: [h | maybe_append_space(t)]
|
||||
defp token_name('>-' ++ rest) do
|
||||
case tokenize_rest(rest) do
|
||||
{:ok, [{:end, _} | _]} ->
|
||||
:middle_expr
|
||||
|
||||
defp closing_bracket?({closing, _}) when closing in ~w"( [ {"a, do: true
|
||||
defp closing_bracket?(_), do: false
|
||||
# Check if there is a "fn" token and, if so, it is not
|
||||
# followed by an "end" token. If this is the case, we
|
||||
# are on a start expr.
|
||||
{:ok, tokens} ->
|
||||
tokens = Enum.reverse(tokens)
|
||||
fn_index = fn_index(tokens)
|
||||
|
||||
if fn_index && end_index(tokens) > fn_index do
|
||||
:start_expr
|
||||
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('eucser' ++ t), do: check_spaces(t, :middle_expr)
|
||||
|
||||
defp token_name(rest) do
|
||||
case Enum.drop_while(rest, &(&1 in @spaces or &1 in @closing_brackets)) do
|
||||
'dne' ++ t -> check_spaces(t, :end_expr)
|
||||
_ -> :expr
|
||||
end
|
||||
end
|
||||
|
||||
# Tokenize the remaining passing check_terminators as false,
|
||||
# which relax the tokenizer to not error on unmatched pairs.
|
||||
# If the tokens start with an "end" we have a middle expr.
|
||||
defp tokenize_rest(rest) do
|
||||
:elixir_tokenizer.tokenize(Enum.reverse(rest), 1, file: "eex", check_terminators: false)
|
||||
end
|
||||
|
||||
defp fn_index(tokens) do
|
||||
Enum.find_index(tokens, fn
|
||||
{:fn_paren, _} -> true
|
||||
{:fn, _} -> true
|
||||
_ -> false
|
||||
end)
|
||||
end
|
||||
|
||||
defp end_index(tokens) do
|
||||
Enum.find_index(tokens, &match?({:end, _}, &1)) || :infinity
|
||||
end
|
||||
|
||||
defp check_spaces(string, token) do
|
||||
if Enum.all?(string, &(&1 in @spaces)) do
|
||||
token
|
||||
else
|
||||
:expr
|
||||
end
|
||||
end
|
||||
|
||||
# Tokenize the buffered text by appending
|
||||
# it to the given accumulator.
|
||||
@@ -172,41 +201,42 @@ defmodule EEx.Tokenizer do
|
||||
[{:text, Enum.reverse(buffer)} | acc]
|
||||
end
|
||||
|
||||
defp trim_if_needed(rest, line, column, opts, buffer) do
|
||||
if opts.trim do
|
||||
buffer = trim_left(buffer, 0)
|
||||
{rest, line, column} = trim_right(rest, line, column, 0)
|
||||
{rest, line, column, buffer}
|
||||
# If trim mode is enabled and the token is on a line with
|
||||
# only itself and whitespace, trim the whitespace around it,
|
||||
# including the line break following it if there is one.
|
||||
defp trim_if_needed(rest, line, opts, buffer, acc) do
|
||||
with true <- opts[:trim],
|
||||
{true, new_buffer} <- trim_left(buffer, acc),
|
||||
{true, new_rest, new_line} <- trim_right(rest, line) do
|
||||
{true, new_rest, new_line, new_buffer}
|
||||
else
|
||||
{rest, line, column, buffer}
|
||||
_ -> {false, rest, line, buffer}
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_init([h | t], line, column) when h in @spaces, do: trim_init(t, line, column + 1)
|
||||
defp trim_init([?\r, ?\n | t], line, _column), do: trim_init(t, line + 1, 1)
|
||||
defp trim_init([?\n | t], line, _column), do: trim_init(t, line + 1, 1)
|
||||
defp trim_init([?<, ?% | _] = rest, line, column), do: {rest, line, column}
|
||||
defp trim_init(_, _, _), do: false
|
||||
|
||||
defp trim_left(buffer, count) do
|
||||
case trim_whitespace(buffer) do
|
||||
[?\n, ?\r | rest] -> trim_left(rest, count + 1)
|
||||
[?\n | rest] -> trim_left(rest, count + 1)
|
||||
_ when count > 0 -> [?\n | buffer]
|
||||
_ -> buffer
|
||||
defp trim_left(buffer, acc) do
|
||||
case {trim_whitespace(buffer), acc} do
|
||||
{[?\n | _] = trimmed_buffer, _} -> {true, trimmed_buffer}
|
||||
{[], [{_, _, _, _, true} | _]} -> {true, []}
|
||||
{[], []} -> {true, []}
|
||||
_ -> {false, buffer}
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_right(rest, line, column, count) do
|
||||
defp trim_right(rest, line) do
|
||||
case trim_whitespace(rest) do
|
||||
[?\r, ?\n | rest] -> trim_right(rest, line + 1, 1, count + 1)
|
||||
[?\n | rest] -> trim_right(rest, line + 1, 1, count + 1)
|
||||
[] -> {[], line, column + length(rest)}
|
||||
_ when count > 0 -> {[?\n | rest], line - 1, column}
|
||||
_ -> {rest, line, column}
|
||||
[?\r, ?\n | trimmed_rest] -> {true, trimmed_rest, line + 1}
|
||||
[?\n | trimmed_rest] -> {true, trimmed_rest, line + 1}
|
||||
[] -> {true, [], line}
|
||||
_ -> {false, rest, line}
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_whitespace([h | t]) when h in @spaces, do: trim_whitespace(t)
|
||||
defp trim_whitespace(list), do: list
|
||||
defp trim_whitespace([h | t]) when h in @spaces do
|
||||
trim_whitespace(t)
|
||||
end
|
||||
|
||||
defp trim_whitespace(list) do
|
||||
list
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
Code.require_file("../test_helper.exs", __DIR__)
|
||||
|
||||
defmodule EEx.SmartEngineTest do
|
||||
use ExUnit.Case, async: true
|
||||
# TODO: Make this async: true once capture_io is removed
|
||||
use ExUnit.Case
|
||||
|
||||
test "evaluates simple string" do
|
||||
assert_eval("foo bar", "foo bar")
|
||||
|
||||
@@ -4,39 +4,37 @@ defmodule EEx.TokenizerTest do
|
||||
use ExUnit.Case, async: true
|
||||
require EEx.Tokenizer, as: T
|
||||
|
||||
@opts %{indentation: 0, trim: false}
|
||||
|
||||
test "simple chars lists" do
|
||||
assert T.tokenize('foo', 1, 1, @opts) == {:ok, [{:text, 'foo'}, {:eof, 1, 4}]}
|
||||
assert T.tokenize('foo', 1) == {:ok, [{:text, 'foo'}]}
|
||||
end
|
||||
|
||||
test "simple strings" do
|
||||
assert T.tokenize("foo", 1, 1, @opts) == {:ok, [{:text, 'foo'}, {:eof, 1, 4}]}
|
||||
assert T.tokenize("foo", 1) == {:ok, [{:text, 'foo'}]}
|
||||
end
|
||||
|
||||
test "strings with embedded code" do
|
||||
assert T.tokenize('foo <% bar %>', 1, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, 5, '', ' bar '}, {:eof, 1, 14}]}
|
||||
assert T.tokenize('foo <% bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with embedded equals code" do
|
||||
assert T.tokenize('foo <%= bar %>', 1, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, 5, '=', ' bar '}, {:eof, 1, 15}]}
|
||||
assert T.tokenize('foo <%= bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '=', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with embedded slash code" do
|
||||
assert T.tokenize('foo <%/ bar %>', 1, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, 5, '/', ' bar '}, {:eof, 1, 15}]}
|
||||
assert T.tokenize('foo <%/ bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '/', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with embedded pipe code" do
|
||||
assert T.tokenize('foo <%| bar %>', 1, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, 5, '|', ' bar '}, {:eof, 1, 15}]}
|
||||
assert T.tokenize('foo <%| bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '|', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with more than one line" do
|
||||
assert T.tokenize('foo\n<%= bar %>', 1, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo\n'}, {:expr, 2, 1, '=', ' bar '}, {:eof, 2, 11}]}
|
||||
assert T.tokenize('foo\n<%= bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo\n'}, {:expr, 2, '=', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with more than one line and expression with more than one line" do
|
||||
@@ -49,208 +47,167 @@ defmodule EEx.TokenizerTest do
|
||||
|
||||
exprs = [
|
||||
{:text, 'foo '},
|
||||
{:expr, 1, 5, '=', ' bar\n\nbaz '},
|
||||
{:expr, 1, '=', ' bar\n\nbaz ', false},
|
||||
{:text, '\n'},
|
||||
{:expr, 4, 1, '', ' foo '},
|
||||
{:text, '\n'},
|
||||
{:eof, 5, 1}
|
||||
{:expr, 4, '', ' foo ', false},
|
||||
{:text, '\n'}
|
||||
]
|
||||
|
||||
assert T.tokenize(string, 1, 1, @opts) == {:ok, exprs}
|
||||
assert T.tokenize(string, 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "quotation" do
|
||||
assert T.tokenize('foo <%% true %>', 1, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo <% true %>'}, {:eof, 1, 16}]}
|
||||
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, 1, @opts) ==
|
||||
{:ok, [{:text, 'foo <% true do %>bar<% end %>'}, {:eof, 1, 32}]}
|
||||
assert T.tokenize('foo <%% true do %>bar<%% end %>', 1) ==
|
||||
{:ok, [{:text, 'foo <% true do %>bar<% end %>'}]}
|
||||
end
|
||||
|
||||
test "quotation with interpolation" do
|
||||
exprs = [
|
||||
{:text, 'a <% b '},
|
||||
{:expr, 1, 9, '=', ' c '},
|
||||
{:expr, 1, '=', ' c ', false},
|
||||
{:text, ' '},
|
||||
{:expr, 1, 18, '=', ' d '},
|
||||
{:text, ' e %> f'},
|
||||
{:eof, 1, 33}
|
||||
{:expr, 1, '=', ' d ', false},
|
||||
{:text, ' e %> f'}
|
||||
]
|
||||
|
||||
assert T.tokenize('a <%% b <%= c %> <%= d %> e %> f', 1, 1, @opts) == {:ok, exprs}
|
||||
assert T.tokenize('a <%% b <%= c %> <%= d %> e %> f', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "improperly formatted quotation with interpolation" do
|
||||
exprs = [
|
||||
{:text, '<%% a <%= b %> c %>'},
|
||||
{:eof, 1, 22}
|
||||
{:text, '<%% a <%= b %> c %>'}
|
||||
]
|
||||
|
||||
assert T.tokenize('<%%% a <%%= b %> c %>', 1, 1, @opts) == {:ok, exprs}
|
||||
assert T.tokenize('<%%% a <%%= b %> c %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "eex comments" do
|
||||
test "comments" do
|
||||
exprs = [
|
||||
{:text, 'foo '},
|
||||
{:eof, 1, 16}
|
||||
{:text, 'foo '}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <%# true %>', 1, 1, @opts) == {:ok, exprs}
|
||||
assert T.tokenize('foo <%# true %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "eex comments with do/end" do
|
||||
test "comments with do/end" do
|
||||
exprs = [
|
||||
{:text, 'foo bar'},
|
||||
{:eof, 1, 32}
|
||||
{:text, 'foo bar'}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <%# true do %>bar<%# end %>', 1, 1, @opts) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "elixir comments" do
|
||||
exprs = [
|
||||
{:text, 'foo '},
|
||||
{:expr, 1, 5, [], ' true # this is a boolean '},
|
||||
{:eof, 1, 35}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% true # this is a boolean %>', 1, 1, @opts) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "elixir comments with do/end" do
|
||||
exprs = [
|
||||
{:start_expr, 1, 1, [], ' if true do # startif '},
|
||||
{:text, 'text'},
|
||||
{:end_expr, 1, 31, [], ' end # closeif '},
|
||||
{:eof, 1, 50}
|
||||
]
|
||||
|
||||
assert T.tokenize('<% if true do # startif %>text<% end # closeif %>', 1, 1, @opts) ==
|
||||
{:ok, exprs}
|
||||
assert T.tokenize('foo <%# true do %>bar<%# end %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with embedded do end" do
|
||||
exprs = [
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, 5, '', ' if true do '},
|
||||
{:start_expr, 1, '', ' if true do ', false},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, 24, '', ' end '},
|
||||
{:eof, 1, 33}
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% if true do %>bar<% end %>', 1, 1, @opts) == {:ok, exprs}
|
||||
assert T.tokenize('foo <% if true do %>bar<% end %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with embedded -> end" do
|
||||
exprs = [
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, 5, '', ' cond do '},
|
||||
{:middle_expr, 1, 18, '', ' false -> '},
|
||||
{:start_expr, 1, '', ' cond do ', false},
|
||||
{:middle_expr, 1, '', ' false -> ', false},
|
||||
{:text, 'bar'},
|
||||
{:middle_expr, 1, 35, '', ' true -> '},
|
||||
{:middle_expr, 1, '', ' true -> ', false},
|
||||
{:text, 'baz'},
|
||||
{:end_expr, 1, 51, '', ' end '},
|
||||
{:eof, 1, 60}
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', 1, 1, @opts) ==
|
||||
assert T.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', 1) ==
|
||||
{:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with multiple callbacks" do
|
||||
exprs = [
|
||||
{:start_expr, 1, 1, '=', ' a fn -> '},
|
||||
{:start_expr, 1, '=', ' a fn -> ', false},
|
||||
{:text, 'foo'},
|
||||
{:middle_expr, 1, 18, '', ' end, fn -> '},
|
||||
{:middle_expr, 1, '', ' end, fn -> ', false},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, 37, '', ' end '},
|
||||
{:eof, 1, 46}
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert T.tokenize('<%= a fn -> %>foo<% end, fn -> %>bar<% end %>', 1, 1, @opts) ==
|
||||
{:ok, exprs}
|
||||
assert T.tokenize('<%= a fn -> %>foo<% end, fn -> %>bar<% end %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with callback followed by do block" do
|
||||
exprs = [
|
||||
{:start_expr, 1, 1, '=', ' a fn -> '},
|
||||
{:start_expr, 1, '=', ' a fn -> ', false},
|
||||
{:text, 'foo'},
|
||||
{:middle_expr, 1, 18, '', ' end do '},
|
||||
{:middle_expr, 1, '', ' end do ', false},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, 33, '', ' end '},
|
||||
{:eof, 1, 42}
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert T.tokenize('<%= a fn -> %>foo<% end do %>bar<% end %>', 1, 1, @opts) == {:ok, exprs}
|
||||
assert T.tokenize('<%= a fn -> %>foo<% end do %>bar<% end %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with embedded keywords blocks" do
|
||||
exprs = [
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, 5, '', ' if true do '},
|
||||
{:start_expr, 1, '', ' if true do ', false},
|
||||
{:text, 'bar'},
|
||||
{:middle_expr, 1, 24, '', ' else '},
|
||||
{:middle_expr, 1, '', ' else ', false},
|
||||
{:text, 'baz'},
|
||||
{:end_expr, 1, 37, '', ' end '},
|
||||
{:eof, 1, 46}
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% if true do %>bar<% else %>baz<% end %>', 1, 1, @opts) ==
|
||||
{:ok, exprs}
|
||||
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 %> \n\n '
|
||||
template = '\t<%= if true do %> \n TRUE \n <% else %>\n FALSE \n <% end %> '
|
||||
|
||||
exprs = [
|
||||
{:start_expr, 1, 2, '=', ' if true do '},
|
||||
{:text, '\n TRUE \n'},
|
||||
{:middle_expr, 3, 3, '', ' else '},
|
||||
{:text, '\n FALSE \n'},
|
||||
{:end_expr, 5, 3, '', ' end '},
|
||||
{:eof, 7, 3}
|
||||
{:start_expr, 1, '=', ' if true do ', true},
|
||||
{:text, ' TRUE \n'},
|
||||
{:middle_expr, 3, '', ' else ', true},
|
||||
{:text, ' FALSE \n'},
|
||||
{:end_expr, 5, '', ' end ', true}
|
||||
]
|
||||
|
||||
assert T.tokenize(template, 1, 1, %{@opts | trim: true}) == {:ok, exprs}
|
||||
assert T.tokenize(template, 1, trim: true) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode with comment" do
|
||||
exprs = [
|
||||
{:text, '\n123'},
|
||||
{:eof, 2, 4}
|
||||
{:text, '123'}
|
||||
]
|
||||
|
||||
assert T.tokenize(' <%# comment %> \n123', 1, 1, %{@opts | trim: true}) == {:ok, exprs}
|
||||
assert T.tokenize(' <%# comment %> \n123', 1, trim: true) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode with CRLF" do
|
||||
exprs = [
|
||||
{:text, '0\n'},
|
||||
{:expr, 2, 3, '=', ' 12 '},
|
||||
{:text, '\n34'},
|
||||
{:eof, 3, 3}
|
||||
{:text, '0\r\n'},
|
||||
{:expr, 2, '=', ' 12 ', true},
|
||||
{:text, '34'}
|
||||
]
|
||||
|
||||
assert T.tokenize('0\r\n <%= 12 %> \r\n34', 1, 1, %{@opts | trim: true}) == {:ok, exprs}
|
||||
assert T.tokenize('0\r\n <%= 12 %> \r\n34', 1, trim: true) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode set to false" do
|
||||
exprs = [
|
||||
{:text, ' '},
|
||||
{:expr, 1, 2, '=', ' 12 '},
|
||||
{:text, ' \n'},
|
||||
{:eof, 2, 1}
|
||||
{:expr, 1, '=', ' 12 ', false},
|
||||
{:text, ' \n'}
|
||||
]
|
||||
|
||||
assert T.tokenize(' <%= 12 %> \n', 1, 1, %{@opts | trim: false}) == {:ok, exprs}
|
||||
assert T.tokenize(' <%= 12 %> \n', 1, trim: false) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode no false positives" do
|
||||
assert_not_trimmed = fn x ->
|
||||
assert T.tokenize(x, 1, 1, %{@opts | trim: false}) == T.tokenize(x, 1, 1, @opts)
|
||||
end
|
||||
assert_not_trimmed = fn x -> assert T.tokenize(x, 1, trim: true) == T.tokenize(x, 1) end
|
||||
|
||||
assert_not_trimmed.('foo <%= "bar" %> ')
|
||||
assert_not_trimmed.('\n <%= "foo" %>bar')
|
||||
@@ -258,13 +215,8 @@ defmodule EEx.TokenizerTest do
|
||||
assert_not_trimmed.(' <%= 01 %><%= 23 %>\n')
|
||||
end
|
||||
|
||||
test "returns error when there is start mark and no end mark" do
|
||||
assert T.tokenize('foo <% :bar', 1, 1, @opts) == {:error, 1, 12, "missing token '%>'"}
|
||||
assert T.tokenize('<%# true ', 1, 1, @opts) == {:error, 1, 10, "missing token '%>'"}
|
||||
end
|
||||
|
||||
test "marks invalid expressions as regular expressions" do
|
||||
assert T.tokenize('<% 1 $ 2 %>', 1, 1, @opts) ==
|
||||
{:ok, [{:expr, 1, 1, [], ' 1 $ 2 '}, {:eof, 1, 12}]}
|
||||
test "raise syntax error when there is start mark and no end mark" do
|
||||
assert T.tokenize('foo <% :bar', 1) == {:error, 1, "missing token '%>'"}
|
||||
assert T.tokenize('<%# true ', 1) == {:error, 1, "missing token '%>'"}
|
||||
end
|
||||
end
|
||||
|
||||
+13
-105
@@ -64,39 +64,9 @@ defmodule EExTest do
|
||||
assert_eval(" • • •\n Jößé Vâlìm Jößé Vâlìm\n", template)
|
||||
end
|
||||
|
||||
test "no spaces" do
|
||||
string = """
|
||||
<%=cond do%>
|
||||
<%false ->%>
|
||||
this
|
||||
<%true ->%>
|
||||
that
|
||||
<%end%>
|
||||
"""
|
||||
|
||||
expected = "\n that\n\n"
|
||||
assert_eval(expected, string, [])
|
||||
end
|
||||
|
||||
test "trim mode" do
|
||||
string = "<%= 123 %> \n \n <%= 789 %>"
|
||||
expected = "123\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
|
||||
string = "<%= 123 %> \n456\n <%= 789 %>"
|
||||
expected = "123\n456\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
|
||||
string = "<%= 123 %> \n <%= 456 %> \n <%= 789 %>"
|
||||
expected = "123\n456\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
|
||||
string = "\n <%= 123 %> \n <%= 456 %> \n <%= 789 %> \n"
|
||||
expected = "123\n456\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
|
||||
string = "\r\n <%= 123 %> \r\n <%= 456 %> \r\n <%= 789 %> \r\n"
|
||||
expected = "123\n456\n789"
|
||||
expected = "123456\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
|
||||
@@ -110,7 +80,7 @@ defmodule EExTest do
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
expected = "\n that\n"
|
||||
expected = " that\n"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
|
||||
@@ -122,32 +92,7 @@ defmodule EExTest do
|
||||
<%= "Fourth line" %>
|
||||
"""
|
||||
|
||||
expected = "First line\nSecond line\nThird line\nFourth line"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
|
||||
test "trim mode with no spaces" do
|
||||
string = """
|
||||
<%=if true do%>
|
||||
this
|
||||
<%else%>
|
||||
that
|
||||
<%end%>
|
||||
"""
|
||||
|
||||
expected = "\n this\n"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
|
||||
string = """
|
||||
<%=cond do%>
|
||||
<%false ->%>
|
||||
this
|
||||
<%true ->%>
|
||||
that
|
||||
<%end%>
|
||||
"""
|
||||
|
||||
expected = "\n that\n"
|
||||
expected = "First lineSecond lineThird lineFourth line"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
|
||||
@@ -167,7 +112,7 @@ defmodule EExTest do
|
||||
assert_eval("foo ", "foo <%= if false do %>bar<% end %>")
|
||||
end
|
||||
|
||||
test "embedded code with do preceded by bracket" do
|
||||
test "embedded code with do preceeded by bracket" do
|
||||
assert_eval("foo bar", "foo <%= if {true}do %>bar<% end %>")
|
||||
assert_eval("foo bar", "foo <%= if (true)do %>bar<% end %>")
|
||||
assert_eval("foo bar", "foo <%= if [true]do %>bar<% end %>")
|
||||
@@ -247,27 +192,25 @@ defmodule EExTest do
|
||||
|
||||
describe "raises syntax errors" do
|
||||
test "when the token is invalid" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1:12: missing token '%>'", fn ->
|
||||
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:18: unexpected middle of expression <% else %>",
|
||||
fn ->
|
||||
EEx.compile_string("<% if true %> foo<% else %>bar<% end %>")
|
||||
end
|
||||
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:5: unexpected end of expression <% end %>", fn ->
|
||||
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:17: unexpected end of string, expected a closing '<% end %>'"
|
||||
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 %>")
|
||||
@@ -275,7 +218,7 @@ defmodule EExTest do
|
||||
end
|
||||
|
||||
test "when nested end expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1:30: unexpected end of expression <% end %>", fn ->
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected end of expression <% end %>", fn ->
|
||||
EEx.compile_string("foo <% if true do %><% end %><% end %>")
|
||||
end
|
||||
end
|
||||
@@ -314,13 +257,13 @@ defmodule EExTest do
|
||||
|
||||
describe "error messages" do
|
||||
test "honor line numbers" do
|
||||
assert_raise EEx.SyntaxError, "nofile:99:12: missing token '%>'", fn ->
|
||||
assert_raise EEx.SyntaxError, "nofile:99: missing token '%>'", fn ->
|
||||
EEx.compile_string("foo <%= bar", line: 99)
|
||||
end
|
||||
end
|
||||
|
||||
test "honor file names" do
|
||||
assert_raise EEx.SyntaxError, "my_file.eex:1:12: missing token '%>'", fn ->
|
||||
assert_raise EEx.SyntaxError, "my_file.eex:1: missing token '%>'", fn ->
|
||||
EEx.compile_string("foo <%= bar", file: "my_file.eex")
|
||||
end
|
||||
end
|
||||
@@ -531,41 +474,6 @@ defmodule EExTest do
|
||||
|
||||
assert_eval("\n\n Good\n \n", string)
|
||||
end
|
||||
|
||||
test "line and column meta" do
|
||||
parser_options = Code.get_compiler_option(:parser_options)
|
||||
Code.put_compiler_option(:parser_options, columns: true)
|
||||
|
||||
try do
|
||||
indentation = 12
|
||||
|
||||
ast =
|
||||
EEx.compile_string(
|
||||
"""
|
||||
<%= f() %> <% f() %>
|
||||
<%= f fn -> %>
|
||||
<%= f() %>
|
||||
<% end %>
|
||||
""",
|
||||
indentation: indentation
|
||||
)
|
||||
|
||||
{_, calls} =
|
||||
Macro.prewalk(ast, [], fn
|
||||
{:f, meta, _args} = expr, acc -> {expr, [meta | acc]}
|
||||
other, acc -> {other, acc}
|
||||
end)
|
||||
|
||||
assert Enum.reverse(calls) == [
|
||||
[line: 1, column: indentation + 5],
|
||||
[line: 1, column: indentation + 15],
|
||||
[line: 2, column: indentation + 7],
|
||||
[line: 3, column: indentation + 9]
|
||||
]
|
||||
after
|
||||
Code.put_compiler_option(:parser_options, parser_options)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "buffers" do
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
warn_exported_vars,
|
||||
%% warn_missing_spec,
|
||||
%% warn_untyped_record,
|
||||
warnings_as_errors,
|
||||
debug_info,
|
||||
{outdir, "ebin/"}
|
||||
]}.
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
defmodule Diff do
|
||||
@moduledoc """
|
||||
Utilities for comparing build artifacts.
|
||||
"""
|
||||
|
||||
@known_chunks ~w(
|
||||
abstract_code
|
||||
debug_info
|
||||
attributes
|
||||
compile_info
|
||||
exports
|
||||
labeled_exports
|
||||
imports
|
||||
indexed_imports
|
||||
locals
|
||||
labeled_locals
|
||||
atoms
|
||||
)a
|
||||
|
||||
@doc """
|
||||
Compares the build artifacts of two build directories.
|
||||
"""
|
||||
@spec compare_dirs(Path.t(), Path.t()) ::
|
||||
{
|
||||
only1_paths :: list(Path.t()),
|
||||
only2_paths :: list(Path.t()),
|
||||
diff :: list({Path.t(), diff :: String.t()})
|
||||
}
|
||||
def compare_dirs(dir1, dir2) do
|
||||
dir1 = Path.expand(dir1)
|
||||
dir2 = Path.expand(dir2)
|
||||
|
||||
assert_dir!(dir1)
|
||||
assert_dir!(dir2)
|
||||
|
||||
dir1_paths = relative_paths(dir1)
|
||||
dir2_paths = relative_paths(dir2)
|
||||
|
||||
only1_paths = dir1_paths -- dir2_paths
|
||||
only2_paths = dir2_paths -- dir1_paths
|
||||
common_paths = dir1_paths -- only1_paths
|
||||
common_files = Enum.reject(common_paths, &File.dir?/1)
|
||||
|
||||
diff =
|
||||
Enum.flat_map(common_files, fn path ->
|
||||
file1 = Path.join(dir1, path)
|
||||
file2 = Path.join(dir2, path)
|
||||
|
||||
case compare_files(file1, file2) do
|
||||
:eq -> []
|
||||
{:diff, diff} -> [{path, diff}]
|
||||
end
|
||||
end)
|
||||
|
||||
{only1_paths, only2_paths, diff}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares the contents of two files.
|
||||
|
||||
If the files are BEAM files, it performs a more human-friendly
|
||||
"BEAM-diff".
|
||||
"""
|
||||
@spec compare_files(Path.t(), Path.t()) :: :eq | {:diff, diff :: String.t()}
|
||||
def compare_files(file1, file2) do
|
||||
content1 = File.read!(file1)
|
||||
content2 = File.read!(file2)
|
||||
|
||||
if content1 == content2 do
|
||||
:eq
|
||||
else
|
||||
diff =
|
||||
if String.ends_with?(file1, ".beam") do
|
||||
beam_diff(file1, content1, file2, content2)
|
||||
else
|
||||
file_diff(file1, file2)
|
||||
end
|
||||
|
||||
{:diff, diff}
|
||||
end
|
||||
end
|
||||
|
||||
defp beam_diff(file1, content1, file2, content2) do
|
||||
with {:ok, {module, chunks1}} <- :beam_lib.chunks(content1, @known_chunks),
|
||||
{:ok, {^module, chunks2}} <- :beam_lib.chunks(content2, @known_chunks),
|
||||
true <- chunks1 != chunks2 do
|
||||
for {chunk1, chunk2} <- Enum.zip(chunks1, chunks2), chunk1 != chunk2 do
|
||||
tmp_file1 =
|
||||
chunk1
|
||||
|> inspect(pretty: true, limit: :infinity)
|
||||
|> write_tmp()
|
||||
|
||||
tmp_file2 =
|
||||
chunk2
|
||||
|> inspect(pretty: true, limit: :infinity)
|
||||
|> write_tmp()
|
||||
|
||||
file_diff(tmp_file1, tmp_file2)
|
||||
end
|
||||
else
|
||||
_ ->
|
||||
file_diff(file1, file2)
|
||||
end
|
||||
end
|
||||
|
||||
defp file_diff(file1, file2) do
|
||||
{diff, _} = System.cmd("diff", [file1, file2])
|
||||
diff
|
||||
end
|
||||
|
||||
defp relative_paths(dir) do
|
||||
dir
|
||||
|> Path.join("**")
|
||||
|> Path.wildcard()
|
||||
|> Enum.map(&Path.relative_to(&1, dir))
|
||||
end
|
||||
|
||||
defp assert_dir!(dir) do
|
||||
unless File.dir?(dir) do
|
||||
raise ArgumentError, "#{inspect(dir)} is not a directory"
|
||||
end
|
||||
end
|
||||
|
||||
defp write_tmp(content) do
|
||||
filename = generate_tmp_filename()
|
||||
File.mkdir_p!("tmp")
|
||||
File.write!(Path.join("tmp", filename), content)
|
||||
Path.join("tmp", filename)
|
||||
end
|
||||
|
||||
defp generate_tmp_filename do
|
||||
sec = :os.system_time(:second)
|
||||
rand = :rand.uniform(999_999_999)
|
||||
scheduler_id = :erlang.system_info(:scheduler_id)
|
||||
"tmp-#{sec}-#{rand}-#{scheduler_id}"
|
||||
end
|
||||
end
|
||||
|
||||
case System.argv() do
|
||||
[dir1, dir2] ->
|
||||
case Diff.compare_dirs(dir1, dir2) do
|
||||
{[], [], []} ->
|
||||
IO.puts("#{inspect(dir1)} and #{inspect(dir2)} are equal")
|
||||
|
||||
{only1, only2, diff} ->
|
||||
for path <- only1, do: IO.puts("Only in #{dir1}: #{path}")
|
||||
for path <- only2, do: IO.puts("Only in #{dir2}: #{path}")
|
||||
for {path, diff} <- diff, do: IO.puts("Diff #{path}:\n#{diff}")
|
||||
|
||||
System.halt(1)
|
||||
end
|
||||
|
||||
_ ->
|
||||
IO.puts("Please, provide two directories as arguments")
|
||||
System.halt(1)
|
||||
end
|
||||
+11
-14
@@ -1,10 +1,10 @@
|
||||
# Returns config for Elixir docs
|
||||
[
|
||||
extras: Path.wildcard("lib/elixir/pages/*.md") ++ ["CHANGELOG.md"],
|
||||
extras: Path.wildcard("lib/elixir/pages/*.md"),
|
||||
groups_for_functions: [
|
||||
Guards: & &1[:guard] == true
|
||||
],
|
||||
skip_undefined_reference_warnings_on: ["lib/elixir/pages/compatibility-and-deprecations.md"],
|
||||
skip_undefined_reference_warnings_on: ["compatibility-and-deprecations"],
|
||||
groups_for_modules: [
|
||||
# [Kernel, Kernel.SpecialForms],
|
||||
|
||||
@@ -89,18 +89,15 @@
|
||||
Kernel.ParallelCompiler,
|
||||
Macro,
|
||||
Macro.Env
|
||||
],
|
||||
Deprecated: [
|
||||
Behaviour,
|
||||
Dict,
|
||||
GenEvent,
|
||||
HashDict,
|
||||
HashSet,
|
||||
Set,
|
||||
Supervisor.Spec
|
||||
]
|
||||
|
||||
## Automatically detected groups
|
||||
|
||||
# Deprecated: [
|
||||
# Behaviour,
|
||||
# Dict,
|
||||
# GenEvent,
|
||||
# HashDict,
|
||||
# HashSet,
|
||||
# Set,
|
||||
# Supervisor.Spec
|
||||
# ]
|
||||
]
|
||||
]
|
||||
|
||||
@@ -10,4 +10,4 @@ main([Source, Target, Version]) ->
|
||||
Props = lists:keyreplace(vsn, 1, Props1, {vsn, Version}),
|
||||
AppDef = io_lib:format("~tp.~n", [{application, Name, Props}]),
|
||||
ok = file:write_file(Target, AppDef),
|
||||
io:format("Generated ~ts app~n", [Name]).
|
||||
io:format("Generated ~ts.app~n", [Name]).
|
||||
|
||||
+11
-70
@@ -6,8 +6,8 @@ defmodule Access do
|
||||
keys of any type in a data structure via the `data[key]` syntax.
|
||||
|
||||
`Access` supports keyword lists (`Keyword`) and maps (`Map`) out
|
||||
of the box. Keywords supports only atoms keys, keys for maps can
|
||||
be of any type. Both returns `nil` if the key does not exist:
|
||||
of the box. The key can be of any type and it returns `nil` if
|
||||
the key does not exist:
|
||||
|
||||
iex> keywords = [a: 1, b: 2]
|
||||
iex> keywords[:a]
|
||||
@@ -236,25 +236,6 @@ defmodule Access do
|
||||
:error
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `fetch/2` but returns the value directly,
|
||||
or raises a `KeyError` exception if `key` is not found.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Access.fetch!(%{name: "meg", age: 26}, :name)
|
||||
"meg"
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec fetch!(container, term) :: term
|
||||
def fetch!(container, key) do
|
||||
case fetch(container, key) do
|
||||
{:ok, value} -> value
|
||||
:error -> raise(KeyError, key: key, term: container)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets the value for the given key in a container (a map, keyword
|
||||
list, or struct that implements the `Access` behaviour).
|
||||
@@ -329,14 +310,6 @@ defmodule Access do
|
||||
|
||||
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`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Access.get_and_update([a: 1], :a, fn current_value ->
|
||||
...> {current_value, current_value + 1}
|
||||
...> end)
|
||||
{1, [a: 2]}
|
||||
|
||||
"""
|
||||
@spec get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
|
||||
when get_value: var, data: container
|
||||
@@ -683,68 +656,36 @@ defmodule Access do
|
||||
end
|
||||
|
||||
defp at(:get_and_update, data, index, next) when is_list(data) do
|
||||
get_and_update_at(data, index, next, [], fn -> nil end)
|
||||
get_and_update_at(data, index, next, [])
|
||||
end
|
||||
|
||||
defp at(_op, data, _index, _next) do
|
||||
raise "Access.at/1 expected a list, got: #{inspect(data)}"
|
||||
end
|
||||
|
||||
defp get_and_update_at([head | rest], 0, next, updates, _default_fun) do
|
||||
defp get_and_update_at([head | rest], 0, next, updates) do
|
||||
case next.(head) do
|
||||
{get, update} -> {get, :lists.reverse([update | updates], rest)}
|
||||
:pop -> {head, :lists.reverse(updates, rest)}
|
||||
end
|
||||
end
|
||||
|
||||
defp get_and_update_at([_ | _] = list, index, next, updates, default_fun) when index < 0 do
|
||||
defp get_and_update_at(list, index, next, updates) when index < 0 do
|
||||
list_length = length(list)
|
||||
|
||||
if list_length + index >= 0 do
|
||||
get_and_update_at(list, list_length + index, next, updates, default_fun)
|
||||
get_and_update_at(list, list_length + index, next, updates)
|
||||
else
|
||||
{default_fun.(), list}
|
||||
{nil, list}
|
||||
end
|
||||
end
|
||||
|
||||
defp get_and_update_at([head | rest], index, next, updates, default_fun) when index > 0 do
|
||||
get_and_update_at(rest, index - 1, next, [head | updates], default_fun)
|
||||
defp get_and_update_at([head | rest], index, next, updates) when index > 0 do
|
||||
get_and_update_at(rest, index - 1, next, [head | updates])
|
||||
end
|
||||
|
||||
defp get_and_update_at([], _index, _next, updates, default_fun) do
|
||||
{default_fun.(), :lists.reverse(updates)}
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Same as `at/1` except that it raises `Enum.OutOfBoundsError`
|
||||
if the given index is out of bounds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_in([:a, :b, :c], [Access.at!(2)])
|
||||
:c
|
||||
iex> get_in([:a, :b, :c], [Access.at!(3)])
|
||||
** (Enum.OutOfBoundsError) out of bounds error
|
||||
|
||||
"""
|
||||
@spec at!(integer) :: access_fun(data :: list, get_value :: term)
|
||||
def at!(index) when is_integer(index) do
|
||||
fn op, data, next -> at!(op, data, index, next) end
|
||||
end
|
||||
|
||||
defp at!(:get, data, index, next) when is_list(data) do
|
||||
case Enum.fetch(data, index) do
|
||||
{:ok, value} -> next.(value)
|
||||
:error -> raise Enum.OutOfBoundsError
|
||||
end
|
||||
end
|
||||
|
||||
defp at!(:get_and_update, data, index, next) when is_list(data) do
|
||||
get_and_update_at(data, index, next, [], fn -> raise Enum.OutOfBoundsError end)
|
||||
end
|
||||
|
||||
defp at!(_op, data, _index, _next) do
|
||||
raise "Access.at!/1 expected a list, got: #{inspect(data)}"
|
||||
defp get_and_update_at([], _index, _next, updates) do
|
||||
{nil, :lists.reverse(updates)}
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
|
||||
+1
-28
@@ -201,7 +201,7 @@ defmodule Agent do
|
||||
@doc false
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
unless Module.has_attribute?(__MODULE__, :doc) do
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
@@ -423,15 +423,6 @@ defmodule Agent do
|
||||
Same as `update/3` but a module, function, and arguments are expected
|
||||
instead of an anonymous function. The state is added as first
|
||||
argument to the given list of arguments.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.update(pid, Kernel, :+, [12])
|
||||
:ok
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
54
|
||||
|
||||
"""
|
||||
@spec update(agent, module, atom, [term], timeout) :: :ok
|
||||
def update(agent, module, fun, args, timeout \\ 5000) do
|
||||
@@ -447,15 +438,6 @@ defmodule Agent do
|
||||
|
||||
Note that `cast` returns `:ok` immediately, regardless of whether `agent` (or
|
||||
the node it should live on) exists.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.cast(pid, fn state -> state + 1 end)
|
||||
:ok
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
43
|
||||
|
||||
"""
|
||||
@spec cast(agent, (state -> state)) :: :ok
|
||||
def cast(agent, fun) when is_function(fun, 1) do
|
||||
@@ -468,15 +450,6 @@ defmodule Agent do
|
||||
Same as `cast/2` but a module, function, and arguments are expected
|
||||
instead of an anonymous function. The state is added as first
|
||||
argument to the given list of arguments.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.cast(pid, Kernel, :+, [12])
|
||||
:ok
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
54
|
||||
|
||||
"""
|
||||
@spec cast(agent, module, atom, [term]) :: :ok
|
||||
def cast(agent, module, fun, args) do
|
||||
|
||||
+97
-294
@@ -7,121 +7,79 @@ defmodule Application do
|
||||
programming languages, but with some additional characteristics.
|
||||
|
||||
An application is a component implementing some specific functionality, with a
|
||||
standardized directory structure, configuration, and life cycle. Applications
|
||||
are *loaded*, *started*, and *stopped*. Each application also has its own
|
||||
environment, which provides a unified API for configuring each application.
|
||||
standardized directory structure, configuration, and lifecycle. Applications
|
||||
are *loaded*, *started*, and *stopped*.
|
||||
|
||||
Developers typically interact with the application environment and its
|
||||
callback module. Therefore those will be the topics we will cover first
|
||||
before jumping into details about the application resource file and life-cycle.
|
||||
## The application resource file
|
||||
|
||||
Applications are specified in their [*resource
|
||||
file*](http://erlang.org/doc/man/app.html), which is a file called `APP.app`,
|
||||
where `APP` is the application name. For example, the application resource
|
||||
file of the OTP application `ex_unit` is called `ex_unit.app`.
|
||||
|
||||
You'll find the resource file of an application in its `ebin` directory, it is
|
||||
generated automatically by Mix. Some of its keys are taken from the keyword
|
||||
lists returned by the `project/0` and `application/0` functions defined in
|
||||
`mix.exs`, and others are generated by Mix itself.
|
||||
|
||||
You can learn more about the generation of application resource files in the
|
||||
documentation of `Mix.Tasks.Compile.App`, available as well by running
|
||||
`mix help compile.app`.
|
||||
|
||||
## The application environment
|
||||
|
||||
Each application has its own environment. The environment is a keyword list
|
||||
that maps atoms to terms. Note that this environment is unrelated to the
|
||||
operating system environment.
|
||||
The key `env` of an application resource file has a list of tuples that map
|
||||
atoms to terms, and its contents are known as the application *environment*.
|
||||
Note that this environment is unrelated to the operating system environment.
|
||||
|
||||
By default, the environment of an application is an empty list. In a Mix
|
||||
project's `mix.exs` file, you can set the `:env` key in `application/0`:
|
||||
project you can set that key in `application/0`:
|
||||
|
||||
def application do
|
||||
[env: [db_host: "localhost"]]
|
||||
[env: [redis_host: "localhost"]]
|
||||
end
|
||||
|
||||
Now, in your application, you can read this environment by using functions
|
||||
such as `fetch_env!/2` and friends:
|
||||
and the generated application resource file is going to have it included.
|
||||
|
||||
defmodule MyApp.DBClient do
|
||||
def start_link() do
|
||||
SomeLib.DBClient.start_link(host: db_host())
|
||||
end
|
||||
The environment is available after loading the application, which is a process
|
||||
explained later:
|
||||
|
||||
defp db_host do
|
||||
Application.fetch_env!(:my_app, :db_host)
|
||||
end
|
||||
end
|
||||
Application.load(:APP_NAME)
|
||||
#=> :ok
|
||||
|
||||
Application.get_env(:APP_NAME, :redis_host)
|
||||
#=> "localhost"
|
||||
|
||||
In Mix projects, the environment of the application and its dependencies can
|
||||
be overridden via the `config/config.exs` file. For example, someone using
|
||||
your application can override its `:db_host` environment variable as follows:
|
||||
be overridden via the `config/config.exs` file. If you start the application
|
||||
with Mix, that configuration is available at compile time, and at runtime too,
|
||||
but take into account it is not included in the generated application resource
|
||||
file, and it is not available if you start the application without Mix.
|
||||
|
||||
import Config
|
||||
config :my_app, :db_host, "db.local"
|
||||
For example, someone using your application can override its `:redis_host`
|
||||
environment variable as follows:
|
||||
|
||||
You can also change the application environment dynamically by using functions
|
||||
such as `put_env/3` and `delete_env/2`. However, as a rule of thumb, each application
|
||||
is responsible for its own environment. Please do not use the functions in this
|
||||
module for directly accessing or modifying the environment of other applications.
|
||||
config :APP_NAME, redis_host: "redis.local"
|
||||
|
||||
### Compile-time environment
|
||||
The function `put_env/3` allows dynamic configuration of the application
|
||||
environment, but as a rule of thumb each application is responsible for its
|
||||
own environment. Please do not use the functions in this module for directly
|
||||
accessing or modifying the environment of other applications.
|
||||
|
||||
In the previous example, we read the application environment at runtime:
|
||||
|
||||
defmodule MyApp.DBClient do
|
||||
def start_link() do
|
||||
SomeLib.DBClient.start_link(host: db_host())
|
||||
end
|
||||
|
||||
defp db_host do
|
||||
Application.fetch_env!(:my_app, :db_host)
|
||||
end
|
||||
end
|
||||
|
||||
In other words, the environment key `:db_host` for application `:my_app`
|
||||
will only be read when `MyApp.DBClient` effectively starts. While reading
|
||||
the application environment at runtime is the preferred approach, in some
|
||||
rare occasions you may want to use the application environment to configure
|
||||
the compilation of a certain project. This is often done by calling `get_env/3`
|
||||
outside of a function:
|
||||
|
||||
defmodule MyApp.DBClient do
|
||||
@db_host Application.get_env(:my_app, :db_host, "db.local")
|
||||
|
||||
def start_link() do
|
||||
SomeLib.DBClient.start_link(host: @db_host)
|
||||
end
|
||||
end
|
||||
|
||||
This approach has one big limitation: if you change the value of the
|
||||
application environment after the code is compiled, the value used at
|
||||
runtime is not going to change! For example, if your `config/runtime.exs`
|
||||
has:
|
||||
|
||||
config :my_app, :db_host, "db.production"
|
||||
|
||||
This value will have no effect as the code was compiled to connect to "db.local",
|
||||
which is mostly likely unavailable in the production environment.
|
||||
|
||||
For those reasons, reading the application environment at runtime should be the
|
||||
first choice. However, if you really have to read the application environment
|
||||
during compilation, we recommend you to use `compile_env/3` instead:
|
||||
|
||||
@db_host Application.compile_env(:my_app, :db_host, "db.local")
|
||||
|
||||
By using `compile_env/3`, tools like Mix will store the values used during
|
||||
compilation and compare the compilation values with the runtime values whenever
|
||||
your system starts, raising an error in case they differ.
|
||||
The application environment can be overridden via the `-config` option of
|
||||
`erl`, as well as command-line options, as we are going to see below.
|
||||
|
||||
## The application callback module
|
||||
|
||||
Applications can be loaded, started, and stopped. Generally, build tools
|
||||
like Mix take care of starting an application and all of its dependencies
|
||||
for you, but you can also do it manually by calling:
|
||||
|
||||
{:ok, _} = Application.ensure_all_started(:some_app)
|
||||
|
||||
When an application starts, developers may configure a callback module
|
||||
that executes custom code. Developers use this callback to start the
|
||||
application supervision tree.
|
||||
|
||||
The first step to do so is to add a `:mod` key to the `application/0`
|
||||
definition in your `mix.exs` file. It expects a tuple, with the application
|
||||
callback module and start argument (commonly an empty list):
|
||||
The `mod` key of an application resource file configures an application
|
||||
callback module and start argument:
|
||||
|
||||
def application do
|
||||
[mod: {MyApp, []}]
|
||||
end
|
||||
|
||||
This key is optional, only needed for applications that start a supervision tree.
|
||||
|
||||
The `MyApp` module given to `:mod` needs to implement the `Application` behaviour.
|
||||
This can be done by putting `use Application` in that module and implementing the
|
||||
`c:start/2` callback, for example:
|
||||
@@ -158,20 +116,7 @@ defmodule Application do
|
||||
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`.
|
||||
|
||||
## The application resource file
|
||||
|
||||
In the sections above, we have configured an application in the
|
||||
`application/0` section of the `mix.exs` file. Ultimately, Mix will use
|
||||
this configuration to create an [*application resource
|
||||
file*](http://erlang.org/doc/man/app.html), which is a file called
|
||||
`APP_NAME.app`. For example, the application resource file of the OTP
|
||||
application `ex_unit` is called `ex_unit.app`.
|
||||
|
||||
You can learn more about the generation of application resource files in
|
||||
the documentation of `Mix.Tasks.Compile.App`, available as well by running
|
||||
`mix help compile.app`.
|
||||
|
||||
## The application life cycle
|
||||
## The application lifecycle
|
||||
|
||||
### Loading applications
|
||||
|
||||
@@ -181,8 +126,16 @@ defmodule Application do
|
||||
Application.load(:ex_unit)
|
||||
#=> :ok
|
||||
|
||||
If an application has included applications, they are also loaded. And the
|
||||
procedure recurses if they in turn have included applications. Included
|
||||
applications are unrelated to applications in Mix umbrella projects, they are
|
||||
an Erlang/OTP concept that has to do with coordinated starts.
|
||||
|
||||
When an application is loaded, the environment specified in its resource file
|
||||
is merged with any overrides from config files.
|
||||
is merged with any overrides from config files passed to `erl` via the
|
||||
`-config` option. It is worth highlighting that releases pass `sys.config`
|
||||
this way. The resulting environment can still be overridden again via specific
|
||||
`-Application` options passed to `erl`.
|
||||
|
||||
Loading an application *does not* load its modules.
|
||||
|
||||
@@ -202,15 +155,17 @@ defmodule Application do
|
||||
system. Instead, you start one or more applications, each with their own
|
||||
initialization and termination logic.
|
||||
|
||||
When an application is started, the `Application.load/1` is automatically
|
||||
invoked if it hasn't been done yet. Then, it checks if the dependencies listed
|
||||
in the `applications` key of the resource file are already started. Having at
|
||||
least one dependency not started is an error condition. Functions like
|
||||
`ensure_all_started/1` takes care of starting an application and all of its
|
||||
dependencies for you.
|
||||
When an application is started, the runtime loads it if it hasn't been loaded
|
||||
yet (in the technical sense described above). Then, it checks if the
|
||||
dependencies listed in the `applications` key of the resource file are already
|
||||
started. Having at least one dependency not started is an error condition, but
|
||||
when you start an application with `mix run`, Mix takes care of starting all
|
||||
the dependencies for you, so in practice you don't need to worry about it
|
||||
unless you are starting applications manually with the API provided by this
|
||||
module.
|
||||
|
||||
If the application does not have a callback module configured, starting is
|
||||
done at this point. Otherwise, its `c:start/2` callback is invoked. The PID of
|
||||
done at this point. Otherwise, its `c:start/2` callback if invoked. The PID of
|
||||
the top-level supervisor returned by this function is stored by the runtime
|
||||
for later use, and the returned application state is saved too, if any.
|
||||
|
||||
@@ -226,9 +181,9 @@ defmodule Application do
|
||||
|
||||
Stopping an application with a callback module has three steps:
|
||||
|
||||
1. If present, invoke the optional callback `c:prep_stop/1`.
|
||||
2. Terminate the top-level supervisor.
|
||||
3. Invoke the required callback `c:stop/1`.
|
||||
1. If present, invoke the optional callback `c:prep_stop/1`.
|
||||
2. Terminate the top-level supervisor.
|
||||
3. Invoke the required callback `c:stop/1`.
|
||||
|
||||
The arguments passed to the callbacks are related to the state optionally
|
||||
returned by `c:start/2`, and are documented in the section about the callback
|
||||
@@ -248,16 +203,17 @@ defmodule Application do
|
||||
|
||||
## Tooling
|
||||
|
||||
The Mix build tool automates most of the application management tasks. For example,
|
||||
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 `mix release` to 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.
|
||||
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
|
||||
@@ -297,7 +253,7 @@ defmodule Application do
|
||||
application specification key `:start_phases` is not `:undefined`.
|
||||
|
||||
`start_args` are the arguments passed to the application in the `:mod`
|
||||
specification key (for example, `mod: {MyApp, [:my_args]}`).
|
||||
specification key (e.g., `mod: {MyApp, [:my_args]}`).
|
||||
|
||||
This function should either return `{:ok, pid}` or `{:ok, pid, state}` if
|
||||
startup is successful. `pid` should be the PID of the top supervisor. `state`
|
||||
@@ -457,135 +413,12 @@ defmodule Application do
|
||||
:application.get_all_env(app)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads the application environment at compilation time.
|
||||
|
||||
Similar to `get_env/3`, except it must be used to read values
|
||||
at compile time. This allows Elixir to track when configuration
|
||||
values change between compile time and runtime.
|
||||
|
||||
The first argument is the application name. The second argument
|
||||
`key_or_path` is either an atom key or a path to traverse in
|
||||
search of the configuration, starting with an atom key.
|
||||
|
||||
For example, imagine the following configuration:
|
||||
|
||||
config :my_app, :key, [foo: [bar: :baz]]
|
||||
|
||||
We can access it during compile time as:
|
||||
|
||||
Application.compile_env(:my_app, :key)
|
||||
#=> [foo: [bar: :baz]]
|
||||
|
||||
Application.compile_env(:my_app, [:key, :foo])
|
||||
#=> [bar: :baz]
|
||||
|
||||
Application.compile_env(:my_app, [:key, :foo, :bar])
|
||||
#=> :baz
|
||||
|
||||
A default value can also be given as third argument. If
|
||||
any of the keys in the path along the way is missing, the
|
||||
default value is used:
|
||||
|
||||
Application.compile_env(:my_app, [:unknown, :foo, :bar], :default)
|
||||
#=> :default
|
||||
|
||||
Application.compile_env(:my_app, [:key, :unknown, :bar], :default)
|
||||
#=> :default
|
||||
|
||||
Application.compile_env(:my_app, [:key, :foo, :unknown], :default)
|
||||
#=> :default
|
||||
|
||||
Giving a path is useful to let Elixir know that only certain paths
|
||||
in a large configuration are compile time dependent.
|
||||
"""
|
||||
# TODO: Warn on v1.14 if get_env/fetch_env/fetch_env! is used at compile time instead of compile_env
|
||||
@doc since: "1.10.0"
|
||||
@spec compile_env(app, key | list, value) :: value
|
||||
defmacro compile_env(app, key_or_path, default \\ nil) when is_atom(app) do
|
||||
if __CALLER__.function do
|
||||
raise "Application.compile_env/3 cannot be called inside functions, only in the module body"
|
||||
end
|
||||
|
||||
quote do
|
||||
Application.__compile_env__(unquote(app), unquote(key_or_path), unquote(default), __ENV__)
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def __compile_env__(app, key_or_path, default, env) do
|
||||
case fetch_compile_env(app, key_or_path, env) do
|
||||
{:ok, value} -> value
|
||||
:error -> default
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads the application environment at compilation time or raises.
|
||||
|
||||
This is the same as `compile_env/3` but it raises an
|
||||
`ArgumentError` if the configuration is not available.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec compile_env!(app, key | list) :: value
|
||||
defmacro compile_env!(app, key_or_path) when is_atom(app) do
|
||||
if __CALLER__.function do
|
||||
raise "Application.compile_env!/2 cannot be called inside functions, only in the module body"
|
||||
end
|
||||
|
||||
quote do
|
||||
Application.__compile_env__!(unquote(app), unquote(key_or_path), __ENV__)
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def __compile_env__!(app, key_or_path, env) do
|
||||
case fetch_compile_env(app, key_or_path, env) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
:error ->
|
||||
raise ArgumentError,
|
||||
"could not fetch application environment #{inspect(key_or_path)} for application " <>
|
||||
"#{inspect(app)} #{fetch_env_failed_reason(app, key_or_path)}"
|
||||
end
|
||||
end
|
||||
|
||||
defp fetch_compile_env(app, key, env) when is_atom(key),
|
||||
do: fetch_compile_env(app, key, [], env)
|
||||
|
||||
defp fetch_compile_env(app, [key | paths], env) when is_atom(key),
|
||||
do: fetch_compile_env(app, key, paths, env)
|
||||
|
||||
defp fetch_compile_env(app, key, path, env) do
|
||||
return = traverse_env(fetch_env(app, key), path)
|
||||
|
||||
for tracer <- env.tracers do
|
||||
tracer.trace({:compile_env, app, [key | path], return}, env)
|
||||
end
|
||||
|
||||
return
|
||||
end
|
||||
|
||||
defp traverse_env(return, []), do: return
|
||||
defp traverse_env(:error, _paths), do: :error
|
||||
defp traverse_env({:ok, value}, [key | keys]), do: traverse_env(Access.fetch(value, key), keys)
|
||||
|
||||
@doc """
|
||||
Returns the value for `key` in `app`'s environment.
|
||||
|
||||
If the configuration parameter does not exist, the function returns the
|
||||
`default` value.
|
||||
|
||||
**Important:** if you are reading the application environment at compilation
|
||||
time, for example, inside the module definition instead of inside of a
|
||||
function, see `compile_env/3` instead.
|
||||
|
||||
**Important:** if you are writing a library to be used by other developers,
|
||||
it is generally recommended to avoid the application environment, as the
|
||||
application environment is effectively a global storage. For more information,
|
||||
read our [library guidelines](library-guidelines.md).
|
||||
|
||||
## Examples
|
||||
|
||||
`get_env/3` is commonly used to read the configuration of your OTP applications.
|
||||
@@ -615,10 +448,14 @@ defmodule Application do
|
||||
by module names). Our database engine can then traverse each repository in the
|
||||
list and then call `get_env(:my_app, Databases.RepoOne)` and so forth to retrieve
|
||||
the configuration of each one.
|
||||
|
||||
**Important:** if you are writing a library to be used by other developers,
|
||||
it is generally recommended to avoid the application environment, as the
|
||||
application environment is effectively a global storage. For more information,
|
||||
read our [library guidelines](library-guidelines.html).
|
||||
"""
|
||||
@spec get_env(app, key, value) :: value
|
||||
def get_env(app, key, default \\ nil) when is_atom(app) do
|
||||
maybe_warn_on_app_env_key(app, key)
|
||||
:application.get_env(app, key, default)
|
||||
end
|
||||
|
||||
@@ -629,8 +466,6 @@ defmodule Application do
|
||||
"""
|
||||
@spec fetch_env(app, key) :: {:ok, value} | :error
|
||||
def fetch_env(app, key) when is_atom(app) do
|
||||
maybe_warn_on_app_env_key(app, key)
|
||||
|
||||
case :application.get_env(app, key) do
|
||||
{:ok, value} -> {:ok, value}
|
||||
:undefined -> :error
|
||||
@@ -641,10 +476,6 @@ defmodule Application do
|
||||
Returns the value for `key` in `app`'s environment.
|
||||
|
||||
If the configuration parameter does not exist, raises `ArgumentError`.
|
||||
|
||||
**Important:** if you are reading the application environment at compilation
|
||||
time, for example, inside the module definition instead of inside of a
|
||||
function, see `compile_env!/2` instead.
|
||||
"""
|
||||
@spec fetch_env!(app, key) :: value
|
||||
def fetch_env!(app, key) when is_atom(app) do
|
||||
@@ -653,21 +484,23 @@ defmodule Application do
|
||||
value
|
||||
|
||||
:error ->
|
||||
raise ArgumentError,
|
||||
"could not fetch application environment #{inspect(key)} for application " <>
|
||||
"#{inspect(app)} #{fetch_env_failed_reason(app, key)}"
|
||||
end
|
||||
end
|
||||
vsn = :application.get_key(app, :vsn)
|
||||
app = inspect(app)
|
||||
key = inspect(key)
|
||||
|
||||
defp fetch_env_failed_reason(app, key) do
|
||||
vsn = :application.get_key(app, :vsn)
|
||||
case vsn do
|
||||
{:ok, _} ->
|
||||
raise ArgumentError,
|
||||
"could not fetch application environment #{key} for application #{app} " <>
|
||||
"because configuration #{key} was not set"
|
||||
|
||||
case vsn do
|
||||
{:ok, _} ->
|
||||
"because configuration at #{inspect(key)} was not set"
|
||||
|
||||
:undefined ->
|
||||
"because the application was not loaded nor configured"
|
||||
: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
|
||||
end
|
||||
end
|
||||
|
||||
@@ -690,13 +523,9 @@ defmodule Application do
|
||||
"""
|
||||
@spec put_env(app, key, value, timeout: timeout, persistent: boolean) :: :ok
|
||||
def put_env(app, key, value, opts \\ []) when is_atom(app) do
|
||||
maybe_warn_on_app_env_key(app, key)
|
||||
:application.set_env(app, key, value, opts)
|
||||
end
|
||||
|
||||
# TODO: Remove this once we support Erlang/OTP 22+ exclusively.
|
||||
@compile {:no_warn_undefined, {:application, :set_env, 2}}
|
||||
|
||||
@doc """
|
||||
Puts the environment for multiple apps at the same time.
|
||||
|
||||
@@ -711,7 +540,6 @@ defmodule Application do
|
||||
|
||||
It receives the same options as `put_env/4`. Returns `:ok`.
|
||||
"""
|
||||
@doc since: "1.9.0"
|
||||
@spec put_all_env([{app, [{key, value}]}], timeout: timeout, persistent: boolean) :: :ok
|
||||
def put_all_env(config, opts \\ []) when is_list(config) and is_list(opts) do
|
||||
# TODO: Remove function exported? check when we require Erlang/OTP 22+
|
||||
@@ -736,18 +564,9 @@ defmodule Application do
|
||||
"""
|
||||
@spec delete_env(app, key, timeout: timeout, persistent: boolean) :: :ok
|
||||
def delete_env(app, key, opts \\ []) when is_atom(app) do
|
||||
maybe_warn_on_app_env_key(app, key)
|
||||
:application.unset_env(app, key, opts)
|
||||
end
|
||||
|
||||
defp maybe_warn_on_app_env_key(_app, key) when is_atom(key),
|
||||
do: :ok
|
||||
|
||||
defp maybe_warn_on_app_env_key(app, key) do
|
||||
message = "passing non-atom as application env key is deprecated, got: #{inspect(key)}"
|
||||
IO.warn_once({Application, :key, app, key}, message, _stacktrace_drop_levels = 2)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Ensures the given `app` is started.
|
||||
|
||||
@@ -763,22 +582,6 @@ defmodule Application do
|
||||
:application.ensure_started(app, type)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Ensures the given `app` is loaded.
|
||||
|
||||
Same as `load/2` but returns `:ok` if the application was already
|
||||
loaded.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec ensure_loaded(app) :: :ok | {:error, term}
|
||||
def ensure_loaded(app) when is_atom(app) do
|
||||
case :application.load(app) do
|
||||
:ok -> :ok
|
||||
{:error, {:already_loaded, ^app}} -> :ok
|
||||
{:error, _} = error -> error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Ensures the given `app` and its applications are started.
|
||||
|
||||
|
||||
+2
-40
@@ -1,46 +1,8 @@
|
||||
defmodule Atom do
|
||||
@moduledoc """
|
||||
Atoms are constants whose values are their own name.
|
||||
|
||||
They are often useful to enumerate over distinct values, such as:
|
||||
|
||||
iex> :apple
|
||||
:apple
|
||||
iex> :orange
|
||||
:orange
|
||||
iex> :watermelon
|
||||
:watermelon
|
||||
|
||||
Atoms are equal if their names are equal.
|
||||
|
||||
iex> :apple == :apple
|
||||
true
|
||||
iex> :apple == :orange
|
||||
false
|
||||
|
||||
Often they are used to express the state of an operation, by using
|
||||
values such as `:ok` and `:error`.
|
||||
|
||||
The booleans `true` and `false` are also atoms:
|
||||
|
||||
iex> true == :true
|
||||
true
|
||||
iex> is_atom(false)
|
||||
true
|
||||
iex> is_boolean(:false)
|
||||
true
|
||||
|
||||
Elixir allows you to skip the leading `:` for the atoms `false`, `true`,
|
||||
and `nil`.
|
||||
|
||||
Atoms must be composed of Unicode characters such as letters, numbers,
|
||||
underscore, and `@`. If the keyword has a character that does not
|
||||
belong to the category above, such as spaces, you can wrap it in
|
||||
quotes:
|
||||
|
||||
iex> :"this is an atom with spaces"
|
||||
:"this is an atom with spaces"
|
||||
Convenience functions for working with atoms.
|
||||
|
||||
See also `Kernel.is_atom/1`.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
|
||||
+66
-66
@@ -10,85 +10,85 @@ defmodule Base do
|
||||
|
||||
## Base 16 alphabet
|
||||
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|:---------|------:|:---------|------:|:---------|------:|:---------|
|
||||
| 0 | 0 | 4 | 4 | 8 | 8 | 12 | C |
|
||||
| 1 | 1 | 5 | 5 | 9 | 9 | 13 | D |
|
||||
| 2 | 2 | 6 | 6 | 10 | A | 14 | E |
|
||||
| 3 | 3 | 7 | 7 | 11 | B | 15 | F |
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|---------:|------:|---------:|------:|---------:|------:|---------:|
|
||||
| 0| 0| 4| 4| 8| 8| 12| C|
|
||||
| 1| 1| 5| 5| 9| 9| 13| D|
|
||||
| 2| 2| 6| 6| 10| A| 14| E|
|
||||
| 3| 3| 7| 7| 11| B| 15| F|
|
||||
|
||||
## Base 32 alphabet
|
||||
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|:---------|------:|:---------|------:|:---------|------:|:---------|
|
||||
| 0 | A | 9 | J | 18 | S | 27 | 3 |
|
||||
| 1 | B | 10 | K | 19 | T | 28 | 4 |
|
||||
| 2 | C | 11 | L | 20 | U | 29 | 5 |
|
||||
| 3 | D | 12 | M | 21 | V | 30 | 6 |
|
||||
| 4 | E | 13 | N | 22 | W | 31 | 7 |
|
||||
| 5 | F | 14 | O | 23 | X | | |
|
||||
| 6 | G | 15 | P | 24 | Y | (pad) | = |
|
||||
| 7 | H | 16 | Q | 25 | Z | | |
|
||||
| 8 | I | 17 | R | 26 | 2 | | |
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|---------:|------:|---------:|------:|---------:|------:|---------:|
|
||||
| 0| A| 9| J| 18| S| 27| 3|
|
||||
| 1| B| 10| K| 19| T| 28| 4|
|
||||
| 2| C| 11| L| 20| U| 29| 5|
|
||||
| 3| D| 12| M| 21| V| 30| 6|
|
||||
| 4| E| 13| N| 22| W| 31| 7|
|
||||
| 5| F| 14| O| 23| X| | |
|
||||
| 6| G| 15| P| 24| Y| (pad)| =|
|
||||
| 7| H| 16| Q| 25| Z| | |
|
||||
| 8| I| 17| R| 26| 2| | |
|
||||
|
||||
|
||||
## Base 32 (extended hex) alphabet
|
||||
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|:---------|------:|:---------|------:|:---------|------:|:---------|
|
||||
| 0 | 0 | 9 | 9 | 18 | I | 27 | R |
|
||||
| 1 | 1 | 10 | A | 19 | J | 28 | S |
|
||||
| 2 | 2 | 11 | B | 20 | K | 29 | T |
|
||||
| 3 | 3 | 12 | C | 21 | L | 30 | U |
|
||||
| 4 | 4 | 13 | D | 22 | M | 31 | V |
|
||||
| 5 | 5 | 14 | E | 23 | N | | |
|
||||
| 6 | 6 | 15 | F | 24 | O | (pad) | = |
|
||||
| 7 | 7 | 16 | G | 25 | P | | |
|
||||
| 8 | 8 | 17 | H | 26 | Q | | |
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|---------:|------:|---------:|------:|---------:|------:|---------:|
|
||||
| 0| 0| 9| 9| 18| I| 27| R|
|
||||
| 1| 1| 10| A| 19| J| 28| S|
|
||||
| 2| 2| 11| B| 20| K| 29| T|
|
||||
| 3| 3| 12| C| 21| L| 30| U|
|
||||
| 4| 4| 13| D| 22| M| 31| V|
|
||||
| 5| 5| 14| E| 23| N| | |
|
||||
| 6| 6| 15| F| 24| O| (pad)| =|
|
||||
| 7| 7| 16| G| 25| P| | |
|
||||
| 8| 8| 17| H| 26| Q| | |
|
||||
|
||||
## Base 64 alphabet
|
||||
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|:----------|------:|:---------|------:|:---------|------:|:---------|
|
||||
| 0 | A | 17 | R | 34 | i | 51 | z |
|
||||
| 1 | B | 18 | S | 35 | j | 52 | 0 |
|
||||
| 2 | C | 19 | T | 36 | k | 53 | 1 |
|
||||
| 3 | D | 20 | U | 37 | l | 54 | 2 |
|
||||
| 4 | E | 21 | V | 38 | m | 55 | 3 |
|
||||
| 5 | F | 22 | W | 39 | n | 56 | 4 |
|
||||
| 6 | G | 23 | X | 40 | o | 57 | 5 |
|
||||
| 7 | H | 24 | Y | 41 | p | 58 | 6 |
|
||||
| 8 | I | 25 | Z | 42 | q | 59 | 7 |
|
||||
| 9 | J | 26 | a | 43 | r | 60 | 8 |
|
||||
| 10 | K | 27 | b | 44 | s | 61 | 9 |
|
||||
| 11 | L | 28 | c | 45 | t | 62 | + |
|
||||
| 12 | M | 29 | d | 46 | u | 63 | / |
|
||||
| 13 | N | 30 | e | 47 | v | | |
|
||||
| 14 | O | 31 | f | 48 | w | (pad) | = |
|
||||
| 15 | P | 32 | g | 49 | x | | |
|
||||
| 16 | Q | 33 | h | 50 | y | | |
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|---------:|------:|---------:|------:|---------:|------:|---------:|
|
||||
| 0| A| 17| R| 34| i| 51| z|
|
||||
| 1| B| 18| S| 35| j| 52| 0|
|
||||
| 2| C| 19| T| 36| k| 53| 1|
|
||||
| 3| D| 20| U| 37| l| 54| 2|
|
||||
| 4| E| 21| V| 38| m| 55| 3|
|
||||
| 5| F| 22| W| 39| n| 56| 4|
|
||||
| 6| G| 23| X| 40| o| 57| 5|
|
||||
| 7| H| 24| Y| 41| p| 58| 6|
|
||||
| 8| I| 25| Z| 42| q| 59| 7|
|
||||
| 9| J| 26| a| 43| r| 60| 8|
|
||||
| 10| K| 27| b| 44| s| 61| 9|
|
||||
| 11| L| 28| c| 45| t| 62| +|
|
||||
| 12| M| 29| d| 46| u| 63| /|
|
||||
| 13| N| 30| e| 47| v| | |
|
||||
| 14| O| 31| f| 48| w| (pad)| =|
|
||||
| 15| P| 32| g| 49| x| | |
|
||||
| 16| Q| 33| h| 50| y| | |
|
||||
|
||||
## Base 64 (URL and filename safe) alphabet
|
||||
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|:---------|------:|:---------|------:|:---------|------:|:---------|
|
||||
| 0 | A | 17 | R | 34 | i | 51 | z |
|
||||
| 1 | B | 18 | S | 35 | j | 52 | 0 |
|
||||
| 2 | C | 19 | T | 36 | k | 53 | 1 |
|
||||
| 3 | D | 20 | U | 37 | l | 54 | 2 |
|
||||
| 4 | E | 21 | V | 38 | m | 55 | 3 |
|
||||
| 5 | F | 22 | W | 39 | n | 56 | 4 |
|
||||
| 6 | G | 23 | X | 40 | o | 57 | 5 |
|
||||
| 7 | H | 24 | Y | 41 | p | 58 | 6 |
|
||||
| 8 | I | 25 | Z | 42 | q | 59 | 7 |
|
||||
| 9 | J | 26 | a | 43 | r | 60 | 8 |
|
||||
| 10 | K | 27 | b | 44 | s | 61 | 9 |
|
||||
| 11 | L | 28 | c | 45 | t | 62 | - |
|
||||
| 12 | M | 29 | d | 46 | u | 63 | _ |
|
||||
| 13 | N | 30 | e | 47 | v | | |
|
||||
| 14 | O | 31 | f | 48 | w | (pad) | = |
|
||||
| 15 | P | 32 | g | 49 | x | | |
|
||||
| 16 | Q | 33 | h | 50 | y | | |
|
||||
| Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding |
|
||||
|------:|---------:|------:|---------:|------:|---------:|------:|---------:|
|
||||
| 0| A| 17| R| 34| i| 51| z|
|
||||
| 1| B| 18| S| 35| j| 52| 0|
|
||||
| 2| C| 19| T| 36| k| 53| 1|
|
||||
| 3| D| 20| U| 37| l| 54| 2|
|
||||
| 4| E| 21| V| 38| m| 55| 3|
|
||||
| 5| F| 22| W| 39| n| 56| 4|
|
||||
| 6| G| 23| X| 40| o| 57| 5|
|
||||
| 7| H| 24| Y| 41| p| 58| 6|
|
||||
| 8| I| 25| Z| 42| q| 59| 7|
|
||||
| 9| J| 26| a| 43| r| 60| 8|
|
||||
| 10| K| 27| b| 44| s| 61| 9|
|
||||
| 11| L| 28| c| 45| t| 62| -|
|
||||
| 12| M| 29| d| 46| u| 63| _|
|
||||
| 13| N| 30| e| 47| v| | |
|
||||
| 14| O| 31| f| 48| w| (pad)| =|
|
||||
| 15| P| 32| g| 49| x| | |
|
||||
| 16| Q| 33| h| 50| y| | |
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -111,9 +111,9 @@ defmodule Behaviour do
|
||||
end
|
||||
end
|
||||
|
||||
defp __behaviour__doc_value(%{"en" => doc}), do: doc
|
||||
defp __behaviour__doc_value(:none), do: nil
|
||||
defp __behaviour__doc_value(:hidden), do: false
|
||||
defp __behaviour__doc_value(_), do: nil
|
||||
defp __behaviour__doc_value(%{"en" => doc}), do: doc
|
||||
|
||||
import unquote(__MODULE__)
|
||||
end
|
||||
|
||||
+36
-125
@@ -1,11 +1,8 @@
|
||||
defmodule Bitwise do
|
||||
@moduledoc """
|
||||
A set of functions that perform calculations on bits.
|
||||
A set of macros that perform calculations on bits.
|
||||
|
||||
All bitwise functions work only on integers; otherwise an
|
||||
`ArithmeticError` is raised.
|
||||
|
||||
The functions in this module come in two flavors: named or
|
||||
The macros in this module come in two flavors: named or
|
||||
operators. For example:
|
||||
|
||||
iex> use Bitwise
|
||||
@@ -29,16 +26,16 @@ defmodule Bitwise do
|
||||
When invoked with no options, `use Bitwise` is equivalent
|
||||
to `import Bitwise`.
|
||||
|
||||
All bitwise functions can be used in guards:
|
||||
All bitwise macros can be used in guards:
|
||||
|
||||
iex> use Bitwise
|
||||
iex> odd? = fn
|
||||
...> int when Bitwise.band(int, 1) == 1 -> true
|
||||
...> int when band(int, 1) == 1 -> true
|
||||
...> _ -> false
|
||||
...> end
|
||||
iex> odd?.(1)
|
||||
true
|
||||
|
||||
All functions in this module are inlined by the compiler.
|
||||
"""
|
||||
|
||||
@doc false
|
||||
@@ -61,260 +58,174 @@ defmodule Bitwise do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the bitwise NOT of the argument.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Calculates the bitwise NOT of its argument.
|
||||
|
||||
iex> bnot(2)
|
||||
-3
|
||||
|
||||
iex> bnot(2) &&& 3
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec bnot(integer) :: integer
|
||||
def bnot(expr) do
|
||||
:erlang.bnot(expr)
|
||||
defmacro bnot(expr) do
|
||||
quote(do: :erlang.bnot(unquote(expr)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Bitwise NOT unary operator.
|
||||
|
||||
Calculates the bitwise NOT of the argument.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Prefix (unary) operator; calculates the bitwise NOT of its argument.
|
||||
|
||||
iex> ~~~2
|
||||
-3
|
||||
|
||||
iex> ~~~2 &&& 3
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec ~~~integer :: integer
|
||||
def ~~~expr do
|
||||
:erlang.bnot(expr)
|
||||
defmacro ~~~expr do
|
||||
quote(do: :erlang.bnot(unquote(expr)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the bitwise AND of its arguments.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> band(9, 3)
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec band(integer, integer) :: integer
|
||||
def band(left, right) do
|
||||
:erlang.band(left, right)
|
||||
defmacro band(left, right) do
|
||||
quote(do: :erlang.band(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Bitwise AND operator.
|
||||
|
||||
Calculates the bitwise AND of its arguments.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Infix operator; calculates the bitwise AND of its arguments.
|
||||
|
||||
iex> 9 &&& 3
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec integer &&& integer :: integer
|
||||
def left &&& right do
|
||||
:erlang.band(left, right)
|
||||
defmacro left &&& right do
|
||||
quote(do: :erlang.band(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the bitwise OR of its arguments.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> bor(9, 3)
|
||||
11
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec bor(integer, integer) :: integer
|
||||
def bor(left, right) do
|
||||
:erlang.bor(left, right)
|
||||
defmacro bor(left, right) do
|
||||
quote(do: :erlang.bor(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Bitwise OR operator.
|
||||
|
||||
Calculates the bitwise OR of its arguments.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Infix operator; calculates the bitwise OR of its arguments.
|
||||
|
||||
iex> 9 ||| 3
|
||||
11
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec integer ||| integer :: integer
|
||||
def left ||| right do
|
||||
:erlang.bor(left, right)
|
||||
defmacro left ||| right do
|
||||
quote(do: :erlang.bor(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the bitwise XOR of its arguments.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> bxor(9, 3)
|
||||
10
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec bxor(integer, integer) :: integer
|
||||
def bxor(left, right) do
|
||||
:erlang.bxor(left, right)
|
||||
defmacro bxor(left, right) do
|
||||
quote(do: :erlang.bxor(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Bitwise XOR operator.
|
||||
|
||||
Calculates the bitwise XOR of its arguments.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Infix operator; calculates the bitwise XOR of its arguments.
|
||||
|
||||
iex> 9 ^^^ 3
|
||||
10
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec integer ^^^ integer :: integer
|
||||
def left ^^^ right do
|
||||
:erlang.bxor(left, right)
|
||||
defmacro left ^^^ right do
|
||||
quote(do: :erlang.bxor(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the result of an arithmetic left bitshift.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> bsl(1, 2)
|
||||
4
|
||||
|
||||
iex> bsl(1, -2)
|
||||
0
|
||||
|
||||
iex> bsl(-1, 2)
|
||||
-4
|
||||
|
||||
iex> bsl(-1, -2)
|
||||
-1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec bsl(integer, integer) :: integer
|
||||
def bsl(left, right) do
|
||||
:erlang.bsl(left, right)
|
||||
defmacro bsl(left, right) do
|
||||
quote(do: :erlang.bsl(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Arithmetic left bitshift operator.
|
||||
|
||||
Calculates the result of an arithmetic left bitshift.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Infix operator; calculates the result of an arithmetic left bitshift.
|
||||
|
||||
iex> 1 <<< 2
|
||||
4
|
||||
|
||||
iex> 1 <<< -2
|
||||
0
|
||||
|
||||
iex> -1 <<< 2
|
||||
-4
|
||||
|
||||
iex> -1 <<< -2
|
||||
-1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec integer <<< integer :: integer
|
||||
def left <<< right do
|
||||
:erlang.bsl(left, right)
|
||||
defmacro left <<< right do
|
||||
quote(do: :erlang.bsl(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the result of an arithmetic right bitshift.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> bsr(1, 2)
|
||||
0
|
||||
|
||||
iex> bsr(1, -2)
|
||||
4
|
||||
|
||||
iex> bsr(-1, 2)
|
||||
-1
|
||||
|
||||
iex> bsr(-1, -2)
|
||||
-4
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec bsr(integer, integer) :: integer
|
||||
def bsr(left, right) do
|
||||
:erlang.bsr(left, right)
|
||||
defmacro bsr(left, right) do
|
||||
quote(do: :erlang.bsr(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Arithmetic right bitshift operator.
|
||||
|
||||
Calculates the result of an arithmetic right bitshift.
|
||||
|
||||
Allowed in guard tests. Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
Infix operator; calculates the result of an arithmetic right bitshift.
|
||||
|
||||
iex> 1 >>> 2
|
||||
0
|
||||
|
||||
iex> 1 >>> -2
|
||||
4
|
||||
|
||||
iex> -1 >>> 2
|
||||
-1
|
||||
|
||||
iex> -1 >>> -2
|
||||
-4
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
@spec integer >>> integer :: integer
|
||||
def left >>> right do
|
||||
:erlang.bsr(left, right)
|
||||
defmacro left >>> right do
|
||||
quote(do: :erlang.bsr(unquote(left), unquote(right)))
|
||||
end
|
||||
end
|
||||
|
||||
+9
-572
@@ -11,7 +11,7 @@ defmodule Calendar do
|
||||
For the actual date, time and datetime structures, see `Date`,
|
||||
`Time`, `NaiveDateTime` and `DateTime`.
|
||||
|
||||
Note designations for year, month, day, and the like, are overspecified
|
||||
Note the year, month, day, etc. designations are overspecified
|
||||
(i.e. an integer instead of `1..12` for months) because different
|
||||
calendars may have a different number of days per month, months per year and so on.
|
||||
"""
|
||||
@@ -23,11 +23,6 @@ defmodule Calendar do
|
||||
@type day_of_week :: non_neg_integer
|
||||
@type era :: non_neg_integer
|
||||
|
||||
@typedoc """
|
||||
A tuple representing the `day` and the `era`.
|
||||
"""
|
||||
@type day_of_era :: {day :: non_neg_integer(), era}
|
||||
|
||||
@type hour :: non_neg_integer
|
||||
@type minute :: non_neg_integer
|
||||
@type second :: non_neg_integer
|
||||
@@ -57,29 +52,21 @@ defmodule Calendar do
|
||||
representing the microseconds to external format. If the precision is 0,
|
||||
it means microseconds must be skipped.
|
||||
"""
|
||||
@type microsecond :: {non_neg_integer, non_neg_integer}
|
||||
@type microsecond :: {0..999_999, 0..6}
|
||||
|
||||
@typedoc "A calendar implementation"
|
||||
@type calendar :: module
|
||||
|
||||
@typedoc "The time zone ID according to the IANA tz database (for example, Europe/Zurich)"
|
||||
@typedoc "The time zone ID according to the IANA tz database (e.g. Europe/Zurich)"
|
||||
@type time_zone :: String.t()
|
||||
|
||||
@typedoc "The time zone abbreviation (for example, CET or CEST or BST, and such)"
|
||||
@typedoc "The time zone abbreviation (e.g. CET or CEST or BST etc.)"
|
||||
@type zone_abbr :: String.t()
|
||||
|
||||
@typedoc """
|
||||
The time zone UTC offset in seconds for standard time.
|
||||
|
||||
See also `t:std_offset/0`.
|
||||
"""
|
||||
@typedoc "The time zone UTC offset in seconds"
|
||||
@type utc_offset :: integer
|
||||
|
||||
@typedoc """
|
||||
The time zone standard offset in seconds (typically not zero in summer times).
|
||||
|
||||
It must be added to `t:utc_offset/0` to get the total offset from UTC used for "wall time".
|
||||
"""
|
||||
@typedoc "The time zone standard offset in seconds (not zero in summer times)"
|
||||
@type std_offset :: integer
|
||||
|
||||
@typedoc "Any map/struct that contains the date fields"
|
||||
@@ -135,7 +122,7 @@ defmodule Calendar do
|
||||
for any other time zone.
|
||||
|
||||
Other time zone databases (including ones provided by packages)
|
||||
can be configured as default either via configuration:
|
||||
can be configure as default either via configuration:
|
||||
|
||||
config :elixir, :time_zone_database, CustomTimeZoneDatabase
|
||||
|
||||
@@ -167,14 +154,8 @@ defmodule Calendar do
|
||||
|
||||
@doc """
|
||||
Calculates the day of the week from the given `year`, `month`, and `day`.
|
||||
|
||||
The `starting_on` represents the starting day of the week. All
|
||||
calendars must support at least the `:default` value. They may
|
||||
also support other values representing their days of the week.
|
||||
"""
|
||||
@callback day_of_week(year, month, day, starting_on :: :default | atom) ::
|
||||
{day_of_week(), first_day_of_week :: non_neg_integer(),
|
||||
last_day_of_week :: non_neg_integer()}
|
||||
@callback day_of_week(year, month, day) :: day_of_week()
|
||||
|
||||
@doc """
|
||||
Calculates the day of the year from the given `year`, `month`, and `day`.
|
||||
@@ -194,7 +175,7 @@ defmodule Calendar do
|
||||
@doc """
|
||||
Calculates the day and era from the given `year`, `month`, and `day`.
|
||||
"""
|
||||
@callback day_of_era(year, month, day) :: day_of_era()
|
||||
@callback day_of_era(year, month, day) :: {non_neg_integer(), era}
|
||||
|
||||
@doc """
|
||||
Converts the date into a string according to the calendar.
|
||||
@@ -284,47 +265,6 @@ defmodule Calendar do
|
||||
"""
|
||||
@callback valid_time?(hour, minute, second, microsecond) :: boolean
|
||||
|
||||
@doc """
|
||||
Parses the string representation for a time returned by `c:time_to_string/4`
|
||||
into a time-tuple.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@callback parse_time(String.t()) ::
|
||||
{:ok, {hour, minute, second, microsecond}}
|
||||
| {:error, atom}
|
||||
|
||||
@doc """
|
||||
Parses the string representation for a date returned by `c:date_to_string/3`
|
||||
into a date-tuple.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@callback parse_date(String.t()) ::
|
||||
{:ok, {year, month, day}}
|
||||
| {:error, atom}
|
||||
|
||||
@doc """
|
||||
Parses the string representation for a naive datetime returned by
|
||||
`c:naive_datetime_to_string/7` into a naive-datetime-tuple.
|
||||
|
||||
The given string may contain a timezone offset but it is ignored.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@callback parse_naive_datetime(String.t()) ::
|
||||
{:ok, {year, month, day, hour, minute, second, microsecond}}
|
||||
| {:error, atom}
|
||||
|
||||
@doc """
|
||||
Parses the string representation for a datetime returned by
|
||||
`c:datetime_to_string/11` into a datetime-tuple.
|
||||
|
||||
The returned datetime must be in UTC. The original `utc_offset`
|
||||
it was written in must be returned in the result.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@callback parse_utc_datetime(String.t()) ::
|
||||
{:ok, {year, month, day, hour, minute, second, microsecond}, utc_offset}
|
||||
| {:error, atom}
|
||||
|
||||
# General Helpers
|
||||
|
||||
@doc """
|
||||
@@ -377,507 +317,4 @@ defmodule Calendar do
|
||||
def get_time_zone_database() do
|
||||
Application.get_env(:elixir, :time_zone_database, Calendar.UTCOnlyTimeZoneDatabase)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Formats received datetime into a string.
|
||||
|
||||
The datetime can be any of the Calendar types (`Time`, `Date`,
|
||||
`NaiveDateTime`, and `DateTime`) or any map, as long as they
|
||||
contain all of the relevant fields necessary for formatting.
|
||||
For example, if you use `%Y` to format the year, the datetime
|
||||
must have the `:year` field. Therefore, if you pass a `Time`,
|
||||
or a map without the `:year` field to a format that expects `%Y`,
|
||||
an error will be raised.
|
||||
|
||||
## Options
|
||||
|
||||
* `:preferred_datetime` - a string for the preferred format to show datetimes,
|
||||
it can't contain the `%c` format and defaults to `"%Y-%m-%d %H:%M:%S"`
|
||||
if the option is not received
|
||||
|
||||
* `:preferred_date` - a string for the preferred format to show dates,
|
||||
it can't contain the `%x` format and defaults to `"%Y-%m-%d"`
|
||||
if the option is not received
|
||||
|
||||
* `:preferred_time` - a string for the preferred format to show times,
|
||||
it can't contain the `%X` format and defaults to `"%H:%M:%S"`
|
||||
if the option is not received
|
||||
|
||||
* `:am_pm_names` - a function that receives either `:am` or `:pm` and returns
|
||||
the name of the period of the day, if the option is not received it defaults
|
||||
to a function that returns `"am"` and `"pm"`, respectively
|
||||
|
||||
* `:month_names` - a function that receives a number and returns the name of
|
||||
the corresponding month, if the option is not received it defaults to a
|
||||
function that returns the month names in English
|
||||
|
||||
* `:abbreviated_month_names` - a function that receives a number and returns the
|
||||
abbreviated name of the corresponding month, if the option is not received it
|
||||
defaults to a function that returns the abbreviated month names in English
|
||||
|
||||
* `:day_of_week_names` - a function that receives a number and returns the name of
|
||||
the corresponding day of week, if the option is not received it defaults to a
|
||||
function that returns the day of week names in English
|
||||
|
||||
* `:abbreviated_day_of_week_names` - a function that receives a number and returns
|
||||
the abbreviated name of the corresponding day of week, if the option is not received
|
||||
it defaults to a function that returns the abbreviated day of week names in English
|
||||
|
||||
## Formatting syntax
|
||||
|
||||
The formatting syntax for strftime is a sequence of characters in the following format:
|
||||
|
||||
%<padding><width><format>
|
||||
|
||||
where:
|
||||
|
||||
* `%`: indicates the start of a formatted section
|
||||
* `<padding>`: set the padding (see below)
|
||||
* `<width>`: a number indicating the minimum size of the formatted section
|
||||
* `<format>`: the format itself (see below)
|
||||
|
||||
### Accepted padding options
|
||||
|
||||
* `-`: no padding, removes all padding from the format
|
||||
* `_`: pad with spaces
|
||||
* `0`: pad with zeroes
|
||||
|
||||
### Accepted formats
|
||||
|
||||
The accepted formats are:
|
||||
|
||||
Format | Description | Examples (in ISO)
|
||||
:----- | :-----------------------------------------------------------------------| :------------------------
|
||||
a | Abbreviated name of day | Mon
|
||||
A | Full name of day | Monday
|
||||
b | Abbreviated month name | Jan
|
||||
B | Full month name | January
|
||||
c | Preferred date+time representation | 2018-10-17 12:34:56
|
||||
d | Day of the month | 01, 12
|
||||
f | Microseconds *(does not support width and padding modifiers)* | 000000, 999999, 0123
|
||||
H | Hour using a 24-hour clock | 00, 23
|
||||
I | Hour using a 12-hour clock | 01, 12
|
||||
j | Day of the year | 001, 366
|
||||
m | Month | 01, 12
|
||||
M | Minute | 00, 59
|
||||
p | "AM" or "PM" (noon is "PM", midnight as "AM") | AM, PM
|
||||
P | "am" or "pm" (noon is "pm", midnight as "am") | am, pm
|
||||
q | Quarter | 1, 2, 3, 4
|
||||
S | Second | 00, 59, 60
|
||||
u | Day of the week | 1 (Monday), 7 (Sunday)
|
||||
x | Preferred date (without time) representation | 2018-10-17
|
||||
X | Preferred time (without date) representation | 12:34:56
|
||||
y | Year as 2-digits | 01, 01, 86, 18
|
||||
Y | Year | -0001, 0001, 1986
|
||||
z | +hhmm/-hhmm time zone offset from UTC (empty string if naive) | +0300, -0530
|
||||
Z | Time zone abbreviation (empty string if naive) | CET, BRST
|
||||
% | Literal "%" character | %
|
||||
|
||||
Any other character will be interpreted as an invalid format and raise an error
|
||||
|
||||
## Examples
|
||||
|
||||
Without options:
|
||||
|
||||
iex> Calendar.strftime(~U[2019-08-26 13:52:06.0Z], "%y-%m-%d %I:%M:%S %p")
|
||||
"19-08-26 01:52:06 PM"
|
||||
|
||||
iex> Calendar.strftime(~U[2019-08-26 13:52:06.0Z], "%a, %B %d %Y")
|
||||
"Mon, August 26 2019"
|
||||
|
||||
iex> Calendar.strftime(~U[2019-08-26 13:52:06.0Z], "%c")
|
||||
"2019-08-26 13:52:06"
|
||||
|
||||
With options:
|
||||
|
||||
iex> Calendar.strftime(~U[2019-08-26 13:52:06.0Z], "%c", preferred_datetime: "%H:%M:%S %d-%m-%y")
|
||||
"13:52:06 26-08-19"
|
||||
|
||||
iex> Calendar.strftime(
|
||||
...> ~U[2019-08-26 13:52:06.0Z],
|
||||
...> "%A",
|
||||
...> day_of_week_names: fn day_of_week ->
|
||||
...> {"segunda-feira", "terça-feira", "quarta-feira", "quinta-feira",
|
||||
...> "sexta-feira", "sábado", "domingo"}
|
||||
...> |> elem(day_of_week - 1)
|
||||
...> end
|
||||
...>)
|
||||
"segunda-feira"
|
||||
|
||||
iex> Calendar.strftime(
|
||||
...> ~U[2019-08-26 13:52:06.0Z],
|
||||
...> "%B",
|
||||
...> month_names: fn month ->
|
||||
...> {"январь", "февраль", "март", "апрель", "май", "июнь",
|
||||
...> "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"}
|
||||
...> |> elem(month - 1)
|
||||
...> end
|
||||
...>)
|
||||
"август"
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec strftime(map(), String.t(), keyword()) :: String.t()
|
||||
def strftime(date_or_time_or_datetime, string_format, user_options \\ [])
|
||||
when is_map(date_or_time_or_datetime) and is_binary(string_format) do
|
||||
parse(
|
||||
string_format,
|
||||
date_or_time_or_datetime,
|
||||
options(user_options),
|
||||
[]
|
||||
)
|
||||
|> IO.iodata_to_binary()
|
||||
end
|
||||
|
||||
defp parse("", _datetime, _format_options, acc),
|
||||
do: Enum.reverse(acc)
|
||||
|
||||
defp parse("%" <> rest, datetime, format_options, acc),
|
||||
do: parse_modifiers(rest, nil, nil, {datetime, format_options, acc})
|
||||
|
||||
defp parse(<<char, rest::binary>>, datetime, format_options, acc),
|
||||
do: parse(rest, datetime, format_options, [char | acc])
|
||||
|
||||
defp parse_modifiers("-" <> rest, width, nil, parser_data) do
|
||||
parse_modifiers(rest, width, "", parser_data)
|
||||
end
|
||||
|
||||
defp parse_modifiers("0" <> rest, width, nil, parser_data) do
|
||||
parse_modifiers(rest, width, ?0, parser_data)
|
||||
end
|
||||
|
||||
defp parse_modifiers("_" <> rest, width, nil, parser_data) do
|
||||
parse_modifiers(rest, width, ?\s, parser_data)
|
||||
end
|
||||
|
||||
defp parse_modifiers(<<digit, rest::binary>>, width, pad, parser_data) when digit in ?0..?9 do
|
||||
new_width = (width || 0) * 10 + (digit - ?0)
|
||||
|
||||
parse_modifiers(rest, new_width, pad, parser_data)
|
||||
end
|
||||
|
||||
# set default padding if none was specified
|
||||
defp parse_modifiers(<<format, _::binary>> = rest, width, nil, parser_data) do
|
||||
parse_modifiers(rest, width, default_pad(format), parser_data)
|
||||
end
|
||||
|
||||
# set default width if none was specified
|
||||
defp parse_modifiers(<<format, _::binary>> = rest, nil, pad, parser_data) do
|
||||
parse_modifiers(rest, default_width(format), pad, parser_data)
|
||||
end
|
||||
|
||||
defp parse_modifiers(rest, width, pad, {datetime, format_options, acc}) do
|
||||
format_modifiers(rest, width, pad, datetime, format_options, acc)
|
||||
end
|
||||
|
||||
defp am_pm(hour, format_options) when hour > 11 do
|
||||
format_options.am_pm_names.(:pm)
|
||||
end
|
||||
|
||||
defp am_pm(hour, format_options) when hour <= 11 do
|
||||
format_options.am_pm_names.(:am)
|
||||
end
|
||||
|
||||
defp default_pad(format) when format in 'aAbBpPZ', do: ?\s
|
||||
defp default_pad(_format), do: ?0
|
||||
|
||||
defp default_width(format) when format in 'dHImMSy', do: 2
|
||||
defp default_width(?j), do: 3
|
||||
defp default_width(format) when format in 'Yz', do: 4
|
||||
defp default_width(_format), do: 0
|
||||
|
||||
# Literally just %
|
||||
defp format_modifiers("%" <> rest, width, pad, datetime, format_options, acc) do
|
||||
parse(rest, datetime, format_options, [pad_leading("%", width, pad) | acc])
|
||||
end
|
||||
|
||||
# Abbreviated name of day
|
||||
defp format_modifiers("a" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
datetime
|
||||
|> Date.day_of_week()
|
||||
|> format_options.abbreviated_day_of_week_names.()
|
||||
|> pad_leading(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Full name of day
|
||||
defp format_modifiers("A" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
datetime
|
||||
|> Date.day_of_week()
|
||||
|> format_options.day_of_week_names.()
|
||||
|> pad_leading(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Abbreviated month name
|
||||
defp format_modifiers("b" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
datetime.month
|
||||
|> format_options.abbreviated_month_names.()
|
||||
|> pad_leading(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Full month name
|
||||
defp format_modifiers("B" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.month |> format_options.month_names.() |> pad_leading(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Preferred date+time representation
|
||||
defp format_modifiers(
|
||||
"c" <> _rest,
|
||||
_width,
|
||||
_pad,
|
||||
_datetime,
|
||||
%{preferred_datetime_invoked: true},
|
||||
_acc
|
||||
) do
|
||||
raise ArgumentError,
|
||||
"tried to format preferred_datetime within another preferred_datetime format"
|
||||
end
|
||||
|
||||
defp format_modifiers("c" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
format_options.preferred_datetime
|
||||
|> parse(datetime, %{format_options | preferred_datetime_invoked: true}, [])
|
||||
|> pad_preferred(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Day of the month
|
||||
defp format_modifiers("d" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.day |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Microseconds
|
||||
defp format_modifiers("f" <> rest, _width, _pad, datetime, format_options, acc) do
|
||||
{microsecond, precision} = datetime.microsecond
|
||||
|
||||
result =
|
||||
microsecond
|
||||
|> Integer.to_string()
|
||||
|> String.pad_leading(6, "0")
|
||||
|> binary_part(0, max(precision, 1))
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Hour using a 24-hour clock
|
||||
defp format_modifiers("H" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.hour |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Hour using a 12-hour clock
|
||||
defp format_modifiers("I" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = (rem(datetime.hour() + 23, 12) + 1) |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Day of the year
|
||||
defp format_modifiers("j" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime |> Date.day_of_year() |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Month
|
||||
defp format_modifiers("m" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.month |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Minute
|
||||
defp format_modifiers("M" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.minute |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# "AM" or "PM" (noon is "PM", midnight as "AM")
|
||||
defp format_modifiers("p" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.hour |> am_pm(format_options) |> String.upcase() |> pad_leading(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# "am" or "pm" (noon is "pm", midnight as "am")
|
||||
defp format_modifiers("P" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
datetime.hour
|
||||
|> am_pm(format_options)
|
||||
|> String.downcase()
|
||||
|> pad_leading(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Quarter
|
||||
defp format_modifiers("q" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime |> Date.quarter_of_year() |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Second
|
||||
defp format_modifiers("S" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.second |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Day of the week
|
||||
defp format_modifiers("u" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime |> Date.day_of_week() |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Preferred date (without time) representation
|
||||
defp format_modifiers(
|
||||
"x" <> _rest,
|
||||
_width,
|
||||
_pad,
|
||||
_datetime,
|
||||
%{preferred_date_invoked: true},
|
||||
_acc
|
||||
) do
|
||||
raise ArgumentError,
|
||||
"tried to format preferred_date within another preferred_date format"
|
||||
end
|
||||
|
||||
defp format_modifiers("x" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
format_options.preferred_date
|
||||
|> parse(datetime, %{format_options | preferred_date_invoked: true}, [])
|
||||
|> pad_preferred(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Preferred time (without date) representation
|
||||
defp format_modifiers(
|
||||
"X" <> _rest,
|
||||
_width,
|
||||
_pad,
|
||||
_datetime,
|
||||
%{preferred_time_invoked: true},
|
||||
_acc
|
||||
) do
|
||||
raise ArgumentError,
|
||||
"tried to format preferred_time within another preferred_time format"
|
||||
end
|
||||
|
||||
defp format_modifiers("X" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result =
|
||||
format_options.preferred_time
|
||||
|> parse(datetime, %{format_options | preferred_time_invoked: true}, [])
|
||||
|> pad_preferred(width, pad)
|
||||
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Year as 2-digits
|
||||
defp format_modifiers("y" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.year |> rem(100) |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# Year
|
||||
defp format_modifiers("Y" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime.year |> Integer.to_string() |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
# +hhmm/-hhmm time zone offset from UTC (empty string if naive)
|
||||
defp format_modifiers(
|
||||
"z" <> rest,
|
||||
width,
|
||||
pad,
|
||||
datetime = %{utc_offset: utc_offset, std_offset: std_offset},
|
||||
format_options,
|
||||
acc
|
||||
) do
|
||||
absolute_offset = abs(utc_offset + std_offset)
|
||||
|
||||
offset_number =
|
||||
Integer.to_string(div(absolute_offset, 3600) * 100 + rem(div(absolute_offset, 60), 60))
|
||||
|
||||
sign = if utc_offset + std_offset >= 0, do: "+", else: "-"
|
||||
result = "#{sign}#{pad_leading(offset_number, width, pad)}"
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
defp format_modifiers("z" <> rest, _width, _pad, datetime, format_options, acc) do
|
||||
parse(rest, datetime, format_options, ["" | acc])
|
||||
end
|
||||
|
||||
# Time zone abbreviation (empty string if naive)
|
||||
defp format_modifiers("Z" <> rest, width, pad, datetime, format_options, acc) do
|
||||
result = datetime |> Map.get(:zone_abbr, "") |> pad_leading(width, pad)
|
||||
parse(rest, datetime, format_options, [result | acc])
|
||||
end
|
||||
|
||||
defp format_modifiers(rest, _width, _pad, _datetime, _format_options, _acc) do
|
||||
{next, _rest} = String.next_grapheme(rest) || {"", ""}
|
||||
raise ArgumentError, "invalid strftime format: %#{next}"
|
||||
end
|
||||
|
||||
defp pad_preferred(result, width, pad) when length(result) < width do
|
||||
pad_preferred([pad | result], width, pad)
|
||||
end
|
||||
|
||||
defp pad_preferred(result, _width, _pad), do: result
|
||||
|
||||
defp pad_leading(string, count, padding) do
|
||||
to_pad = count - byte_size(string)
|
||||
if to_pad > 0, do: do_pad_leading(to_pad, padding, string), else: string
|
||||
end
|
||||
|
||||
defp do_pad_leading(0, _, acc), do: acc
|
||||
|
||||
defp do_pad_leading(count, padding, acc),
|
||||
do: do_pad_leading(count - 1, padding, [padding | acc])
|
||||
|
||||
defp options(user_options) do
|
||||
default_options = %{
|
||||
preferred_date: "%Y-%m-%d",
|
||||
preferred_time: "%H:%M:%S",
|
||||
preferred_datetime: "%Y-%m-%d %H:%M:%S",
|
||||
am_pm_names: fn
|
||||
:am -> "am"
|
||||
:pm -> "pm"
|
||||
end,
|
||||
month_names: fn month ->
|
||||
{"January", "February", "March", "April", "May", "June", "July", "August", "September",
|
||||
"October", "November", "December"}
|
||||
|> elem(month - 1)
|
||||
end,
|
||||
day_of_week_names: fn day_of_week ->
|
||||
{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
|
||||
|> elem(day_of_week - 1)
|
||||
end,
|
||||
abbreviated_month_names: fn month ->
|
||||
{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
|
||||
|> elem(month - 1)
|
||||
end,
|
||||
abbreviated_day_of_week_names: fn day_of_week ->
|
||||
{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"} |> elem(day_of_week - 1)
|
||||
end,
|
||||
preferred_datetime_invoked: false,
|
||||
preferred_date_invoked: false,
|
||||
preferred_time_invoked: false
|
||||
}
|
||||
|
||||
Enum.reduce(user_options, default_options, fn {key, value}, acc ->
|
||||
if Map.has_key?(acc, key) do
|
||||
%{acc | key => value}
|
||||
else
|
||||
raise ArgumentError, "unknown option #{inspect(key)} given to Calendar.strftime/3"
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
+38
-244
@@ -88,20 +88,20 @@ defmodule Date do
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec range(Calendar.date(), Calendar.date()) :: Date.Range.t()
|
||||
def range(%{calendar: calendar} = first, %{calendar: calendar} = last) do
|
||||
@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: %Date{calendar: calendar, year: first.year, month: first.month, day: first.day},
|
||||
last: %Date{calendar: calendar, year: last.year, month: last.month, day: last.day},
|
||||
first: first,
|
||||
last: last,
|
||||
first_in_iso_days: first_days,
|
||||
last_in_iso_days: last_days
|
||||
}
|
||||
end
|
||||
|
||||
def range(%{calendar: _, year: _, month: _, day: _}, %{calendar: _, year: _, month: _, day: _}) do
|
||||
def range(%Date{}, %Date{}) do
|
||||
raise ArgumentError, "both dates must have matching calendars"
|
||||
end
|
||||
|
||||
@@ -224,33 +224,6 @@ defmodule Date do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new ISO date.
|
||||
|
||||
Expects all values to be integers. Returns `date` if each
|
||||
entry fits its appropriate range, raises if the date is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.new!(2000, 1, 1)
|
||||
~D[2000-01-01]
|
||||
iex> Date.new!(2000, 13, 1)
|
||||
** (ArgumentError) cannot build date, reason: :invalid_date
|
||||
iex> Date.new!(2000, 2, 29)
|
||||
~D[2000-02-29]
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec new!(Calendar.year(), Calendar.month(), Calendar.day(), Calendar.calendar()) :: t
|
||||
def new!(year, month, day, calendar \\ Calendar.ISO) do
|
||||
case new(year, month, day, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError, "cannot build date, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given date to a string according to its calendar.
|
||||
|
||||
@@ -290,9 +263,30 @@ defmodule Date do
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) do
|
||||
with {:ok, {year, month, day}} <- Calendar.ISO.parse_date(string) do
|
||||
convert(%Date{year: year, month: month, day: day}, calendar)
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<?-, rest::binary>>, calendar) do
|
||||
with {:ok, %{year: year} = date} <- raw_from_iso8601(rest, calendar) do
|
||||
{:ok, %{date | year: -year}}
|
||||
end
|
||||
end
|
||||
|
||||
def from_iso8601(<<rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar)
|
||||
end
|
||||
|
||||
[match_date, guard_date, read_date] = Calendar.ISO.__match_date__()
|
||||
|
||||
defp raw_from_iso8601(string, calendar) do
|
||||
with unquote(match_date) <- string,
|
||||
true <- unquote(guard_date) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
|
||||
with {:ok, date} <- new(year, month, day, Calendar.ISO) do
|
||||
convert(date, calendar)
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -425,45 +419,6 @@ defmodule Date do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a number of gregorian days to a `Date` struct.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.from_gregorian_days(1)
|
||||
~D[0000-01-02]
|
||||
iex> Date.from_gregorian_days(730_485)
|
||||
~D[2000-01-01]
|
||||
iex> Date.from_gregorian_days(-1)
|
||||
~D[-0001-12-31]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec from_gregorian_days(integer(), Calendar.calendar()) :: t
|
||||
def from_gregorian_days(days, calendar \\ Calendar.ISO) when is_integer(days) do
|
||||
from_iso_days({days, 0}, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `date` struct to a number of gregorian days.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.to_gregorian_days(~D[0000-01-02])
|
||||
1
|
||||
iex> Date.to_gregorian_days(~D[2000-01-01])
|
||||
730_485
|
||||
iex> Date.to_gregorian_days(~N[2000-01-01 00:00:00])
|
||||
730_485
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec to_gregorian_days(Calendar.date()) :: integer()
|
||||
def to_gregorian_days(date) do
|
||||
{days, _} = to_iso_days(date)
|
||||
days
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two date structs.
|
||||
|
||||
@@ -684,11 +639,6 @@ defmodule Date do
|
||||
calendar (the default), it is an integer from 1 to 7, where
|
||||
1 is Monday and 7 is Sunday.
|
||||
|
||||
An optional `starting_on` value may be supplied, which
|
||||
configures the weekday the week starts on. The default value
|
||||
for it is `:default`, which translates to `:monday` for the
|
||||
built-in ISO calendar. Any other weekday may be given to.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.day_of_week(~D[2016-10-31])
|
||||
@@ -700,131 +650,13 @@ defmodule Date do
|
||||
iex> Date.day_of_week(~D[-0015-10-30])
|
||||
3
|
||||
|
||||
iex> Date.day_of_week(~D[2016-10-31], :sunday)
|
||||
2
|
||||
iex> Date.day_of_week(~D[2016-11-01], :sunday)
|
||||
3
|
||||
iex> Date.day_of_week(~N[2016-11-01 01:23:45], :sunday)
|
||||
3
|
||||
iex> Date.day_of_week(~D[-0015-10-30], :sunday)
|
||||
4
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec day_of_week(Calendar.date(), starting_on :: :default | atom) :: Calendar.day_of_week()
|
||||
def day_of_week(date, starting_on \\ :default)
|
||||
@spec day_of_week(Calendar.date()) :: Calendar.day()
|
||||
def day_of_week(date)
|
||||
|
||||
def day_of_week(%{calendar: calendar, year: year, month: month, day: day}, starting_on) do
|
||||
{day_of_week, _first, _last} = calendar.day_of_week(year, month, day, starting_on)
|
||||
day_of_week
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates a date that is the first day of the week for the given `date`.
|
||||
|
||||
If the day is already the first day of the week, it returns the
|
||||
day itself. For the built-in ISO calendar, the week starts on Monday.
|
||||
A weekday rather than `:default` can be given as `starting_on`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.beginning_of_week(~D[2020-07-11])
|
||||
~D[2020-07-06]
|
||||
iex> Date.beginning_of_week(~D[2020-07-06])
|
||||
~D[2020-07-06]
|
||||
iex> Date.beginning_of_week(~D[2020-07-11], :sunday)
|
||||
~D[2020-07-05]
|
||||
iex> Date.beginning_of_week(~D[2020-07-11], :saturday)
|
||||
~D[2020-07-11]
|
||||
iex> Date.beginning_of_week(~N[2020-07-11 01:23:45])
|
||||
~D[2020-07-06]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec beginning_of_week(Calendar.date(), starting_on :: :default | atom) :: Date.t()
|
||||
def beginning_of_week(date, starting_on \\ :default)
|
||||
|
||||
def beginning_of_week(%{calendar: Calendar.ISO} = date, starting_on) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
iso_days = Calendar.ISO.date_to_iso_days(year, month, day)
|
||||
|
||||
{year, month, day} =
|
||||
case Calendar.ISO.iso_days_to_day_of_week(iso_days, starting_on) do
|
||||
1 ->
|
||||
{year, month, day}
|
||||
|
||||
day_of_week ->
|
||||
Calendar.ISO.date_from_iso_days(iso_days - day_of_week + 1)
|
||||
end
|
||||
|
||||
%Date{calendar: Calendar.ISO, year: year, month: month, day: day}
|
||||
end
|
||||
|
||||
def beginning_of_week(%{calendar: calendar} = date, starting_on) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
|
||||
case calendar.day_of_week(year, month, day, starting_on) do
|
||||
{day_of_week, day_of_week, _} ->
|
||||
%Date{calendar: calendar, year: year, month: month, day: day}
|
||||
|
||||
{day_of_week, first_day_of_week, _} ->
|
||||
add(date, -(day_of_week - first_day_of_week))
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates a date that is the last day of the week for the given `date`.
|
||||
|
||||
If the day is already the last day of the week, it returns the
|
||||
day itself. For the built-in ISO calendar, the week ends on Sunday.
|
||||
A weekday rather than `:default` can be given as `starting_on`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.end_of_week(~D[2020-07-11])
|
||||
~D[2020-07-12]
|
||||
iex> Date.end_of_week(~D[2020-07-05])
|
||||
~D[2020-07-05]
|
||||
iex> Date.end_of_week(~D[2020-07-06], :sunday)
|
||||
~D[2020-07-11]
|
||||
iex> Date.end_of_week(~D[2020-07-06], :sunday)
|
||||
~D[2020-07-11]
|
||||
iex> Date.end_of_week(~D[2020-07-06], :saturday)
|
||||
~D[2020-07-10]
|
||||
iex> Date.end_of_week(~N[2020-07-11 01:23:45])
|
||||
~D[2020-07-12]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec end_of_week(Calendar.date(), starting_on :: :default | atom) :: Date.t()
|
||||
def end_of_week(date, starting_on \\ :default)
|
||||
|
||||
def end_of_week(%{calendar: Calendar.ISO} = date, starting_on) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
iso_days = Calendar.ISO.date_to_iso_days(year, month, day)
|
||||
|
||||
{year, month, day} =
|
||||
case Calendar.ISO.iso_days_to_day_of_week(iso_days, starting_on) do
|
||||
7 ->
|
||||
{year, month, day}
|
||||
|
||||
day_of_week ->
|
||||
Calendar.ISO.date_from_iso_days(iso_days + 7 - day_of_week)
|
||||
end
|
||||
|
||||
%Date{calendar: Calendar.ISO, year: year, month: month, day: day}
|
||||
end
|
||||
|
||||
def end_of_week(%{calendar: calendar} = date, starting_on) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
|
||||
case calendar.day_of_week(year, month, day, starting_on) do
|
||||
{day_of_week, _, day_of_week} ->
|
||||
%Date{calendar: calendar, year: year, month: month, day: day}
|
||||
|
||||
{day_of_week, _, last_day_of_week} ->
|
||||
add(date, last_day_of_week - day_of_week)
|
||||
end
|
||||
def day_of_week(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.day_of_week(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -928,45 +760,6 @@ defmodule Date do
|
||||
calendar.day_of_era(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates a date that is the first day of the month for the given `date`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.beginning_of_month(~D[2000-01-31])
|
||||
~D[2000-01-01]
|
||||
iex> Date.beginning_of_month(~D[2000-01-01])
|
||||
~D[2000-01-01]
|
||||
iex> Date.beginning_of_month(~N[2000-01-31 01:23:45])
|
||||
~D[2000-01-01]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec beginning_of_month(Calendar.date()) :: t()
|
||||
def beginning_of_month(%{year: year, month: month, calendar: calendar}) do
|
||||
%Date{year: year, month: month, day: 1, calendar: calendar}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates a date that is the last day of the month for the given `date`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.end_of_month(~D[2000-01-01])
|
||||
~D[2000-01-31]
|
||||
iex> Date.end_of_month(~D[2000-01-31])
|
||||
~D[2000-01-31]
|
||||
iex> Date.end_of_month(~N[2000-01-01 01:23:45])
|
||||
~D[2000-01-31]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec end_of_month(Calendar.date()) :: t()
|
||||
def end_of_month(%{year: year, month: month, calendar: calendar} = date) do
|
||||
day = Date.days_in_month(date)
|
||||
%Date{year: year, month: month, day: day, calendar: calendar}
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
defimpl String.Chars do
|
||||
@@ -976,11 +769,12 @@ defmodule Date do
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(%{calendar: calendar, year: year, month: month, day: day}, _) do
|
||||
"~D[" <> calendar.date_to_string(year, month, day) <> suffix(calendar) <> "]"
|
||||
def inspect(%{calendar: Calendar.ISO, year: year, month: month, day: day}, _) do
|
||||
"~D[" <> Calendar.ISO.date_to_string(year, month, day) <> "]"
|
||||
end
|
||||
|
||||
defp suffix(Calendar.ISO), do: ""
|
||||
defp suffix(calendar), do: " " <> inspect(calendar)
|
||||
def inspect(date, opts) do
|
||||
Inspect.Any.inspect(date, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+117
-378
@@ -25,22 +25,12 @@ defmodule DateTime do
|
||||
datetimes and returns `{:error, :utc_only_time_zone_database}`
|
||||
for any other time zone.
|
||||
|
||||
Other time zone databases can also be configured. For example,
|
||||
two of the available options are:
|
||||
Other time zone databases (including ones provided by packages)
|
||||
can be configure as default either via configuration:
|
||||
|
||||
* [`tz`](https://hexdocs.pm/tz/)
|
||||
* [`tzdata`](https://hexdocs.pm/tzdata/)
|
||||
config :elixir, :time_zone_database, CustomTimeZoneDatabase
|
||||
|
||||
To use them, first make sure it is added as a dependency in `mix.exs`.
|
||||
It can then be configured either via configuration:
|
||||
|
||||
config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
|
||||
|
||||
or by calling `Calendar.put_time_zone_database/1`:
|
||||
|
||||
Calendar.put_time_zone_database(Tzdata.TimeZoneDatabase)
|
||||
|
||||
See the proper names in the library installation instructions.
|
||||
or by calling `Calendar.put_time_zone_database/1`.
|
||||
"""
|
||||
|
||||
@enforce_keys [:year, :month, :day, :hour, :minute, :second] ++
|
||||
@@ -77,7 +67,6 @@ defmodule DateTime do
|
||||
}
|
||||
|
||||
@unix_days :calendar.date_to_gregorian_days({1970, 1, 1})
|
||||
@seconds_per_day 24 * 60 * 60
|
||||
|
||||
@doc """
|
||||
Returns the current datetime in UTC.
|
||||
@@ -94,165 +83,12 @@ defmodule DateTime do
|
||||
System.os_time() |> from_unix!(:native, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a datetime from date and time structs.
|
||||
|
||||
It expects a time zone to put the `DateTime` in.
|
||||
If the time zone is not passed it will default to `"Etc/UTC"`,
|
||||
which always succeeds. Otherwise, the `DateTime` is checked against the time zone database
|
||||
given as `time_zone_database`. See the "Time zone database"
|
||||
section in the module documentation.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> DateTime.new(~D[2016-05-24], ~T[13:26:08.003], "Etc/UTC")
|
||||
{:ok, ~U[2016-05-24 13:26:08.003Z]}
|
||||
|
||||
When the datetime is ambiguous - for instance during changing from summer
|
||||
to winter time - the two possible valid datetimes are returned. First the one
|
||||
that happens first, then the one that happens after.
|
||||
|
||||
iex> {:ambiguous, first_dt, second_dt} = DateTime.new(~D[2018-10-28], ~T[02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> first_dt
|
||||
#DateTime<2018-10-28 02:30:00+02:00 CEST Europe/Copenhagen>
|
||||
iex> second_dt
|
||||
#DateTime<2018-10-28 02:30:00+01:00 CET Europe/Copenhagen>
|
||||
|
||||
When there is a gap in wall time - for instance in spring when the clocks are
|
||||
turned forward - the latest valid datetime just before the gap and the first
|
||||
valid datetime just after the gap.
|
||||
|
||||
iex> {:gap, just_before, just_after} = DateTime.new(~D[2019-03-31], ~T[02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> just_before
|
||||
#DateTime<2019-03-31 01:59:59.999999+01:00 CET Europe/Copenhagen>
|
||||
iex> just_after
|
||||
#DateTime<2019-03-31 03:00:00+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
Most of the time there is one, and just one, valid datetime for a certain
|
||||
date and time in a certain time zone.
|
||||
|
||||
iex> {:ok, datetime} = DateTime.new(~D[2018-07-28], ~T[12:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> datetime
|
||||
#DateTime<2018-07-28 12:30:00+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec new(Date.t(), Time.t(), Calendar.time_zone(), Calendar.time_zone_database()) ::
|
||||
{:ok, t}
|
||||
| {:ambiguous, t, t}
|
||||
| {:gap, t, t}
|
||||
| {:error,
|
||||
:incompatible_calendars | :time_zone_not_found | :utc_only_time_zone_database}
|
||||
def new(
|
||||
date,
|
||||
time,
|
||||
time_zone \\ "Etc/UTC",
|
||||
time_zone_database \\ Calendar.get_time_zone_database()
|
||||
)
|
||||
|
||||
def new(%Date{calendar: calendar} = date, %Time{calendar: calendar} = time, "Etc/UTC", _db) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
%{hour: hour, minute: minute, second: second, microsecond: microsecond} = time
|
||||
|
||||
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
|
||||
|
||||
def new(date, time, time_zone, time_zone_database) do
|
||||
with {:ok, naive_datetime} <- NaiveDateTime.new(date, time) do
|
||||
from_naive(naive_datetime, time_zone, time_zone_database)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a datetime from date and time structs, raising on errors.
|
||||
|
||||
It expects a time zone to put the `DateTime` in.
|
||||
If the time zone is not passed it will default to `"Etc/UTC"`,
|
||||
which always succeeds. Otherwise, the DateTime is checked against the time zone database
|
||||
given as `time_zone_database`. See the "Time zone database"
|
||||
section in the module documentation.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> DateTime.new!(~D[2016-05-24], ~T[13:26:08.003], "Etc/UTC")
|
||||
~U[2016-05-24 13:26:08.003Z]
|
||||
|
||||
When the datetime is ambiguous - for instance during changing from summer
|
||||
to winter time - an error will be raised.
|
||||
|
||||
iex> DateTime.new!(~D[2018-10-28], ~T[02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
** (ArgumentError) cannot build datetime with ~D[2018-10-28] and ~T[02:30:00] because such instant is ambiguous in time zone Europe/Copenhagen as there is an overlap between #DateTime<2018-10-28 02:30:00+02:00 CEST Europe/Copenhagen> and #DateTime<2018-10-28 02:30:00+01:00 CET Europe/Copenhagen>
|
||||
|
||||
When there is a gap in wall time - for instance in spring when the clocks are
|
||||
turned forward - an error will be raised.
|
||||
|
||||
iex> DateTime.new!(~D[2019-03-31], ~T[02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
** (ArgumentError) cannot build datetime with ~D[2019-03-31] and ~T[02:30:00] because such instant does not exist in time zone Europe/Copenhagen as there is a gap between #DateTime<2019-03-31 01:59:59.999999+01:00 CET Europe/Copenhagen> and #DateTime<2019-03-31 03:00:00+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
Most of the time there is one, and just one, valid datetime for a certain
|
||||
date and time in a certain time zone.
|
||||
|
||||
iex> datetime = DateTime.new!(~D[2018-07-28], ~T[12:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> datetime
|
||||
#DateTime<2018-07-28 12:30:00+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec new!(Date.t(), Time.t(), Calendar.time_zone(), Calendar.time_zone_database()) :: t
|
||||
def new!(
|
||||
date,
|
||||
time,
|
||||
time_zone \\ "Etc/UTC",
|
||||
time_zone_database \\ Calendar.get_time_zone_database()
|
||||
)
|
||||
|
||||
def new!(date, time, time_zone, time_zone_database) do
|
||||
case new(date, time, time_zone, time_zone_database) do
|
||||
{:ok, datetime} ->
|
||||
datetime
|
||||
|
||||
{:ambiguous, dt1, dt2} ->
|
||||
raise ArgumentError,
|
||||
"cannot build datetime with #{inspect(date)} and #{inspect(time)} because such " <>
|
||||
"instant is ambiguous in time zone #{time_zone} as there is an overlap " <>
|
||||
"between #{inspect(dt1)} and #{inspect(dt2)}"
|
||||
|
||||
{:gap, dt1, dt2} ->
|
||||
raise ArgumentError,
|
||||
"cannot build datetime with #{inspect(date)} and #{inspect(time)} because such " <>
|
||||
"instant does not exist in time zone #{time_zone} as there is a gap " <>
|
||||
"between #{inspect(dt1)} and #{inspect(dt2)}"
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot build datetime with #{inspect(date)} and #{inspect(time)}, reason: #{
|
||||
inspect(reason)
|
||||
}"
|
||||
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. Up to
|
||||
253402300799 seconds is supported.
|
||||
be converted to microseconds internally.
|
||||
|
||||
Unix times are always in UTC and therefore the DateTime
|
||||
will be returned in UTC.
|
||||
@@ -267,26 +103,14 @@ defmodule DateTime do
|
||||
iex> datetime
|
||||
~U[2015-05-25 13:26:08.868569Z]
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_unix(253_402_300_799)
|
||||
iex> datetime
|
||||
~U[9999-12-31 23:59:59Z]
|
||||
|
||||
iex> {:error, :invalid_unix_time} = DateTime.from_unix(253_402_300_800)
|
||||
|
||||
The unit can also be an integer as in `t:System.time_unit/0`:
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_unix(143_256_036_886_856, 1024)
|
||||
iex> datetime
|
||||
~U[6403-03-17 07:05:22.320312Z]
|
||||
|
||||
Negative Unix times are supported up to -377705116800 seconds:
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_unix(-377_705_116_800)
|
||||
iex> datetime
|
||||
~U[-9999-01-01 00:00:00Z]
|
||||
|
||||
iex> {:error, :invalid_unix_time} = DateTime.from_unix(-377_705_116_801)
|
||||
|
||||
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}
|
||||
@@ -588,13 +412,11 @@ defmodule DateTime do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pacific_datetime} = DateTime.shift_zone(~U[2018-07-16 10:00:00Z], "America/Los_Angeles", FakeTimeZoneDatabase)
|
||||
iex> cph_datetime = DateTime.from_naive!(~N[2018-07-16 12:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> {:ok, pacific_datetime} = DateTime.shift_zone(cph_datetime, "America/Los_Angeles", FakeTimeZoneDatabase)
|
||||
iex> pacific_datetime
|
||||
#DateTime<2018-07-16 03:00:00-07:00 PDT America/Los_Angeles>
|
||||
|
||||
iex> DateTime.shift_zone(~U[2018-07-16 10:00:00Z], "bad timezone", FakeTimeZoneDatabase)
|
||||
{:error, :time_zone_not_found}
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec shift_zone(t, Calendar.time_zone(), Calendar.time_zone_database()) ::
|
||||
@@ -649,34 +471,6 @@ defmodule DateTime do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Changes the time zone of a `DateTime` or raises on errors.
|
||||
|
||||
See `shift_zone/3` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> DateTime.shift_zone!(~U[2018-07-16 10:00:00Z], "America/Los_Angeles", FakeTimeZoneDatabase)
|
||||
#DateTime<2018-07-16 03:00:00-07:00 PDT America/Los_Angeles>
|
||||
|
||||
iex> DateTime.shift_zone!(~U[2018-07-16 10:00:00Z], "bad timezone", FakeTimeZoneDatabase)
|
||||
** (ArgumentError) cannot shift ~U[2018-07-16 10:00:00Z] to "bad timezone" time zone, reason: :time_zone_not_found
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec shift_zone!(t, Calendar.time_zone(), Calendar.time_zone_database()) :: t
|
||||
def shift_zone!(datetime, time_zone, time_zone_database \\ Calendar.get_time_zone_database()) do
|
||||
case shift_zone(datetime, time_zone, time_zone_database) do
|
||||
{:ok, datetime} ->
|
||||
datetime
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot shift #{inspect(datetime)} to #{inspect(time_zone)} time zone" <>
|
||||
", reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the current datetime in the provided time zone.
|
||||
|
||||
@@ -691,11 +485,9 @@ defmodule DateTime do
|
||||
iex> {:ok, datetime} = DateTime.now("Etc/UTC")
|
||||
iex> datetime.time_zone
|
||||
"Etc/UTC"
|
||||
|
||||
iex> DateTime.now("Europe/Copenhagen")
|
||||
{:error, :utc_only_time_zone_database}
|
||||
|
||||
iex> DateTime.now("bad timezone", FakeTimeZoneDatabase)
|
||||
iex> DateTime.now("not a real time zone name", FakeTimeZoneDatabase)
|
||||
{:error, :time_zone_not_found}
|
||||
|
||||
"""
|
||||
@@ -712,38 +504,6 @@ defmodule DateTime do
|
||||
shift_zone(utc_now(), time_zone, time_zone_database)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the current datetime in the provided time zone or raises on errors
|
||||
|
||||
See `now/2` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> datetime = DateTime.now!("Etc/UTC")
|
||||
iex> datetime.time_zone
|
||||
"Etc/UTC"
|
||||
|
||||
iex> DateTime.now!("Europe/Copenhagen")
|
||||
** (ArgumentError) cannot get current datetime in "Europe/Copenhagen" time zone, reason: :utc_only_time_zone_database
|
||||
|
||||
iex> DateTime.now!("bad timezone", FakeTimeZoneDatabase)
|
||||
** (ArgumentError) cannot get current datetime in "bad timezone" time zone, reason: :time_zone_not_found
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec now!(Calendar.time_zone(), Calendar.time_zone_database()) :: t
|
||||
def now!(time_zone, time_zone_database \\ Calendar.get_time_zone_database()) do
|
||||
case now(time_zone, time_zone_database) do
|
||||
{:ok, datetime} ->
|
||||
datetime
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot get current datetime in #{inspect(time_zone)} time zone, reason: " <>
|
||||
inspect(reason)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `datetime` to Unix time.
|
||||
|
||||
@@ -753,10 +513,6 @@ defmodule DateTime do
|
||||
It will return the integer with the given unit,
|
||||
according to `System.convert_time_unit/3`.
|
||||
|
||||
If you want to get the current time in Unix seconds,
|
||||
do not do `DateTime.utc_now() |> DateTime.to_unix()`.
|
||||
Simply call `System.os_time(:second)` instead.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> 1_464_096_368 |> DateTime.from_unix!() |> DateTime.to_unix()
|
||||
@@ -945,14 +701,25 @@ defmodule DateTime do
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
time_zone: time_zone,
|
||||
zone_abbr: zone_abbr,
|
||||
utc_offset: utc_offset,
|
||||
std_offset: std_offset
|
||||
} = datetime
|
||||
|
||||
Calendar.ISO.date_to_string(year, month, day, format) <>
|
||||
"T" <>
|
||||
Calendar.ISO.time_to_string(hour, minute, second, microsecond, format) <>
|
||||
Calendar.ISO.offset_to_string(utc_offset, std_offset, time_zone, format)
|
||||
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) when format in [:extended, :basic] do
|
||||
@@ -1015,116 +782,94 @@ defmodule DateTime do
|
||||
@doc since: "1.4.0"
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) ::
|
||||
{:ok, t, Calendar.utc_offset()} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) do
|
||||
with {:ok, {year, month, day, hour, minute, second, microsecond}, offset} <-
|
||||
Calendar.ISO.parse_utc_datetime(string) do
|
||||
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"
|
||||
}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
with {:ok, converted} <- convert(datetime, calendar) do
|
||||
{:ok, converted, offset}
|
||||
def from_iso8601(<<?-, rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar, true)
|
||||
end
|
||||
|
||||
def from_iso8601(<<rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar, false)
|
||||
end
|
||||
|
||||
@sep [?\s, ?T]
|
||||
[match_date, guard_date, read_date] = Calendar.ISO.__match_date__()
|
||||
[match_time, guard_time, read_time] = Calendar.ISO.__match_time__()
|
||||
|
||||
defp raw_from_iso8601(string, calendar, is_year_negative) do
|
||||
with <<unquote(match_date), sep, unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_date) and sep in @sep and unquote(guard_time),
|
||||
{microsecond, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{offset, ""} <- Calendar.ISO.parse_offset(rest) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
{hour, minute, second} = unquote(read_time)
|
||||
year = if is_year_negative, do: -year, else: year
|
||||
|
||||
cond do
|
||||
not calendar.valid_date?(year, month, day) ->
|
||||
{:error, :invalid_date}
|
||||
|
||||
not calendar.valid_time?(hour, minute, second, microsecond) ->
|
||||
{:error, :invalid_time}
|
||||
|
||||
offset == 0 ->
|
||||
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, 0}
|
||||
|
||||
is_nil(offset) ->
|
||||
{:error, :missing_offset}
|
||||
|
||||
true ->
|
||||
day_fraction = Calendar.ISO.time_to_day_fraction(hour, minute, second, {0, 0})
|
||||
|
||||
{{year, month, day}, {hour, minute, second, _}} =
|
||||
case apply_tz_offset({0, day_fraction}, offset) do
|
||||
{0, day_fraction} ->
|
||||
{{year, month, day}, Calendar.ISO.time_from_day_fraction(day_fraction)}
|
||||
|
||||
{extra_days, day_fraction} ->
|
||||
base_days = Calendar.ISO.date_to_iso_days(year, month, day)
|
||||
|
||||
{Calendar.ISO.date_from_iso_days(base_days + extra_days),
|
||||
Calendar.ISO.time_from_day_fraction(day_fraction)}
|
||||
end
|
||||
|
||||
datetime = %DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
std_offset: 0,
|
||||
utc_offset: 0,
|
||||
zone_abbr: "UTC",
|
||||
time_zone: "Etc/UTC"
|
||||
}
|
||||
|
||||
{:ok, datetime, offset}
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a number of gregorian seconds to a `DateTime` struct.
|
||||
|
||||
The returned `DateTime` will have `UTC` timezone, if you want other timezone, please use
|
||||
`DateTime.shift_zone/3`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> DateTime.from_gregorian_seconds(1)
|
||||
~U[0000-01-01 00:00:01Z]
|
||||
iex> DateTime.from_gregorian_seconds(63_755_511_991, {5000, 3})
|
||||
~U[2020-05-01 00:26:31.005Z]
|
||||
iex> DateTime.from_gregorian_seconds(-1)
|
||||
~U[-0001-12-31 23:59:59Z]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec from_gregorian_seconds(integer(), Calendar.microsecond(), Calendar.calendar()) :: t
|
||||
def from_gregorian_seconds(
|
||||
seconds,
|
||||
{microsecond, precision} \\ {0, 0},
|
||||
calendar \\ Calendar.ISO
|
||||
)
|
||||
when is_integer(seconds) do
|
||||
iso_days = Calendar.ISO.gregorian_seconds_to_iso_days(seconds, microsecond)
|
||||
|
||||
{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},
|
||||
std_offset: 0,
|
||||
utc_offset: 0,
|
||||
zone_abbr: "UTC",
|
||||
time_zone: "Etc/UTC"
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `DateTime` struct to a number of gregorian seconds and microseconds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt = %DateTime{year: 0000, month: 1, day: 1, zone_abbr: "UTC",
|
||||
...> hour: 0, minute: 0, second: 1, microsecond: {0, 0},
|
||||
...> utc_offset: 0, std_offset: 0, time_zone: "Etc/UTC"}
|
||||
iex> DateTime.to_gregorian_seconds(dt)
|
||||
{1, 0}
|
||||
|
||||
iex> dt = %DateTime{year: 2020, month: 5, day: 1, zone_abbr: "UTC",
|
||||
...> hour: 0, minute: 26, second: 31, microsecond: {5000, 0},
|
||||
...> utc_offset: 0, std_offset: 0, time_zone: "Etc/UTC"}
|
||||
iex> DateTime.to_gregorian_seconds(dt)
|
||||
{63_755_511_991, 5000}
|
||||
|
||||
iex> dt = %DateTime{year: 2020, month: 5, day: 1, zone_abbr: "CET",
|
||||
...> hour: 1, minute: 26, second: 31, microsecond: {5000, 0},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
|
||||
iex> DateTime.to_gregorian_seconds(dt)
|
||||
{63_755_511_991, 5000}
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec to_gregorian_seconds(Calendar.datetime()) :: {integer(), non_neg_integer()}
|
||||
def to_gregorian_seconds(
|
||||
%{
|
||||
std_offset: std_offset,
|
||||
utc_offset: utc_offset,
|
||||
microsecond: {microsecond, _}
|
||||
} = datetime
|
||||
) do
|
||||
{days, day_fraction} =
|
||||
datetime
|
||||
|> to_iso_days()
|
||||
|> apply_tz_offset(utc_offset + std_offset)
|
||||
|
||||
seconds_in_day = seconds_from_day_fraction(day_fraction)
|
||||
{days * @seconds_per_day + seconds_in_day, microsecond}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `datetime` to a string according to its calendar.
|
||||
|
||||
@@ -1343,7 +1088,7 @@ defmodule DateTime do
|
||||
|
||||
@doc """
|
||||
Returns the given datetime with the microsecond field truncated to the given
|
||||
precision (`:microsecond`, `:millisecond` or `:second`).
|
||||
precision (`:microsecond`, `millisecond` or `:second`).
|
||||
|
||||
The given datetime is returned unchanged if it already has lower precision than
|
||||
the given precision.
|
||||
@@ -1525,12 +1270,6 @@ defmodule DateTime do
|
||||
}
|
||||
end
|
||||
|
||||
defp seconds_from_day_fraction({parts_in_day, @seconds_per_day}),
|
||||
do: parts_in_day
|
||||
|
||||
defp seconds_from_day_fraction({parts_in_day, parts_per_day}),
|
||||
do: div(parts_in_day * @seconds_per_day, parts_per_day)
|
||||
|
||||
defimpl String.Chars do
|
||||
def to_string(datetime) do
|
||||
%{
|
||||
@@ -1565,7 +1304,7 @@ defmodule DateTime do
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(datetime, _) do
|
||||
def inspect(%{calendar: Calendar.ISO} = datetime, _) do
|
||||
%{
|
||||
year: year,
|
||||
month: month,
|
||||
@@ -1577,12 +1316,11 @@ defmodule DateTime do
|
||||
time_zone: time_zone,
|
||||
zone_abbr: zone_abbr,
|
||||
utc_offset: utc_offset,
|
||||
std_offset: std_offset,
|
||||
calendar: calendar
|
||||
std_offset: std_offset
|
||||
} = datetime
|
||||
|
||||
formatted =
|
||||
calendar.datetime_to_string(
|
||||
Calendar.ISO.datetime_to_string(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
@@ -1598,14 +1336,15 @@ defmodule DateTime do
|
||||
|
||||
case datetime do
|
||||
%{utc_offset: 0, std_offset: 0, time_zone: "Etc/UTC"} ->
|
||||
"~U[" <> formatted <> suffix(calendar) <> "]"
|
||||
"~U[" <> formatted <> "]"
|
||||
|
||||
_ ->
|
||||
"#DateTime<" <> formatted <> suffix(calendar) <> ">"
|
||||
"#DateTime<" <> formatted <> ">"
|
||||
end
|
||||
end
|
||||
|
||||
defp suffix(Calendar.ISO), do: ""
|
||||
defp suffix(calendar), do: " " <> inspect(calendar)
|
||||
def inspect(datetime, opts) do
|
||||
Inspect.Any.inspect(datetime, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+152
-496
@@ -8,12 +8,6 @@ defmodule Calendar.ISO do
|
||||
applied for all time, consequently the dates give different results
|
||||
before the year 1583 from when the Gregorian calendar was adopted.
|
||||
|
||||
Given this is the default calendar used by Elixir, it has one
|
||||
difference compared to the ISO8601 specification in that it allows
|
||||
a whitespace instead of `T` as a seperator between date and times
|
||||
both when parsing and formatting. Strict formatting can be done
|
||||
by using the `to_iso8601` found in `NaiveDateTime` and `DateTime`.
|
||||
|
||||
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.
|
||||
@@ -26,49 +20,9 @@ defmodule Calendar.ISO do
|
||||
unix_end = 315_569_519_999_999_999 - @unix_epoch * 1_000_000
|
||||
@unix_range_microseconds unix_start..unix_end
|
||||
|
||||
@typedoc """
|
||||
"Before the Current Era" or "Before the Common Era" (BCE), for those years less than `1`.
|
||||
"""
|
||||
@type bce :: 0
|
||||
|
||||
@typedoc """
|
||||
The "Current Era" or the "Common Era" (CE) which starts in year `1`.
|
||||
"""
|
||||
@type ce :: 1
|
||||
|
||||
@typedoc """
|
||||
The calendar era.
|
||||
|
||||
The ISO calendar has two eras:
|
||||
* [CE](`t:ce/0`) - which starts in year `1` and is defined as era `1`.
|
||||
* [BCE](`t:bce/0`) - for those years less than `1` and is defined as era `0`.
|
||||
"""
|
||||
@type era :: bce | ce
|
||||
@type year :: -9999..9999
|
||||
@type month :: 1..12
|
||||
@type day :: 1..31
|
||||
@type hour :: 0..23
|
||||
@type minute :: 0..59
|
||||
@type second :: 0..59
|
||||
@type weekday :: :monday | :tuesday | :wednesday | :thursday | :friday | :saturday | :sunday
|
||||
|
||||
@typedoc """
|
||||
Microseconds with stored precision.
|
||||
|
||||
The precision represents the number of digits that must be used when
|
||||
representing the microseconds to external format. If the precision is 0,
|
||||
it means microseconds must be skipped.
|
||||
"""
|
||||
@type microsecond :: {0..999_999, 0..6}
|
||||
|
||||
@typedoc """
|
||||
Integer that represents the day of the week, where 1 is Monday and 7 is Sunday.
|
||||
"""
|
||||
@type day_of_week :: 1..7
|
||||
|
||||
@type day_of_year :: 1..366
|
||||
@type quarter_of_year :: 1..4
|
||||
@type year_of_era :: {1..10000, era}
|
||||
|
||||
@seconds_per_minute 60
|
||||
@seconds_per_hour 60 * 60
|
||||
@@ -78,16 +32,18 @@ defmodule Calendar.ISO do
|
||||
@microseconds_per_second 1_000_000
|
||||
@parts_per_day @seconds_per_day * @microseconds_per_second
|
||||
|
||||
@sep [?\s, ?T]
|
||||
@days_per_nonleap_year 365
|
||||
@days_per_leap_year 366
|
||||
|
||||
@months_in_year 12
|
||||
|
||||
# The ISO epoch starts, in this implementation,
|
||||
# with ~D[0000-01-01]. Era "1" starts
|
||||
# on ~D[0001-01-01] which is 366 days later.
|
||||
@iso_epoch 366
|
||||
|
||||
[match_date, guard_date, read_date] =
|
||||
@doc false
|
||||
def __match_date__ do
|
||||
quote do
|
||||
[
|
||||
<<y1, y2, y3, y4, ?-, m1, m2, ?-, d1, d2>>,
|
||||
@@ -101,8 +57,10 @@ defmodule Calendar.ISO do
|
||||
}
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
[match_time, guard_time, read_time] =
|
||||
@doc false
|
||||
def __match_time__ do
|
||||
quote do
|
||||
[
|
||||
<<h1, h2, ?:, i1, i2, ?:, s1, s2>>,
|
||||
@@ -115,276 +73,6 @@ defmodule Calendar.ISO do
|
||||
}
|
||||
]
|
||||
end
|
||||
|
||||
defguardp is_year(year) when year in -9999..9999
|
||||
defguardp is_year_BCE(year) when year in -9999..0
|
||||
defguardp is_year_CE(year) when year in 1..9999
|
||||
defguardp is_month(month) when month in 1..12
|
||||
defguardp is_day(day) when day in 1..31
|
||||
defguardp is_hour(hour) when hour in 0..23
|
||||
defguardp is_minute(minute) when minute in 0..59
|
||||
defguardp is_second(second) when second in 0..59
|
||||
|
||||
defguardp is_microsecond(microsecond, precision)
|
||||
when microsecond in 0..999_999 and precision in 0..6
|
||||
|
||||
defguardp is_time_zone(term) when is_binary(term)
|
||||
defguardp is_zone_abbr(term) when is_binary(term)
|
||||
defguardp is_utc_offset(offset) when is_integer(offset)
|
||||
defguardp is_std_offset(offset) when is_integer(offset)
|
||||
|
||||
@doc """
|
||||
Parses a time string.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.parse_time("23:50:07")
|
||||
{:ok, {23, 50, 7, {0, 0}}}
|
||||
iex> Calendar.ISO.parse_time("23:50:07Z")
|
||||
{:ok, {23, 50, 7, {0, 0}}}
|
||||
iex> Calendar.ISO.parse_time("T23:50:07Z")
|
||||
{:ok, {23, 50, 7, {0, 0}}}
|
||||
|
||||
iex> Calendar.ISO.parse_time("23:50:07,0123456")
|
||||
{:ok, {23, 50, 7, {12345, 6}}}
|
||||
iex> Calendar.ISO.parse_time("23:50:07.0123456")
|
||||
{:ok, {23, 50, 7, {12345, 6}}}
|
||||
iex> Calendar.ISO.parse_time("23:50:07.123Z")
|
||||
{:ok, {23, 50, 7, {123000, 3}}}
|
||||
|
||||
iex> Calendar.ISO.parse_time("2015:01:23 23-50-07")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_time("23:50:07A")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_time("23:50:07.")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_time("23:50:61")
|
||||
{:error, :invalid_time}
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@impl true
|
||||
def parse_time("T" <> string) when is_binary(string),
|
||||
do: do_parse_time(string)
|
||||
|
||||
def parse_time(string) when is_binary(string),
|
||||
do: do_parse_time(string)
|
||||
|
||||
defp do_parse_time(string) do
|
||||
with <<unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_time),
|
||||
{microsecond, rest} <- parse_microsecond(rest),
|
||||
{_offset, ""} <- parse_offset(rest) do
|
||||
{hour, minute, second} = unquote(read_time)
|
||||
|
||||
if valid_time?(hour, minute, second, microsecond) do
|
||||
{:ok, {hour, minute, second, microsecond}}
|
||||
else
|
||||
{:error, :invalid_time}
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses a date string.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.parse_date("2015-01-23")
|
||||
{:ok, {2015, 1, 23}}
|
||||
iex> Calendar.ISO.parse_date("-2015-01-23")
|
||||
{:ok, {-2015, 1, 23}}
|
||||
iex> Calendar.ISO.parse_date("2015:01:23")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_date("2015-01-32")
|
||||
{:error, :invalid_date}
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@impl true
|
||||
def parse_date("-" <> string) when is_binary(string),
|
||||
do: parse_date(string, -1)
|
||||
|
||||
def parse_date(string) when is_binary(string),
|
||||
do: parse_date(string, 1)
|
||||
|
||||
defp parse_date(string, multiplier) do
|
||||
with unquote(match_date) <- string, true <- unquote(guard_date) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
year = multiplier * year
|
||||
|
||||
if valid_date?(year, month, day) do
|
||||
{:ok, {year, month, day}}
|
||||
else
|
||||
{:error, :invalid_date}
|
||||
end
|
||||
else
|
||||
_ ->
|
||||
{:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses a naive datetime string.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23 23:50:07")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {0, 0}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {0, 0}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07Z")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {0, 0}}}
|
||||
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23 23:50:07.0")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {0, 1}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23 23:50:07,0123456")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {12345, 6}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23 23:50:07.0123456")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {12345, 6}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123Z")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {123000, 3}}}
|
||||
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23P23:50:07")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015:01:23 23-50-07")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23 23:50:07A")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23 23:50:61")
|
||||
{:error, :invalid_time}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-32 23:50:07")
|
||||
{:error, :invalid_date}
|
||||
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123+02:30")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {123000, 3}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123+00:00")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {123000, 3}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123-02:30")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {123000, 3}}}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123-00:00")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123-00:60")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_naive_datetime("2015-01-23T23:50:07.123-24:00")
|
||||
{:error, :invalid_format}
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@impl true
|
||||
def parse_naive_datetime("-" <> string) when is_binary(string),
|
||||
do: parse_naive_datetime(string, -1)
|
||||
|
||||
def parse_naive_datetime(string) when is_binary(string),
|
||||
do: parse_naive_datetime(string, 1)
|
||||
|
||||
defp parse_naive_datetime(string, multiplier) do
|
||||
with <<unquote(match_date), sep, unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_date) and sep in @sep and unquote(guard_time),
|
||||
{microsecond, rest} <- parse_microsecond(rest),
|
||||
{_offset, ""} <- parse_offset(rest) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
{hour, minute, second} = unquote(read_time)
|
||||
year = multiplier * year
|
||||
|
||||
cond do
|
||||
not valid_date?(year, month, day) ->
|
||||
{:error, :invalid_date}
|
||||
|
||||
not valid_time?(hour, minute, second, microsecond) ->
|
||||
{:error, :invalid_time}
|
||||
|
||||
true ->
|
||||
{:ok, {year, month, day, hour, minute, second, microsecond}}
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses a UTC datetime string.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23T23:50:07Z")
|
||||
{:ok, {2015, 1, 23, 23, 50, 7, {0, 0}}, 0}
|
||||
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23T23:50:07.123+02:30")
|
||||
{:ok, {2015, 1, 23, 21, 20, 7, {123000, 3}}, 9000}
|
||||
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23T23:50:07,123+02:30")
|
||||
{:ok, {2015, 1, 23, 21, 20, 7, {123000, 3}}, 9000}
|
||||
|
||||
iex> Calendar.ISO.parse_utc_datetime("-2015-01-23T23:50:07Z")
|
||||
{:ok, {-2015, 1, 23, 23, 50, 7, {0, 0}}, 0}
|
||||
|
||||
iex> Calendar.ISO.parse_utc_datetime("-2015-01-23T23:50:07,123+02:30")
|
||||
{:ok, {-2015, 1, 23, 21, 20, 7, {123000, 3}}, 9000}
|
||||
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23P23:50:07")
|
||||
{:error, :invalid_format}
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23T23:50:07")
|
||||
{:error, :missing_offset}
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23 23:50:61")
|
||||
{:error, :invalid_time}
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-32 23:50:07")
|
||||
{:error, :invalid_date}
|
||||
iex> Calendar.ISO.parse_utc_datetime("2015-01-23T23:50:07.123-00:00")
|
||||
{:error, :invalid_format}
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@impl true
|
||||
def parse_utc_datetime("-" <> string) when is_binary(string),
|
||||
do: parse_utc_datetime(string, -1)
|
||||
|
||||
def parse_utc_datetime(string) when is_binary(string),
|
||||
do: parse_utc_datetime(string, 1)
|
||||
|
||||
defp parse_utc_datetime(string, multiplier) do
|
||||
with <<unquote(match_date), sep, unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_date) and sep in @sep and unquote(guard_time),
|
||||
{microsecond, rest} <- parse_microsecond(rest),
|
||||
{offset, ""} <- parse_offset(rest) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
{hour, minute, second} = unquote(read_time)
|
||||
year = multiplier * year
|
||||
|
||||
cond do
|
||||
not valid_date?(year, month, day) ->
|
||||
{:error, :invalid_date}
|
||||
|
||||
not valid_time?(hour, minute, second, microsecond) ->
|
||||
{:error, :invalid_time}
|
||||
|
||||
offset == 0 ->
|
||||
{:ok, {year, month, day, hour, minute, second, microsecond}, offset}
|
||||
|
||||
is_nil(offset) ->
|
||||
{:error, :missing_offset}
|
||||
|
||||
true ->
|
||||
day_fraction = time_to_day_fraction(hour, minute, second, {0, 0})
|
||||
|
||||
{{year, month, day}, {hour, minute, second, _}} =
|
||||
case add_day_fraction_to_iso_days({0, day_fraction}, -offset, 86400) do
|
||||
{0, day_fraction} ->
|
||||
{{year, month, day}, time_from_day_fraction(day_fraction)}
|
||||
|
||||
{extra_days, day_fraction} ->
|
||||
base_days = date_to_iso_days(year, month, day)
|
||||
{date_from_iso_days(base_days + extra_days), time_from_day_fraction(day_fraction)}
|
||||
end
|
||||
|
||||
{:ok, {year, month, day, hour, minute, second, microsecond}, offset}
|
||||
end
|
||||
else
|
||||
_ ->
|
||||
{:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -491,7 +179,7 @@ defmodule Calendar.ISO do
|
||||
@doc since: "1.5.0"
|
||||
@impl true
|
||||
@spec time_from_day_fraction(Calendar.day_fraction()) ::
|
||||
{hour(), minute(), second(), microsecond()}
|
||||
{Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()}
|
||||
def time_from_day_fraction({0, _}) do
|
||||
{0, 0, 0, {0, 6}}
|
||||
end
|
||||
@@ -500,12 +188,12 @@ defmodule Calendar.ISO do
|
||||
total_microseconds = divide_by_parts_per_day(parts_in_day, parts_per_day)
|
||||
|
||||
{hours, rest_microseconds1} =
|
||||
div_rem(total_microseconds, @seconds_per_hour * @microseconds_per_second)
|
||||
div_mod(total_microseconds, @seconds_per_hour * @microseconds_per_second)
|
||||
|
||||
{minutes, rest_microseconds2} =
|
||||
div_rem(rest_microseconds1, @seconds_per_minute * @microseconds_per_second)
|
||||
div_mod(rest_microseconds1, @seconds_per_minute * @microseconds_per_second)
|
||||
|
||||
{seconds, microseconds} = div_rem(rest_microseconds2, @microseconds_per_second)
|
||||
{seconds, microseconds} = div_mod(rest_microseconds2, @microseconds_per_second)
|
||||
{hours, minutes, seconds, {microseconds, 6}}
|
||||
end
|
||||
|
||||
@@ -524,7 +212,7 @@ defmodule Calendar.ISO do
|
||||
719_528
|
||||
end
|
||||
|
||||
def date_to_iso_days(year, month, day) do
|
||||
def date_to_iso_days(year, month, day) when year in -9999..9999 do
|
||||
ensure_day_in_month!(year, month, day)
|
||||
|
||||
days_in_previous_years(year) + days_before_month(month) + leap_day_offset(year, month) + day -
|
||||
@@ -540,7 +228,7 @@ defmodule Calendar.ISO do
|
||||
{year, month, day_in_month + 1}
|
||||
end
|
||||
|
||||
defp div_rem(int1, int2) do
|
||||
defp div_mod(int1, int2) do
|
||||
div = div(int1, int2)
|
||||
rem = int1 - div * int2
|
||||
|
||||
@@ -575,16 +263,14 @@ defmodule Calendar.ISO do
|
||||
@doc since: "1.4.0"
|
||||
@spec days_in_month(year, month) :: 28..31
|
||||
@impl true
|
||||
def days_in_month(year, month) when is_year(year) and is_month(month) do
|
||||
days_in_month_guarded(year, month)
|
||||
end
|
||||
def days_in_month(year, month)
|
||||
|
||||
defp days_in_month_guarded(year, 2) do
|
||||
def days_in_month(year, 2) do
|
||||
if leap_year?(year), do: 29, else: 28
|
||||
end
|
||||
|
||||
defp days_in_month_guarded(_, month) when month in [4, 6, 9, 11], do: 30
|
||||
defp days_in_month_guarded(_, _), do: 31
|
||||
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
|
||||
|
||||
@doc """
|
||||
Returns how many months there are in the given year.
|
||||
@@ -598,8 +284,8 @@ defmodule Calendar.ISO do
|
||||
@doc since: "1.7.0"
|
||||
@impl true
|
||||
@spec months_in_year(year) :: 12
|
||||
def months_in_year(year) when is_year(year) do
|
||||
12
|
||||
def months_in_year(_year) do
|
||||
@months_in_year
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -622,87 +308,47 @@ defmodule Calendar.ISO do
|
||||
@doc since: "1.3.0"
|
||||
@spec leap_year?(year) :: boolean()
|
||||
@impl true
|
||||
def leap_year?(year) when is_year(year) do
|
||||
def leap_year?(year) when is_integer(year) do
|
||||
rem(year, 4) === 0 and (rem(year, 100) !== 0 or rem(year, 400) === 0)
|
||||
end
|
||||
|
||||
# TODO: Deprecate me on v1.15
|
||||
@doc false
|
||||
def day_of_week(year, month, day) do
|
||||
day_of_week(year, month, day, :default) |> elem(0)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the day of the week from the given `year`, `month`, and `day`.
|
||||
|
||||
It is an integer from 1 to 7, where 1 is the given `starting_on` weekday.
|
||||
For example, if `starting_on` is set to `:monday`, then 1 is Monday and
|
||||
7 is Sunday.
|
||||
|
||||
`starting_on` can also be `:default`, which is equivalent to `:monday`.
|
||||
It is an integer from 1 to 7, where 1 is Monday and 7 is Sunday.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.day_of_week(2016, 10, 31, :monday)
|
||||
{1, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 1, :monday)
|
||||
{2, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 2, :monday)
|
||||
{3, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 3, :monday)
|
||||
{4, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 4, :monday)
|
||||
{5, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 5, :monday)
|
||||
{6, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 6, :monday)
|
||||
{7, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(-99, 1, 31, :monday)
|
||||
{4, 1, 7}
|
||||
|
||||
iex> Calendar.ISO.day_of_week(2016, 10, 31, :sunday)
|
||||
{2, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 1, :sunday)
|
||||
{3, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 2, :sunday)
|
||||
{4, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 3, :sunday)
|
||||
{5, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 4, :sunday)
|
||||
{6, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 5, :sunday)
|
||||
{7, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 6, :sunday)
|
||||
{1, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(-99, 1, 31, :sunday)
|
||||
{5, 1, 7}
|
||||
|
||||
iex> Calendar.ISO.day_of_week(2016, 10, 31, :saturday)
|
||||
{3, 1, 7}
|
||||
iex> Calendar.ISO.day_of_week(2016, 10, 31)
|
||||
1
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 1)
|
||||
2
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 2)
|
||||
3
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 3)
|
||||
4
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 4)
|
||||
5
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 5)
|
||||
6
|
||||
iex> Calendar.ISO.day_of_week(2016, 11, 6)
|
||||
7
|
||||
iex> Calendar.ISO.day_of_week(-99, 1, 31)
|
||||
4
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec day_of_week(year, month, day, :default | weekday) :: {day_of_week(), 1, 7}
|
||||
@doc since: "1.4.0"
|
||||
@spec day_of_week(year, month, day) :: 1..7
|
||||
@impl true
|
||||
def day_of_week(year, month, day, starting_on) do
|
||||
iso_days = date_to_iso_days(year, month, day)
|
||||
{iso_days_to_day_of_week(iso_days, starting_on), 1, 7}
|
||||
def day_of_week(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
iso_days_to_day_of_week(date_to_iso_days(year, month, day))
|
||||
end
|
||||
|
||||
@doc false
|
||||
def iso_days_to_day_of_week(iso_days, starting_on) do
|
||||
Integer.mod(iso_days + day_of_week_offset(starting_on), 7) + 1
|
||||
defp iso_days_to_day_of_week(iso_days) do
|
||||
Integer.mod(iso_days + 5, 7) + 1
|
||||
end
|
||||
|
||||
defp day_of_week_offset(:default), do: 5
|
||||
defp day_of_week_offset(:wednesday), do: 3
|
||||
defp day_of_week_offset(:thursday), do: 2
|
||||
defp day_of_week_offset(:friday), do: 1
|
||||
defp day_of_week_offset(:saturday), do: 0
|
||||
defp day_of_week_offset(:sunday), do: 6
|
||||
defp day_of_week_offset(:monday), do: 5
|
||||
defp day_of_week_offset(:tuesday), do: 4
|
||||
|
||||
@doc """
|
||||
Calculates the day of the year from the given `year`, `month`, and `day`.
|
||||
|
||||
@@ -719,9 +365,10 @@ defmodule Calendar.ISO do
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec day_of_year(year, month, day) :: day_of_year()
|
||||
@spec day_of_year(year, month, day) :: 1..366
|
||||
@impl true
|
||||
def day_of_year(year, month, day) do
|
||||
def day_of_year(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
ensure_day_in_month!(year, month, day)
|
||||
days_before_month(month) + leap_day_offset(year, month) + day
|
||||
end
|
||||
@@ -744,19 +391,20 @@ defmodule Calendar.ISO do
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec quarter_of_year(year, month, day) :: quarter_of_year()
|
||||
@spec quarter_of_year(year, month, day) :: 1..4
|
||||
@impl true
|
||||
def quarter_of_year(year, month, day)
|
||||
when is_year(year) and is_month(month) and is_day(day) do
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
div(month - 1, 3) + 1
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the year and era from the given `year`.
|
||||
|
||||
The ISO calendar has two eras: the "current era" (CE) which
|
||||
starts in year `1` and is defined as era `1`. And "before the current
|
||||
era" (BCE) for those years less than `1`, defined as era `0`.
|
||||
The ISO calendar has two eras: the current era which
|
||||
starts in year 1 and is defined as era "1". And a
|
||||
second era for those years less than 1 defined as
|
||||
era "0".
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -771,13 +419,13 @@ defmodule Calendar.ISO do
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec year_of_era(year) :: {1..10000, era}
|
||||
@spec year_of_era(year) :: {year, era :: 0..1}
|
||||
@impl true
|
||||
def year_of_era(year) when is_year_CE(year) do
|
||||
def year_of_era(year) when is_integer(year) and year > 0 do
|
||||
{year, 1}
|
||||
end
|
||||
|
||||
def year_of_era(year) when is_year_BCE(year) do
|
||||
def year_of_era(year) when is_integer(year) and year < 1 do
|
||||
{abs(year) + 1, 0}
|
||||
end
|
||||
|
||||
@@ -799,14 +447,16 @@ defmodule Calendar.ISO do
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec day_of_era(year, month, day) :: Calendar.day_of_era()
|
||||
@spec day_of_era(year, month, day) :: {day :: pos_integer(), era :: 0..1}
|
||||
@impl true
|
||||
def day_of_era(year, month, day) when is_year_CE(year) do
|
||||
def day_of_era(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) and year > 0 do
|
||||
day = date_to_iso_days(year, month, day) - @iso_epoch + 1
|
||||
{day, 1}
|
||||
end
|
||||
|
||||
def day_of_era(year, month, day) when is_year_BCE(year) do
|
||||
def day_of_era(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) and year < 1 do
|
||||
day = abs(date_to_iso_days(year, month, day) - @iso_epoch)
|
||||
{day, 0}
|
||||
end
|
||||
@@ -842,23 +492,14 @@ defmodule Calendar.ISO do
|
||||
Calendar.microsecond(),
|
||||
:basic | :extended
|
||||
) :: String.t()
|
||||
def time_to_string(
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
{ms_value, ms_precision} = microsecond,
|
||||
format \\ :extended
|
||||
)
|
||||
when is_hour(hour) and is_minute(minute) and is_second(second) and
|
||||
is_microsecond(ms_value, ms_precision) and format in [:basic, :extended] do
|
||||
time_to_string_guarded(hour, minute, second, microsecond, format)
|
||||
end
|
||||
def time_to_string(hour, minute, second, microsecond, format \\ :extended)
|
||||
|
||||
defp time_to_string_guarded(hour, minute, second, {_, 0}, format) do
|
||||
def time_to_string(hour, minute, second, {_, 0}, format) when format in [:basic, :extended] do
|
||||
time_to_string_format(hour, minute, second, format)
|
||||
end
|
||||
|
||||
defp time_to_string_guarded(hour, minute, second, {microsecond, precision}, format) do
|
||||
def time_to_string(hour, minute, second, {microsecond, precision}, format)
|
||||
when format in [:basic, :extended] do
|
||||
time_to_string_format(hour, minute, second, format) <>
|
||||
"." <> (microsecond |> zero_pad(6) |> binary_part(0, precision))
|
||||
end
|
||||
@@ -897,16 +538,12 @@ defmodule Calendar.ISO do
|
||||
@spec date_to_string(year, month, day, :basic | :extended) :: String.t()
|
||||
@impl true
|
||||
def date_to_string(year, month, day, format \\ :extended)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) and
|
||||
format in [:basic, :extended] do
|
||||
date_to_string_guarded(year, month, day, format)
|
||||
end
|
||||
|
||||
defp date_to_string_guarded(year, month, day, :extended) do
|
||||
def 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_guarded(year, month, day, :basic) do
|
||||
def date_to_string(year, month, day, :basic) do
|
||||
zero_pad(year, 4) <> zero_pad(month, 2) <> zero_pad(day, 2)
|
||||
end
|
||||
|
||||
@@ -949,7 +586,8 @@ defmodule Calendar.ISO do
|
||||
second,
|
||||
microsecond,
|
||||
format \\ :extended
|
||||
) do
|
||||
)
|
||||
when format in [:basic, :extended] do
|
||||
date_to_string(year, month, day, format) <>
|
||||
" " <> time_to_string(hour, minute, second, microsecond, format)
|
||||
end
|
||||
@@ -963,14 +601,6 @@ defmodule Calendar.ISO do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> time_zone = "Etc/UTC"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "UTC", 0, 0)
|
||||
"2017-08-01 01:02:03.00000Z"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "UTC", 3600, 0)
|
||||
"2017-08-01 01:02:03.00000+01:00"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "UTC", 3600, 3600)
|
||||
"2017-08-01 01:02:03.00000+02:00"
|
||||
|
||||
iex> time_zone = "Europe/Berlin"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "CET", 3600, 0)
|
||||
"2017-08-01 01:02:03.00000+01:00 CET Europe/Berlin"
|
||||
@@ -1018,8 +648,7 @@ defmodule Calendar.ISO do
|
||||
std_offset,
|
||||
format \\ :extended
|
||||
)
|
||||
when is_time_zone(time_zone) and is_zone_abbr(zone_abbr) and is_utc_offset(utc_offset) and
|
||||
is_std_offset(std_offset) do
|
||||
when format in [:basic, :extended] do
|
||||
date_to_string(year, month, day, format) <>
|
||||
" " <>
|
||||
time_to_string(hour, minute, second, microsecond, format) <>
|
||||
@@ -1027,28 +656,6 @@ defmodule Calendar.ISO do
|
||||
zone_to_string(utc_offset, std_offset, zone_abbr, time_zone)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def offset_to_string(0, 0, "Etc/UTC", _format), do: "Z"
|
||||
|
||||
def offset_to_string(utc, std, _zone, format) 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
|
||||
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(_, _, _, "Etc/UTC"), do: ""
|
||||
defp zone_to_string(_, _, abbr, zone), do: " " <> abbr <> " " <> zone
|
||||
|
||||
@doc """
|
||||
Determines if the date given is valid according to the proleptic Gregorian calendar.
|
||||
|
||||
@@ -1067,9 +674,9 @@ defmodule Calendar.ISO do
|
||||
@doc since: "1.5.0"
|
||||
@impl true
|
||||
@spec valid_date?(year, month, day) :: boolean
|
||||
def valid_date?(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
is_year(year) and is_month(month) and day in 1..days_in_month(year, month)
|
||||
def valid_date?(year, month, day) do
|
||||
month in 1..12 and year in -9999..9999 and
|
||||
(is_integer(day) and day >= 1 and day <= days_in_month(year, month))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1093,11 +700,9 @@ defmodule Calendar.ISO do
|
||||
@impl true
|
||||
@spec valid_time?(Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()) ::
|
||||
boolean
|
||||
def valid_time?(hour, minute, second, {ms_value, ms_precision} = _microsecond)
|
||||
when is_integer(hour) and is_integer(minute) and is_integer(second) and is_integer(ms_value) and
|
||||
is_integer(ms_value) do
|
||||
is_hour(hour) and is_minute(minute) and is_second(second) and
|
||||
is_microsecond(ms_value, ms_precision)
|
||||
def valid_time?(hour, minute, second, {microsecond, precision}) do
|
||||
hour in 0..23 and minute in 0..59 and second in 0..59 and microsecond in 0..999_999 and
|
||||
precision in 0..6
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1110,6 +715,27 @@ defmodule Calendar.ISO do
|
||||
{0, 1}
|
||||
end
|
||||
|
||||
defp offset_to_string(0, 0, "Etc/UTC", _format), do: "Z"
|
||||
|
||||
defp offset_to_string(utc, std, _zone, format) 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
|
||||
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
|
||||
|
||||
defp sign(total) when total < 0, do: "-"
|
||||
defp sign(_), do: "+"
|
||||
|
||||
@@ -1151,7 +777,44 @@ defmodule Calendar.ISO do
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_microsecond("." <> rest) do
|
||||
@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)
|
||||
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)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def parse_microsecond("." <> rest) do
|
||||
case parse_microsecond(rest, 0, "") do
|
||||
{"", 0, _} ->
|
||||
:error
|
||||
@@ -1165,11 +828,11 @@ defmodule Calendar.ISO do
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_microsecond("," <> rest) do
|
||||
def parse_microsecond("," <> rest) do
|
||||
parse_microsecond("." <> rest)
|
||||
end
|
||||
|
||||
defp parse_microsecond(rest) do
|
||||
def parse_microsecond(rest) do
|
||||
{{0, 0}, rest}
|
||||
end
|
||||
|
||||
@@ -1178,25 +841,26 @@ defmodule Calendar.ISO do
|
||||
|
||||
defp parse_microsecond(rest, precision, acc), do: {acc, precision, rest}
|
||||
|
||||
defp parse_offset(""), do: {nil, ""}
|
||||
defp parse_offset("Z"), do: {0, ""}
|
||||
defp parse_offset("-00:00"), do: :error
|
||||
@doc false
|
||||
def parse_offset(""), do: {nil, ""}
|
||||
def parse_offset("Z"), do: {0, ""}
|
||||
def parse_offset("-00:00"), do: :error
|
||||
|
||||
defp parse_offset(<<?+, hour::2-bytes, ?:, min::2-bytes, rest::binary>>),
|
||||
def parse_offset(<<?+, hour::2-bytes, ?:, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(1, hour, min, rest)
|
||||
|
||||
defp parse_offset(<<?-, hour::2-bytes, ?:, min::2-bytes, rest::binary>>),
|
||||
def parse_offset(<<?-, hour::2-bytes, ?:, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(-1, hour, min, rest)
|
||||
|
||||
defp parse_offset(<<?+, hour::2-bytes, min::2-bytes, rest::binary>>),
|
||||
def parse_offset(<<?+, hour::2-bytes, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(1, hour, min, rest)
|
||||
|
||||
defp parse_offset(<<?-, hour::2-bytes, min::2-bytes, rest::binary>>),
|
||||
def parse_offset(<<?-, hour::2-bytes, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(-1, hour, min, rest)
|
||||
|
||||
defp parse_offset(<<?+, hour::2-bytes, rest::binary>>), do: parse_offset(1, hour, "00", rest)
|
||||
defp parse_offset(<<?-, hour::2-bytes, rest::binary>>), do: parse_offset(-1, hour, "00", rest)
|
||||
defp parse_offset(_), do: :error
|
||||
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
|
||||
|
||||
defp parse_offset(sign, hour, min, rest) do
|
||||
with {hour, ""} when hour < 24 <- Integer.parse(hour),
|
||||
@@ -1207,14 +871,6 @@ defmodule Calendar.ISO do
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def gregorian_seconds_to_iso_days(seconds, microsecond) do
|
||||
{days, rest_seconds} = div_rem(seconds, @seconds_per_day)
|
||||
microseconds_in_day = rest_seconds * @microseconds_per_second + microsecond
|
||||
day_fraction = {microseconds_in_day, @parts_per_day}
|
||||
{days, day_fraction}
|
||||
end
|
||||
|
||||
@doc false
|
||||
def iso_days_to_unit({days, {parts, ppd}}, unit) do
|
||||
day_microseconds = days * @parts_per_day
|
||||
@@ -1367,7 +1023,7 @@ defmodule Calendar.ISO do
|
||||
end
|
||||
|
||||
defp iso_seconds_to_datetime(seconds) do
|
||||
{days, rest_seconds} = div_rem(seconds, @seconds_per_day)
|
||||
{days, rest_seconds} = div_mod(seconds, @seconds_per_day)
|
||||
|
||||
date = date_from_iso_days(days)
|
||||
time = seconds_to_time(rest_seconds)
|
||||
@@ -1375,13 +1031,13 @@ defmodule Calendar.ISO do
|
||||
end
|
||||
|
||||
defp seconds_to_time(seconds) when seconds in 0..@last_second_of_the_day do
|
||||
{hour, rest_seconds} = div_rem(seconds, @seconds_per_hour)
|
||||
{minute, second} = div_rem(rest_seconds, @seconds_per_minute)
|
||||
{hour, rest_seconds} = div_mod(seconds, @seconds_per_hour)
|
||||
{minute, second} = div_mod(rest_seconds, @seconds_per_minute)
|
||||
|
||||
{hour, minute, second}
|
||||
end
|
||||
|
||||
defp ensure_day_in_month!(year, month, day) when is_integer(day) do
|
||||
defp ensure_day_in_month!(year, month, day) do
|
||||
if day < 1 or day > days_in_month(year, month) do
|
||||
raise ArgumentError, "invalid date: #{date_to_string(year, month, day)}"
|
||||
end
|
||||
|
||||
@@ -78,8 +78,6 @@ defmodule NaiveDateTime do
|
||||
microsecond: Calendar.microsecond()
|
||||
}
|
||||
|
||||
@seconds_per_day 24 * 60 * 60
|
||||
|
||||
@doc """
|
||||
Returns the current naive datetime in UTC.
|
||||
|
||||
@@ -119,53 +117,6 @@ defmodule NaiveDateTime do
|
||||
|> DateTime.to_naive()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the "local time" for the machine the Elixir program is running on.
|
||||
|
||||
WARNING: This function can cause insidious bugs. It depends on the time zone
|
||||
configuration at run time. This can changed and be set to a time zone that has
|
||||
daylight saving jumps (spring forward or fall back).
|
||||
|
||||
This function can be used to display what the time is right now for the time
|
||||
zone configuration that the machine happens to have. An example would be a
|
||||
desktop program displaying a clock to the user. For any other uses it is
|
||||
probably a bad idea to use this function.
|
||||
|
||||
For most cases, use `DateTime.now/2` or `DateTime.utc_now/1` instead.
|
||||
|
||||
Does not include fractional seconds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> naive_datetime = NaiveDateTime.local_now()
|
||||
iex> naive_datetime.year >= 2019
|
||||
true
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec local_now(Calendar.calendar()) :: t
|
||||
def local_now(calendar \\ Calendar.ISO)
|
||||
|
||||
def local_now(Calendar.ISO) do
|
||||
{{year, month, day}, {hour, minute, second}} = :erlang.localtime()
|
||||
{:ok, ndt} = NaiveDateTime.new(year, month, day, hour, minute, second)
|
||||
ndt
|
||||
end
|
||||
|
||||
def local_now(calendar) do
|
||||
naive_datetime = local_now()
|
||||
|
||||
case convert(naive_datetime, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, :incompatible_calendars} ->
|
||||
raise ArgumentError,
|
||||
~s(cannot get "local now" in target calendar #{inspect(calendar)}, ) <>
|
||||
"reason: cannot convert from Calendar.ISO to #{inspect(calendar)}."
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new ISO naive datetime.
|
||||
|
||||
@@ -210,7 +161,7 @@ defmodule NaiveDateTime do
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond() | non_neg_integer,
|
||||
Calendar.microsecond(),
|
||||
Calendar.calendar()
|
||||
) :: {:ok, t} | {:error, atom}
|
||||
def new(year, month, day, hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
@@ -244,61 +195,6 @@ defmodule NaiveDateTime do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new ISO naive datetime.
|
||||
|
||||
Expects all values to be integers. Returns `naive_datetime`
|
||||
if each entry fits its appropriate range, raises if
|
||||
time or date is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.new!(2000, 1, 1, 0, 0, 0)
|
||||
~N[2000-01-01 00:00:00]
|
||||
iex> NaiveDateTime.new!(2000, 2, 29, 0, 0, 0)
|
||||
~N[2000-02-29 00:00:00]
|
||||
iex> NaiveDateTime.new!(2000, 1, 1, 23, 59, 59, {0, 1})
|
||||
~N[2000-01-01 23:59:59.0]
|
||||
iex> NaiveDateTime.new!(2000, 1, 1, 23, 59, 59, 999_999)
|
||||
~N[2000-01-01 23:59:59.999999]
|
||||
iex> NaiveDateTime.new!(2000, 1, 1, 23, 59, 59, {0, 1}, Calendar.ISO)
|
||||
~N[2000-01-01 23:59:59.0]
|
||||
iex> NaiveDateTime.new!(2000, 1, 1, 24, 59, 59, 999_999)
|
||||
** (ArgumentError) cannot build naive datetime, reason: :invalid_time
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec new!(
|
||||
Calendar.year(),
|
||||
Calendar.month(),
|
||||
Calendar.day(),
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond() | non_neg_integer,
|
||||
Calendar.calendar()
|
||||
) :: t
|
||||
def new!(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond \\ {0, 0},
|
||||
calendar \\ Calendar.ISO
|
||||
)
|
||||
|
||||
def new!(year, month, day, hour, minute, second, microsecond, calendar) do
|
||||
case new(year, month, day, hour, minute, second, microsecond, calendar) do
|
||||
{:ok, naive_datetime} ->
|
||||
naive_datetime
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError, "cannot build naive datetime, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a naive datetime from date and time structs.
|
||||
|
||||
@@ -329,24 +225,6 @@ defmodule NaiveDateTime do
|
||||
{:ok, naive_datetime}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a naive datetime from date and time structs.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.new!(~D[2010-01-13], ~T[23:00:07.005])
|
||||
~N[2010-01-13 23:00:07.005]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec new!(Date.t(), Time.t()) :: t
|
||||
def new!(date, time)
|
||||
|
||||
def new!(%Date{calendar: calendar} = date, %Time{calendar: calendar} = time) do
|
||||
{:ok, naive_datetime} = new(date, time)
|
||||
naive_datetime
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds a specified amount of time to a `NaiveDateTime`.
|
||||
|
||||
@@ -656,21 +534,35 @@ defmodule NaiveDateTime do
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) do
|
||||
with {:ok, {year, month, day, hour, minute, second, microsecond}} <-
|
||||
Calendar.ISO.parse_naive_datetime(string) do
|
||||
convert(
|
||||
%NaiveDateTime{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
},
|
||||
calendar
|
||||
)
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<?-, rest::binary>>, calendar) do
|
||||
with {:ok, %{year: year} = naive_datetime} <- raw_from_iso8601(rest, calendar) do
|
||||
{:ok, %{naive_datetime | year: -year}}
|
||||
end
|
||||
end
|
||||
|
||||
def from_iso8601(<<rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar)
|
||||
end
|
||||
|
||||
@sep [?\s, ?T]
|
||||
[match_date, guard_date, read_date] = Calendar.ISO.__match_date__()
|
||||
[match_time, guard_time, read_time] = Calendar.ISO.__match_time__()
|
||||
|
||||
defp raw_from_iso8601(string, calendar) do
|
||||
with <<unquote(match_date), sep, unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_date) and sep in @sep and unquote(guard_time),
|
||||
{microsec, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{_offset, ""} <- Calendar.ISO.parse_offset(rest) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
{hour, min, sec} = unquote(read_time)
|
||||
|
||||
with {:ok, iso_naive_dt} <- new(year, month, day, hour, min, sec, microsec, Calendar.ISO) do
|
||||
convert(iso_naive_dt, calendar)
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -748,8 +640,16 @@ defmodule NaiveDateTime do
|
||||
microsecond: microsecond
|
||||
} = naive_datetime
|
||||
|
||||
Calendar.ISO.date_to_string(year, month, day, format) <>
|
||||
"T" <> Calendar.ISO.time_to_string(hour, minute, second, microsecond, format)
|
||||
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
|
||||
@@ -772,8 +672,8 @@ defmodule NaiveDateTime do
|
||||
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 an Erlang
|
||||
datetime tuple without the time zone information:
|
||||
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},
|
||||
@@ -844,82 +744,6 @@ defmodule NaiveDateTime do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a number of gregorian seconds to a `NaiveDateTime` struct.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.from_gregorian_seconds(1)
|
||||
~N[0000-01-01 00:00:01]
|
||||
iex> NaiveDateTime.from_gregorian_seconds(63_755_511_991, {5000, 3})
|
||||
~N[2020-05-01 00:26:31.005]
|
||||
iex> NaiveDateTime.from_gregorian_seconds(-1)
|
||||
~N[-0001-12-31 23:59:59]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec from_gregorian_seconds(integer(), Calendar.microsecond(), Calendar.calendar()) :: t
|
||||
def from_gregorian_seconds(
|
||||
seconds,
|
||||
{microsecond, precision} \\ {0, 0},
|
||||
calendar \\ Calendar.ISO
|
||||
)
|
||||
when is_integer(seconds) do
|
||||
iso_days = Calendar.ISO.gregorian_seconds_to_iso_days(seconds, microsecond)
|
||||
|
||||
{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
|
||||
|
||||
@doc """
|
||||
Converts a `NaiveDateTime` struct to a number of gregorian seconds and microseconds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.to_gregorian_seconds(~N[0000-01-01 00:00:01])
|
||||
{1, 0}
|
||||
iex> NaiveDateTime.to_gregorian_seconds(~N[2020-05-01 00:26:31.005])
|
||||
{63_755_511_991, 5000}
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec to_gregorian_seconds(Calendar.naive_datetime()) :: {integer(), non_neg_integer()}
|
||||
def to_gregorian_seconds(%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond, precision}
|
||||
}) do
|
||||
{days, day_fraction} =
|
||||
calendar.naive_datetime_to_iso_days(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
{microsecond, precision}
|
||||
)
|
||||
|
||||
seconds_in_day = seconds_from_day_fraction(day_fraction)
|
||||
{days * @seconds_per_day + seconds_in_day, microsecond}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two `NaiveDateTime` structs.
|
||||
|
||||
@@ -1064,12 +888,6 @@ defmodule NaiveDateTime do
|
||||
|
||||
## Helpers
|
||||
|
||||
defp seconds_from_day_fraction({parts_in_day, @seconds_per_day}),
|
||||
do: parts_in_day
|
||||
|
||||
defp seconds_from_day_fraction({parts_in_day, parts_per_day}),
|
||||
do: div(parts_in_day * @seconds_per_day, parts_per_day)
|
||||
|
||||
# Keep it multiline for proper function clause errors.
|
||||
defp to_iso_days(%{
|
||||
calendar: calendar,
|
||||
@@ -1118,7 +936,7 @@ defmodule NaiveDateTime do
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(naive_datetime, _) do
|
||||
def inspect(%{calendar: Calendar.ISO} = naive_datetime, _) do
|
||||
%{
|
||||
year: year,
|
||||
month: month,
|
||||
@@ -1126,17 +944,17 @@ defmodule NaiveDateTime do
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
microsecond: microsecond
|
||||
} = naive_datetime
|
||||
|
||||
formatted =
|
||||
calendar.naive_datetime_to_string(year, month, day, hour, minute, second, microsecond)
|
||||
Calendar.ISO.naive_datetime_to_string(year, month, day, hour, minute, second, microsecond)
|
||||
|
||||
"~N[" <> formatted <> suffix(calendar) <> "]"
|
||||
"~N[" <> formatted <> "]"
|
||||
end
|
||||
|
||||
defp suffix(Calendar.ISO), do: ""
|
||||
defp suffix(calendar), do: " " <> inspect(calendar)
|
||||
def inspect(naive, opts) do
|
||||
Inspect.Any.inspect(naive, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+33
-111
@@ -46,7 +46,6 @@ defmodule Time do
|
||||
}
|
||||
|
||||
@parts_per_day 86_400_000_000
|
||||
@seconds_per_day 24 * 60 * 60
|
||||
|
||||
@doc """
|
||||
Returns the current time in UTC.
|
||||
@@ -111,7 +110,7 @@ defmodule Time do
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond() | non_neg_integer,
|
||||
Calendar.microsecond() | integer,
|
||||
Calendar.calendar()
|
||||
) :: {:ok, t} | {:error, atom}
|
||||
def new(hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
@@ -140,44 +139,6 @@ defmodule Time do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new time.
|
||||
|
||||
Expects all values to be integers. Returns `time` if each
|
||||
entry fits its appropriate range, raises if the time is invalid.
|
||||
|
||||
Microseconds can also be given with a precision, which must be an
|
||||
integer between 0 and 6.
|
||||
|
||||
The built-in calendar does not support leap seconds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.new!(0, 0, 0, 0)
|
||||
~T[00:00:00.000000]
|
||||
iex> Time.new!(23, 59, 59, 999_999)
|
||||
~T[23:59:59.999999]
|
||||
iex> Time.new!(24, 59, 59, 999_999)
|
||||
** (ArgumentError) cannot build time, reason: :invalid_time
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec new!(
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond() | non_neg_integer,
|
||||
Calendar.calendar()
|
||||
) :: t
|
||||
def new!(hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
|
||||
case new(hour, minute, second, microsecond, calendar) do
|
||||
{:ok, time} ->
|
||||
time
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError, "cannot build time, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `time` to a string.
|
||||
|
||||
@@ -252,12 +213,30 @@ defmodule Time do
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) do
|
||||
with {:ok, {hour, minute, second, microsecond}} <- Calendar.ISO.parse_time(string) do
|
||||
convert(
|
||||
%Time{hour: hour, minute: minute, second: second, microsecond: microsecond},
|
||||
calendar
|
||||
)
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<?T, rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar)
|
||||
end
|
||||
|
||||
def from_iso8601(<<rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar)
|
||||
end
|
||||
|
||||
[match_time, guard_time, read_time] = Calendar.ISO.__match_time__()
|
||||
|
||||
defp raw_from_iso8601(string, calendar) do
|
||||
with <<unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_time),
|
||||
{microsec, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{_offset, ""} <- Calendar.ISO.parse_offset(rest) do
|
||||
{hour, min, sec} = unquote(read_time)
|
||||
|
||||
with {:ok, utc_time} <- new(hour, min, sec, microsec, Calendar.ISO) do
|
||||
convert(utc_time, calendar)
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -397,63 +376,6 @@ defmodule Time do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a number of seconds after midnight to a `Time` struct.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.from_seconds_after_midnight(10_000)
|
||||
~T[02:46:40]
|
||||
iex> Time.from_seconds_after_midnight(30_000, {5000, 3})
|
||||
~T[08:20:00.005]
|
||||
iex> Time.from_seconds_after_midnight(-1)
|
||||
~T[23:59:59]
|
||||
iex> Time.from_seconds_after_midnight(100_000)
|
||||
~T[03:46:40]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec from_seconds_after_midnight(
|
||||
integer(),
|
||||
Calendar.microsecond(),
|
||||
Calendar.calendar()
|
||||
) :: t
|
||||
def from_seconds_after_midnight(seconds, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
when is_integer(seconds) do
|
||||
seconds_in_day = Integer.mod(seconds, @seconds_per_day)
|
||||
|
||||
{hour, minute, second, {_, _}} =
|
||||
calendar.time_from_day_fraction({seconds_in_day, @seconds_per_day})
|
||||
|
||||
%Time{
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `Time` struct to a number of seconds after midnight.
|
||||
|
||||
The returned value is a two-element tuple with the number of seconds and microseconds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.to_seconds_after_midnight(~T[23:30:15])
|
||||
{84615, 0}
|
||||
iex> Time.to_seconds_after_midnight(~N[2010-04-17 23:30:15.999])
|
||||
{84615, 999000}
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec to_seconds_after_midnight(Calendar.time()) :: {integer(), non_neg_integer()}
|
||||
def to_seconds_after_midnight(%{microsecond: {microsecond, _precision}} = time) do
|
||||
iso_days = {0, to_day_fraction(time)}
|
||||
{Calendar.ISO.iso_days_to_unit(iso_days, :second), microsecond}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds the `number` of `unit`s to the given `time`.
|
||||
|
||||
@@ -652,12 +574,12 @@ defmodule Time do
|
||||
|
||||
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, minute, second, and microsecond is considered. Any
|
||||
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 time value is earlier than
|
||||
`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
|
||||
@@ -771,20 +693,20 @@ defmodule Time do
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(time, _) do
|
||||
def inspect(%{calendar: Calendar.ISO} = time, _) do
|
||||
%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
calendar: Calendar.ISO
|
||||
} = time
|
||||
|
||||
"~T[" <>
|
||||
calendar.time_to_string(hour, minute, second, microsecond) <> suffix(calendar) <> "]"
|
||||
"~T[" <> Calendar.ISO.time_to_string(hour, minute, second, microsecond) <> "]"
|
||||
end
|
||||
|
||||
defp suffix(Calendar.ISO), do: ""
|
||||
defp suffix(calendar), do: " " <> inspect(calendar)
|
||||
def inspect(time, opts) do
|
||||
Inspect.Any.inspect(time, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -59,7 +59,7 @@ defmodule Calendar.TimeZoneDatabase do
|
||||
with a limit for when the period ends (wall time). The second nested two-tuple is the period
|
||||
just after the gap and a datetime (wall time) for when the period begins just after the gap.
|
||||
|
||||
If there is only a single possible period for the provided `datetime`, then a tuple with `:ok`
|
||||
If there is only a single possible period for the provided `datetime`, the a tuple with `:single`
|
||||
and the `time_zone_period` is returned.
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
|
||||
+123
-396
@@ -1,5 +1,5 @@
|
||||
defmodule Code do
|
||||
@moduledoc ~S"""
|
||||
@moduledoc """
|
||||
Utilities for managing code compilation, code evaluation, and code loading.
|
||||
|
||||
This module complements Erlang's [`:code` module](http://www.erlang.org/doc/man/code.html)
|
||||
@@ -19,8 +19,7 @@ defmodule Code do
|
||||
|
||||
* `eval_file/2` - evaluates the file contents without tracking its name. It
|
||||
returns the result of the last expression in the file, instead of the modules
|
||||
defined in it. Evaluated files do not trigger the compilation tracers described
|
||||
in the next section.
|
||||
defined in it.
|
||||
|
||||
In a nutshell, the first must be used when you want to keep track of the files
|
||||
handled by the system, to avoid the same file from being compiled multiple
|
||||
@@ -29,100 +28,9 @@ defmodule Code do
|
||||
`compile_file/2` must be used when you are interested in the modules defined in a
|
||||
file, without tracking. `eval_file/2` should be used when you are interested in
|
||||
the result of evaluating the file rather than the modules it defines.
|
||||
|
||||
## Compilation tracers
|
||||
|
||||
Elixir supports compilation tracers, which allows modules to observe constructs
|
||||
handled by the Elixir compiler when compiling files. A tracer is a module
|
||||
that implements the `trace/2` function. The function receives the event name
|
||||
as first argument and `Macro.Env` as second and it must return `:ok`. It is
|
||||
very important for a tracer to do as little work as possible synchronously
|
||||
and dispatch the bulk of the work to a separate process. **Slow tracers will
|
||||
slow down compilation**.
|
||||
|
||||
You can configure your list of tracers via `put_compiler_option/2`. The
|
||||
following events are available to tracers:
|
||||
|
||||
* `:start` - (since v1.11.0) invoked whenever the compiler starts to trace
|
||||
a new lexical context, such as a new file. Keep in mind the compiler runs
|
||||
in parallel, so multiple files may invoke `:start` and run at the same
|
||||
time. The value of the `lexical_tracker` of the macro environment, albeit
|
||||
opaque, can be used to uniquely identify the environment.
|
||||
|
||||
* `:stop` - (since v1.11.0) invoked whenever the compiler stops tracing a
|
||||
new lexical context, such as a new file.
|
||||
|
||||
* `{:import, meta, module, opts}` - traced whenever `module` is imported.
|
||||
`meta` is the import AST metadata and `opts` are the import options.
|
||||
|
||||
* `{:imported_function, meta, module, name, arity}` and
|
||||
`{:imported_macro, meta, module, name, arity}` - traced whenever an
|
||||
imported function or macro is invoked. `meta` is the call AST metadata,
|
||||
`module` is the module the import is from, followed by the `name` and `arity`
|
||||
of the imported function/macro.
|
||||
|
||||
* `{:alias, meta, alias, as, opts}` - traced whenever `alias` is aliased
|
||||
to `as`. `meta` is the alias AST metadata and `opts` are the alias options.
|
||||
|
||||
* `{:alias_expansion, meta, as, alias}` traced whenever there is an alias
|
||||
expansion for a previously defined `alias`, i.e. when the user writes `as`
|
||||
which is expanded to `alias`. `meta` is the alias expansion AST metadata.
|
||||
|
||||
* `{:alias_reference, meta, module}` - traced whenever there is an alias
|
||||
in the code, i.e. whenever the user writes `MyModule.Foo.Bar` in the code,
|
||||
regardless if it was expanded or not.
|
||||
|
||||
* `{:require, meta, module, opts}` - traced whenever `module` is required.
|
||||
`meta` is the require AST metadata and `opts` are the require options.
|
||||
|
||||
* `{:struct_expansion, meta, module, keys}` - traced whenever `module`'s struct
|
||||
is expanded. `meta` is the struct AST metadata and `keys` are the keys being
|
||||
used by expansion
|
||||
|
||||
* `{:remote_function, meta, module, name, arity}` and
|
||||
`{:remote_macro, meta, module, name, arity}` - traced whenever a remote
|
||||
function or macro is referenced. `meta` is the call AST metadata, `module`
|
||||
is the invoked module, followed by the `name` and `arity`.
|
||||
|
||||
* `{:local_function, meta, name, arity}` and
|
||||
`{:local_macro, meta, name, arity}` - traced whenever a local
|
||||
function or macro is referenced. `meta` is the call AST metadata, followed by
|
||||
the `name` and `arity`.
|
||||
|
||||
* `{:compile_env, app, path, return}` - traced whenever `Application.compile_env/3`
|
||||
or `Application.compile_env!/2` are called. `app` is an atom, `path` is a list
|
||||
of keys to traverse in the application environment and `return` is either
|
||||
`{:ok, value}` or `:error`.
|
||||
|
||||
The `:tracers` compiler option can be combined with the `:parser_options`
|
||||
compiler option to enrich the metadata of the traced events above.
|
||||
|
||||
New events may be added at any time in the future, therefore it is advised
|
||||
for the `trace/2` function to have a "catch-all" clause.
|
||||
|
||||
Below is an example tracer that prints all remote function invocations:
|
||||
|
||||
defmodule MyTracer do
|
||||
def trace({:remote_function, _meta, module, name, arity}, env) do
|
||||
IO.puts "#{env.file}:#{env.line} #{inspect(module)}.#{name}/#{arity}"
|
||||
:ok
|
||||
end
|
||||
|
||||
def trace(_event, _env) do
|
||||
:ok
|
||||
end
|
||||
end
|
||||
"""
|
||||
|
||||
@typedoc """
|
||||
A list with all variable bindings.
|
||||
|
||||
The binding keys are usually atoms, but they may be a tuple for variables
|
||||
defined in a different context.
|
||||
"""
|
||||
@type binding :: [{atom() | tuple(), any}]
|
||||
|
||||
@boolean_compiler_options [
|
||||
@available_compiler_options [
|
||||
:docs,
|
||||
:debug_info,
|
||||
:ignore_module_conflict,
|
||||
@@ -130,10 +38,6 @@ defmodule Code do
|
||||
:warnings_as_errors
|
||||
]
|
||||
|
||||
@list_compiler_options [:no_warn_undefined, :tracers, :parser_options]
|
||||
|
||||
@available_compiler_options @boolean_compiler_options ++ @list_compiler_options
|
||||
|
||||
@doc """
|
||||
Lists all required files.
|
||||
|
||||
@@ -150,7 +54,7 @@ defmodule Code do
|
||||
:elixir_code_server.call(:required)
|
||||
end
|
||||
|
||||
@deprecated "Use Code.required_files/0 instead"
|
||||
# TODO: Deprecate on v1.9
|
||||
@doc false
|
||||
def loaded_files do
|
||||
required_files()
|
||||
@@ -171,18 +75,18 @@ defmodule Code do
|
||||
# Now unrequire all files
|
||||
Code.unrequire_files(Code.required_files())
|
||||
|
||||
# Note that modules are still available
|
||||
# Notice modules are still available
|
||||
function_exported?(EExTest.Compiled, :before_compile, 0)
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec unrequire_files([binary]) :: :ok
|
||||
def unrequire_files(files) when is_list(files) do
|
||||
def unrequire_files(files) do
|
||||
:elixir_code_server.cast({:unrequire_files, files})
|
||||
end
|
||||
|
||||
@deprecated "Use Code.unrequire_files/1 instead"
|
||||
# TODO: Deprecate on v1.9
|
||||
@doc false
|
||||
def unload_files(files) do
|
||||
unrequire_files(files)
|
||||
@@ -259,7 +163,7 @@ defmodule Code do
|
||||
@doc """
|
||||
Evaluates the contents given by `string`.
|
||||
|
||||
The `binding` argument is a list of variable bindings.
|
||||
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
|
||||
@@ -290,7 +194,7 @@ defmodule Code do
|
||||
and the second a list of imported macro names and arity; the list
|
||||
of function names and arity must be sorted
|
||||
|
||||
Note that setting any of the values above overrides Elixir's default
|
||||
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`,
|
||||
@@ -300,8 +204,8 @@ defmodule Code do
|
||||
where `value` is the value returned from evaluating `string`.
|
||||
If an error occurs while evaluating `string` an exception will be raised.
|
||||
|
||||
`binding` is a list with all variable bindings
|
||||
after evaluating `string`. The binding keys are usually atoms, but they
|
||||
`binding` is a keyword list with the value of all variable bindings
|
||||
after evaluating `string`. The binding key is usually an atom, but it
|
||||
may be a tuple for variables defined in a different context.
|
||||
|
||||
## Examples
|
||||
@@ -323,22 +227,17 @@ defmodule Code do
|
||||
{3, [a: 1, b: 2]}
|
||||
|
||||
"""
|
||||
@spec eval_string(List.Chars.t(), binding, Macro.Env.t() | keyword) :: {term, binding}
|
||||
@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
|
||||
eval_string_with_error_handling(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)
|
||||
eval_string_with_error_handling(string, binding, opts)
|
||||
end
|
||||
|
||||
defp eval_string_with_error_handling(string, binding, opts) do
|
||||
%{line: line, file: file} = env = :elixir.env_for_eval(opts)
|
||||
forms = :elixir.string_to_quoted!(to_charlist(string), line, 1, file, [])
|
||||
{value, binding, _env} = :elixir.eval_forms(forms, binding, env)
|
||||
{value, binding, _env, _scope} = :elixir.eval(to_charlist(string), binding, opts)
|
||||
{value, binding}
|
||||
end
|
||||
|
||||
@@ -375,7 +274,7 @@ defmodule Code do
|
||||
|
||||
* `:force_do_end_blocks` (since v1.9.0) - when `true`, converts all
|
||||
inline usages of `do: ...`, `else: ...` and friends into `do/end`
|
||||
blocks. Defaults to `false`. Note that this option is convergent:
|
||||
blocks. Defaults to `false`. Notice this option is convergent:
|
||||
once you set it to `true`, all keywords will be converted. If you
|
||||
set it to `false` later on, `do/end` blocks won't be converted
|
||||
back to keywords.
|
||||
@@ -395,7 +294,7 @@ defmodule Code do
|
||||
a whole.
|
||||
|
||||
The formatter does not hard code names. The formatter will not behave
|
||||
specially because a function is named `defmodule`, `def`, or the like. This
|
||||
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
|
||||
@@ -532,7 +431,7 @@ defmodule Code do
|
||||
rules in the future. The goal of documenting them is to provide better
|
||||
understanding on what to expect from the formatter.
|
||||
|
||||
### Multi-line lists, maps, tuples, and the like
|
||||
### 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
|
||||
@@ -677,7 +576,7 @@ defmodule Code do
|
||||
Macro arguments are typically transformed by unquoting them into the
|
||||
returned quoted expressions (instead of evaluated).
|
||||
|
||||
See `eval_string/3` for a description of `binding` and options.
|
||||
See `eval_string/3` for a description of bindings and options.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -693,17 +592,17 @@ defmodule Code do
|
||||
{3, [a: 1, b: 2]}
|
||||
|
||||
"""
|
||||
@spec eval_quoted(Macro.t(), binding, Macro.Env.t() | keyword) :: {term, binding}
|
||||
@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} = :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} = :elixir.eval_quoted(quoted, binding, opts)
|
||||
{value, binding, _env, _scope} = :elixir.eval_quoted(quoted, binding, opts)
|
||||
{value, binding}
|
||||
end
|
||||
|
||||
@@ -745,7 +644,7 @@ defmodule Code do
|
||||
end
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
@doc """
|
||||
Converts the given string to its quoted form.
|
||||
|
||||
Returns `{:ok, quoted_form}` if it succeeds,
|
||||
@@ -759,9 +658,6 @@ defmodule Code do
|
||||
* `:line` - the starting line of the string being parsed.
|
||||
Defaults to 1.
|
||||
|
||||
* `:column` - (since v1.11.0) the starting column of the string being parsed.
|
||||
Defaults to 1.
|
||||
|
||||
* `:columns` - when `true`, attach a `:column` key to the quoted
|
||||
metadata. Defaults to `false`.
|
||||
|
||||
@@ -769,23 +665,11 @@ defmodule Code do
|
||||
when non-existing atoms are found by the tokenizer.
|
||||
Defaults to `false`.
|
||||
|
||||
* `:token_metadata` (since v1.10.0) - when `true`, includes token-related
|
||||
metadata in the expression AST, such as metadata for `do` and `end`
|
||||
tokens, for closing tokens, end of expressions, as well as delimiters
|
||||
for sigils. See `t:Macro.metadata/0`. Defaults to `false`.
|
||||
|
||||
* `:literal_encoder` (since v1.10.0) - how to encode literals in the AST.
|
||||
It must be a function that receives two arguments, the literal and its
|
||||
metadata, and it must return `{:ok, ast :: Macro.t}` or
|
||||
`{:error, reason :: binary}`. If you return anything than the literal
|
||||
itself as the `term`, then the AST is no longer valid. This option
|
||||
may still useful for textual analysis of the source code.
|
||||
|
||||
* `:static_atoms_encoder` - the static atom encoder function, see
|
||||
"The `:static_atoms_encoder` function" section below. Note this
|
||||
option overrides the `:existing_atoms_only` behaviour for static
|
||||
atoms but `:existing_atoms_only` is still used for dynamic atoms,
|
||||
such as atoms with interpolations.
|
||||
* `:static_atom_encoder` - The static atom encoder function, see
|
||||
"The `:static_atom_encoder` function" section below. This option
|
||||
overrides the `:existing_atoms_only` behaviour for static atoms
|
||||
but `:existing_atoms_only` is still used for dynamic atoms, such
|
||||
as atoms with interpolations.
|
||||
|
||||
* `:warn_on_unnecessary_quotes` - when `false`, does not warn
|
||||
when atoms, keywords or calls have unnecessary quotes on
|
||||
@@ -797,9 +681,9 @@ defmodule Code do
|
||||
`Macro.to_string/2`, which converts a quoted form to a string/binary
|
||||
representation.
|
||||
|
||||
## The `:static_atoms_encoder` function
|
||||
## The `:static_atom_encoder` function
|
||||
|
||||
When `static_atoms_encoder: &my_encoder/2` is passed as an argument,
|
||||
When `static_atom_encoder: &my_encoder/2` is passed as an argument,
|
||||
`my_encoder/2` is called every time the tokenizer needs to create a
|
||||
"static" atom. Static atoms are atoms in the AST that function as
|
||||
aliases, remote calls, local calls, variable names, regular atoms
|
||||
@@ -810,8 +694,8 @@ defmodule Code do
|
||||
`{:ok, token :: term} | {:error, reason :: binary}`.
|
||||
|
||||
The encoder function is supposed to create an atom from the given
|
||||
string. To produce a valid AST, it is required to return `{:ok, term}`,
|
||||
where `term` is an atom. It is possible to return something other than an atom,
|
||||
string. It is required to return either `{:ok, term}`, where term is
|
||||
an atom. It is possible to return something else than an atom,
|
||||
however, in that case the AST is no longer "valid" in that it cannot
|
||||
be used to compile or evaluate Elixir code. A use case for this is
|
||||
if you want to use the Elixir parser in a user-facing situation, but
|
||||
@@ -824,18 +708,17 @@ defmodule Code do
|
||||
|
||||
* syntax keywords (`fn`, `do`, `else`, and so on)
|
||||
|
||||
* atoms containing interpolation (`:"#{1 + 1} is two"`), as these
|
||||
* atoms containing interpolation (`:"\#{1 + 1} is two"`), as these
|
||||
atoms are constructed at runtime.
|
||||
|
||||
"""
|
||||
@spec string_to_quoted(List.Chars.t(), keyword) ::
|
||||
{:ok, Macro.t()} | {:error, {location :: keyword, term, term}}
|
||||
{: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)
|
||||
column = Keyword.get(opts, :column, 1)
|
||||
|
||||
case :elixir.string_to_tokens(to_charlist(string), line, column, file, opts) do
|
||||
case :elixir.string_to_tokens(to_charlist(string), line, file, opts) do
|
||||
{:ok, tokens} ->
|
||||
:elixir.tokens_to_quoted(tokens, file, opts)
|
||||
|
||||
@@ -858,8 +741,7 @@ defmodule Code do
|
||||
def string_to_quoted!(string, opts \\ []) when is_list(opts) do
|
||||
file = Keyword.get(opts, :file, "nofile")
|
||||
line = Keyword.get(opts, :line, 1)
|
||||
column = Keyword.get(opts, :column, 1)
|
||||
:elixir.string_to_quoted!(to_charlist(string), line, column, file, opts)
|
||||
:elixir.string_to_quoted!(to_charlist(string), line, file, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -869,22 +751,22 @@ defmodule Code do
|
||||
|
||||
While `require_file/2` and `compile_file/2` return the loaded modules and their
|
||||
bytecode, `eval_file/2` simply evaluates the file contents and returns the
|
||||
evaluation result and its binding (exactly the same return value as `eval_string/3`).
|
||||
evaluation result and its bindings (exactly the same return value as `eval_string/3`).
|
||||
"""
|
||||
@spec eval_file(binary, nil | binary) :: {term, binding}
|
||||
@spec eval_file(binary, nil | binary) :: {term, binding :: list}
|
||||
def eval_file(file, relative_to \\ nil) when is_binary(file) do
|
||||
file = find_file(file, relative_to)
|
||||
eval_string(File.read!(file), [], file: file, line: 1)
|
||||
end
|
||||
|
||||
@deprecated "Use Code.require_file/2 or Code.compile_file/2 instead"
|
||||
# TODO: Deprecate on v1.9
|
||||
@doc false
|
||||
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, fn _, _ -> :ok end)
|
||||
:elixir_code_server.cast({:required, file})
|
||||
verify_loaded(loaded)
|
||||
loaded
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -894,7 +776,7 @@ defmodule Code do
|
||||
If the file was already required, `require_file/2` doesn't do anything and
|
||||
returns `nil`.
|
||||
|
||||
Note that if `require_file/2` is invoked by different processes concurrently,
|
||||
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 once with a given file, that file will be compiled only once.
|
||||
@@ -930,15 +812,14 @@ defmodule Code do
|
||||
:proceed ->
|
||||
loaded = :elixir_compiler.file(file, fn _, _ -> :ok end)
|
||||
:elixir_code_server.cast({:required, file})
|
||||
verify_loaded(loaded)
|
||||
loaded
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets all compilation options from the code server.
|
||||
Gets the compilation options from the code server.
|
||||
|
||||
To get individual options, see `get_compiler_option/1`.
|
||||
For a description of all options, see `put_compiler_option/2`.
|
||||
Check `compiler_options/1` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -946,55 +827,15 @@ defmodule Code do
|
||||
#=> %{debug_info: true, docs: true, ...}
|
||||
|
||||
"""
|
||||
@spec compiler_options :: map
|
||||
@spec compiler_options() :: %{optional(atom) => boolean}
|
||||
def compiler_options do
|
||||
for key <- @available_compiler_options, into: %{} do
|
||||
{key, :elixir_config.get(key)}
|
||||
end
|
||||
:elixir_config.get(:compiler_options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Stores all given compilation options.
|
||||
Returns a list with the available compiler options.
|
||||
|
||||
To store individual options, see `put_compiler_option/2`.
|
||||
For a description of all options, see `put_compiler_option/2`.
|
||||
|
||||
## Examples
|
||||
|
||||
Code.compiler_options()
|
||||
#=> %{debug_info: true, docs: true, ...}
|
||||
|
||||
"""
|
||||
@spec compiler_options(Enumerable.t()) :: %{optional(atom) => boolean}
|
||||
def compiler_options(opts) do
|
||||
for {key, value} <- opts, into: %{} do
|
||||
previous = get_compiler_option(key)
|
||||
put_compiler_option(key, value)
|
||||
{key, previous}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the value of a given compiler option.
|
||||
|
||||
For a description of all options, see `put_compiler_option/2`.
|
||||
|
||||
## Examples
|
||||
|
||||
Code.get_compiler_option(:debug_info)
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec get_compiler_option(atom) :: term
|
||||
def get_compiler_option(key) when key in @available_compiler_options do
|
||||
:elixir_config.get(key)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a list with all available compiler options.
|
||||
|
||||
For a description of all options, see `put_compiler_option/2`.
|
||||
See `compiler_options/1` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1007,101 +848,11 @@ defmodule Code do
|
||||
@available_compiler_options
|
||||
end
|
||||
|
||||
@doc """
|
||||
Stores a compilation option.
|
||||
|
||||
These options are global since they are stored by Elixir's code server.
|
||||
|
||||
Available options are:
|
||||
|
||||
* `:docs` - when `true`, retain documentation in the compiled module.
|
||||
Defaults to `true`.
|
||||
|
||||
* `:debug_info` - when `true`, retain debug information in the compiled
|
||||
module. This allows a developer to reconstruct the original source
|
||||
code. Defaults to `true`.
|
||||
|
||||
* `:ignore_module_conflict` - when `true`, override modules that were
|
||||
already defined without raising errors. Defaults to `false`.
|
||||
|
||||
* `: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_as_errors` - causes compilation to fail when warnings are
|
||||
generated. Defaults to `false`.
|
||||
|
||||
* `:no_warn_undefined` (since v1.10.0) - list of modules and `{Mod, fun, arity}`
|
||||
tuples that will not emit warnings that the module or function does not exist
|
||||
at compilation time. Pass atom `:all` to skip warning for all undefined
|
||||
functions. This can be useful when doing dynamic compilation. Defaults to `[]`.
|
||||
|
||||
* `:tracers` (since v1.10.0) - a list of tracers (modules) to be used during
|
||||
compilation. See the module docs for more information. Defaults to `[]`.
|
||||
|
||||
* `:parser_options` (since v1.10.0) - a keyword list of options to be given
|
||||
to the parser when compiling files. It accepts the same options as
|
||||
`string_to_quoted/2` (except by the options that change the AST itself).
|
||||
This can be used in combination with the tracer to retrieve localized
|
||||
information about events happening during compilation. Defaults to `[]`.
|
||||
|
||||
It always returns `:ok`. Raises an error for invalid options.
|
||||
|
||||
## Examples
|
||||
|
||||
Code.put_compiler_option(:debug_info, true)
|
||||
#=> :ok
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec put_compiler_option(atom, term) :: :ok
|
||||
def put_compiler_option(key, value) when key in @boolean_compiler_options do
|
||||
if not is_boolean(value) do
|
||||
raise "compiler option #{inspect(key)} should be a boolean, got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
:elixir_config.put(key, value)
|
||||
:ok
|
||||
end
|
||||
|
||||
def put_compiler_option(:no_warn_undefined, value) do
|
||||
if value != :all and not is_list(value) do
|
||||
raise "compiler option :no_warn_undefined should be a list or the atom :all, " <>
|
||||
"got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
:elixir_config.put(:no_warn_undefined, value)
|
||||
:ok
|
||||
end
|
||||
|
||||
def put_compiler_option(key, value) when key in @list_compiler_options do
|
||||
if not is_list(value) do
|
||||
raise "compiler option #{inspect(key)} should be a list, got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
if key == :parser_options and not Keyword.keyword?(value) do
|
||||
raise "compiler option #{inspect(key)} should be a keyword list, " <>
|
||||
"got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
if key == :tracers and not Enum.all?(value, &is_atom/1) do
|
||||
raise "compiler option #{inspect(key)} should be a list of modules, " <>
|
||||
"got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
:elixir_config.put(key, value)
|
||||
:ok
|
||||
end
|
||||
|
||||
def put_compiler_option(key, _value) do
|
||||
raise "unknown compiler option: #{inspect(key)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Purge compiler modules.
|
||||
|
||||
The compiler utilizes temporary modules to compile code. For example,
|
||||
`elixir_compiler_1`, `elixir_compiler_2`, and so on. In case the compiled code
|
||||
`elixir_compiler_1`, `elixir_compiler_2`, etc. In case the compiled code
|
||||
stores references to anonymous functions or similar, the Elixir compiler
|
||||
may be unable to reclaim those modules, keeping an unnecessary amount of
|
||||
code in memory and eventually leading to modules such as `elixir_compiler_12345`.
|
||||
@@ -1118,6 +869,54 @@ defmodule Code do
|
||||
:elixir_code_server.call(:purge_compiler_modules)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sets compilation options.
|
||||
|
||||
These options are global since they are stored by Elixir's Code Server.
|
||||
|
||||
Available options are:
|
||||
|
||||
* `:docs` - when `true`, retain documentation in the compiled module.
|
||||
Defaults to `true`.
|
||||
|
||||
* `:debug_info` - when `true`, retain debug information in the compiled
|
||||
module. This allows a developer to reconstruct the original source
|
||||
code. Defaults to `false`.
|
||||
|
||||
* `:ignore_module_conflict` - when `true`, override modules that were
|
||||
already defined without raising errors. Defaults to `false`.
|
||||
|
||||
* `: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_as_errors` - causes compilation to fail when warnings are
|
||||
generated. Defaults to `false`.
|
||||
|
||||
It returns the new map of compiler options.
|
||||
|
||||
## Examples
|
||||
|
||||
Code.compiler_options(debug_info: true)
|
||||
#=> %{debug_info: true, docs: true,
|
||||
#=> warnings_as_errors: false, ignore_module_conflict: false}
|
||||
|
||||
"""
|
||||
@spec compiler_options(Enumerable.t()) :: %{optional(atom) => boolean}
|
||||
def compiler_options(opts) do
|
||||
Enum.each(opts, fn
|
||||
{key, value} when key in @available_compiler_options ->
|
||||
if not is_boolean(value) do
|
||||
raise "compiler option #{inspect(key)} should be a boolean, got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
{key, _} ->
|
||||
raise "unknown compiler option: #{inspect(key)}"
|
||||
end)
|
||||
|
||||
:elixir_config.update(:compiler_options, &Enum.into(opts, &1))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles the given string.
|
||||
|
||||
@@ -1134,8 +933,7 @@ defmodule Code do
|
||||
"""
|
||||
@spec compile_string(List.Chars.t(), binary) :: [{module, binary}]
|
||||
def compile_string(string, file \\ "nofile") when is_binary(file) do
|
||||
loaded = :elixir_compiler.string(to_charlist(string), file, fn _, _ -> :ok end)
|
||||
Enum.map(loaded, fn {module, _map, binary} -> {module, binary} end)
|
||||
:elixir_compiler.string(to_charlist(string), file, fn _, _ -> :ok end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1148,8 +946,7 @@ defmodule Code do
|
||||
"""
|
||||
@spec compile_quoted(Macro.t(), binary) :: [{module, binary}]
|
||||
def compile_quoted(quoted, file \\ "nofile") when is_binary(file) do
|
||||
loaded = :elixir_compiler.quoted(quoted, file, fn _, _ -> :ok end)
|
||||
Enum.map(loaded, fn {module, _map, binary} -> {module, binary} end)
|
||||
:elixir_compiler.quoted(quoted, file, fn _, _ -> :ok end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1169,8 +966,7 @@ defmodule Code do
|
||||
@doc since: "1.7.0"
|
||||
@spec compile_file(binary, nil | binary) :: [{module, binary}]
|
||||
def compile_file(file, relative_to \\ nil) when is_binary(file) do
|
||||
loaded = :elixir_compiler.file(find_file(file, relative_to), fn _, _ -> :ok end)
|
||||
verify_loaded(loaded)
|
||||
:elixir_compiler.file(find_file(file, relative_to), fn _, _ -> :ok end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1253,39 +1049,27 @@ defmodule Code do
|
||||
Ensures the given module is compiled and loaded.
|
||||
|
||||
If the module is already loaded, it works as no-op. If the module was
|
||||
not compiled yet, `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.
|
||||
|
||||
Given this function halts compilation, use it carefully. In particular,
|
||||
avoid using it to guess which modules are in the system. Overuse of this
|
||||
function can also lead to deadlocks, where two modules check at the same time
|
||||
if the other is compiled. This returns a specific unavailable error code,
|
||||
where we cannot successfully verify a module is available or not.
|
||||
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 not, returns `{:error, reason}` with the error reason.
|
||||
|
||||
If the module being checked is currently in a compiler deadlock,
|
||||
this function returns `{:error, :unavailable}`. Unavailable doesn't
|
||||
necessarily mean the module doesn't exist, just that it is not currently
|
||||
available, but it (or may not) become available in the future.
|
||||
this functions returns `{:error, :nofile}`.
|
||||
|
||||
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 | :unavailable}
|
||||
{: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 can_await_module_compilation?() do
|
||||
if is_pid(:erlang.get(:elixir_compiler_pid)) do
|
||||
case Kernel.ErrorHandler.ensure_compiled(module, :module, :soft) do
|
||||
:found -> {:module, module}
|
||||
:deadlock -> {:error, :unavailable}
|
||||
:not_found -> {:error, :nofile}
|
||||
:not_found -> error
|
||||
end
|
||||
else
|
||||
error
|
||||
@@ -1297,22 +1081,13 @@ defmodule Code do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns true if the current process can await for module compilation.
|
||||
Ensures the given module is compiled and loaded.
|
||||
|
||||
When compiling Elixir code via `Kernel.ParallelCompiler`, which is
|
||||
used by Mix and `elixirc`, calling a module that has not yet been
|
||||
compiled will block the caller until the module becomes available.
|
||||
Executing Elixir scripts, such as passing a filename to `elixir`,
|
||||
does not await.
|
||||
Similar to `ensure_compiled/1`, but returns `true` if the module
|
||||
is already loaded or was successfully loaded and compiled.
|
||||
Returns `false` otherwise.
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec can_await_module_compilation? :: boolean
|
||||
def can_await_module_compilation? do
|
||||
:erlang.process_info(self(), :error_handler) == {:error_handler, Kernel.ErrorHandler}
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use Code.ensure_compiled/1 instead (see the proper disclaimers in its docs)"
|
||||
@spec ensure_compiled?(module) :: boolean
|
||||
def ensure_compiled?(module) when is_atom(module) do
|
||||
match?({:module, ^module}, ensure_compiled(module))
|
||||
end
|
||||
@@ -1334,7 +1109,7 @@ defmodule Code do
|
||||
# Module documentation of an existing module
|
||||
iex> {:docs_v1, _, :elixir, _, %{"en" => module_doc}, _, _} = Code.fetch_docs(Atom)
|
||||
iex> module_doc |> String.split("\n") |> Enum.at(0)
|
||||
"Atoms are constants whose values are their own name."
|
||||
"Convenience functions for working with atoms."
|
||||
|
||||
# A module that doesn't exist
|
||||
iex> Code.fetch_docs(ModuleNotGood)
|
||||
@@ -1347,8 +1122,8 @@ defmodule Code do
|
||||
docs :: [doc_element]}
|
||||
| {:error, :module_not_found | :chunk_not_found | {:invalid_chunk, binary}}
|
||||
when annotation: :erl_anno.anno(),
|
||||
beam_language: :elixir | :erlang | atom(),
|
||||
doc_content: %{optional(binary) => binary} | :none | :hidden,
|
||||
beam_language: :elixir | :erlang | :lfe | :alpaca | atom(),
|
||||
doc_content: %{required(binary) => binary} | :none | :hidden,
|
||||
doc_element:
|
||||
{{kind :: atom, function_name :: atom, arity}, annotation, signature, doc_content,
|
||||
metadata},
|
||||
@@ -1359,73 +1134,31 @@ defmodule Code do
|
||||
|
||||
def fetch_docs(module) when is_atom(module) do
|
||||
case :code.get_object_code(module) do
|
||||
{_module, bin, beam_path} ->
|
||||
case fetch_docs_from_beam(bin) do
|
||||
{:error, :chunk_not_found} ->
|
||||
app_root = Path.expand(Path.join(["..", ".."]), beam_path)
|
||||
path = Path.join([app_root, "doc", "chunks", "#{module}.chunk"])
|
||||
fetch_docs_from_chunk(path)
|
||||
|
||||
other ->
|
||||
other
|
||||
end
|
||||
|
||||
:error ->
|
||||
case :code.which(module) do
|
||||
:preloaded ->
|
||||
# The erts directory is not necessarily included in releases
|
||||
# unless it is listed as an extra application.
|
||||
case :code.lib_dir(:erts) do
|
||||
path when is_list(path) ->
|
||||
path = Path.join([path, "doc", "chunks", "#{module}.chunk"])
|
||||
fetch_docs_from_chunk(path)
|
||||
|
||||
{:error, _} ->
|
||||
{:error, :chunk_not_found}
|
||||
end
|
||||
|
||||
_ ->
|
||||
{:error, :module_not_found}
|
||||
end
|
||||
{_module, bin, _beam_path} -> do_fetch_docs(bin)
|
||||
:error -> {:error, :module_not_found}
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_docs(path) when is_binary(path) do
|
||||
fetch_docs_from_beam(String.to_charlist(path))
|
||||
do_fetch_docs(String.to_charlist(path))
|
||||
end
|
||||
|
||||
@docs_chunk 'Docs'
|
||||
|
||||
defp fetch_docs_from_beam(bin_or_path) do
|
||||
defp do_fetch_docs(bin_or_path) do
|
||||
case :beam_lib.chunks(bin_or_path, [@docs_chunk]) do
|
||||
{:ok, {_module, [{@docs_chunk, bin}]}} ->
|
||||
load_docs_chunk(bin)
|
||||
try do
|
||||
:erlang.binary_to_term(bin)
|
||||
rescue
|
||||
_ -> {:error, {:invalid_chunk, bin}}
|
||||
end
|
||||
|
||||
{:error, :beam_lib, {:missing_chunk, _, @docs_chunk}} ->
|
||||
{:error, :chunk_not_found}
|
||||
|
||||
{:error, :beam_lib, {:file_error, _, :enoent}} ->
|
||||
{:error, :module_not_found}
|
||||
end
|
||||
end
|
||||
|
||||
defp fetch_docs_from_chunk(path) do
|
||||
case File.read(path) do
|
||||
{:ok, bin} ->
|
||||
load_docs_chunk(bin)
|
||||
|
||||
{:error, _} ->
|
||||
{:error, :chunk_not_found}
|
||||
end
|
||||
end
|
||||
|
||||
defp load_docs_chunk(bin) do
|
||||
:erlang.binary_to_term(bin)
|
||||
rescue
|
||||
_ ->
|
||||
{:error, {:invalid_chunk, bin}}
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Deprecated function to retrieve old documentation format.
|
||||
|
||||
@@ -1460,10 +1193,4 @@ defmodule Code do
|
||||
raise Code.LoadError, file: file
|
||||
end
|
||||
end
|
||||
|
||||
defp verify_loaded(loaded) do
|
||||
maps_binaries = Enum.map(loaded, fn {_module, map, binary} -> {map, binary} end)
|
||||
Module.ParallelChecker.verify(maps_binaries, [])
|
||||
Enum.map(loaded, fn {module, _map, binary} -> {module, binary} end)
|
||||
end
|
||||
end
|
||||
|
||||
+157
-190
@@ -42,8 +42,6 @@ defmodule Code.Formatter do
|
||||
:<~>,
|
||||
:<|>,
|
||||
:^^^,
|
||||
:+++,
|
||||
:---,
|
||||
:in,
|
||||
:++,
|
||||
:--,
|
||||
@@ -142,8 +140,8 @@ defmodule Code.Formatter do
|
||||
Checks if two strings are equivalent.
|
||||
"""
|
||||
def equivalent(string1, string2) when is_binary(string1) and is_binary(string2) do
|
||||
quoted1 = :elixir.string_to_quoted!(to_charlist(string1), 1, 1, "nofile", [])
|
||||
quoted2 = :elixir.string_to_quoted!(to_charlist(string2), 1, 1, "nofile", [])
|
||||
quoted1 = :elixir.string_to_quoted!(to_charlist(string1), 1, "nofile", [])
|
||||
quoted2 = :elixir.string_to_quoted!(to_charlist(string2), 1, "nofile", [])
|
||||
|
||||
case not_equivalent(quoted1, quoted2) do
|
||||
{left, right} -> {:error, left, right}
|
||||
@@ -207,13 +205,8 @@ defmodule Code.Formatter do
|
||||
warn_on_unnecessary_quotes: false
|
||||
]
|
||||
|
||||
parser_options = [
|
||||
literal_encoder: &{:ok, {:__block__, &2, [&1]}},
|
||||
token_metadata: true
|
||||
]
|
||||
|
||||
with {:ok, tokens} <- :elixir.string_to_tokens(charlist, line, 1, file, tokenizer_options),
|
||||
{:ok, forms} <- :elixir.tokens_to_quoted(tokens, file, parser_options) do
|
||||
with {:ok, tokens} <- :elixir.string_to_tokens(charlist, line, file, tokenizer_options),
|
||||
{:ok, forms} <- :elixir.tokens_to_quoted(tokens, file, formatter_metadata: true) do
|
||||
state =
|
||||
Process.get(:code_formatter_comments)
|
||||
|> Enum.reverse()
|
||||
@@ -239,8 +232,8 @@ defmodule Code.Formatter do
|
||||
{:ok, doc} ->
|
||||
doc
|
||||
|
||||
{:error, {location, error, token}} ->
|
||||
:elixir_errors.parse_error(location, Keyword.get(opts, :file, "nofile"), error, token)
|
||||
{:error, {line, error, token}} ->
|
||||
:elixir_errors.parse_error(line, Keyword.get(opts, :file, "nofile"), error, token)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -355,7 +348,7 @@ defmodule Code.Formatter do
|
||||
not interpolated?(entries) ->
|
||||
bitstring_to_algebra(meta, entries, state)
|
||||
|
||||
meta[:delimiter] == ~s["""] ->
|
||||
meta[:format] == :bin_heredoc ->
|
||||
{doc, state} =
|
||||
entries
|
||||
|> prepend_heredoc_line()
|
||||
@@ -377,7 +370,7 @@ defmodule Code.Formatter do
|
||||
not list_interpolated?(entries) ->
|
||||
remote_to_algebra(quoted, context, state)
|
||||
|
||||
meta[:delimiter] == ~s['''] ->
|
||||
meta[:format] == :list_heredoc ->
|
||||
{doc, state} =
|
||||
entries
|
||||
|> prepend_heredoc_line()
|
||||
@@ -435,12 +428,12 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({:__block__, meta, [list]}, _context, state) when is_list(list) do
|
||||
case meta[:delimiter] do
|
||||
~s['''] ->
|
||||
case meta[:format] do
|
||||
:list_heredoc ->
|
||||
string = list |> List.to_string() |> escape_heredoc()
|
||||
{@single_heredoc |> concat(string) |> concat(@single_heredoc) |> force_unfit(), state}
|
||||
|
||||
~s['] ->
|
||||
:charlist ->
|
||||
string = list |> List.to_string() |> escape_string(@single_quote)
|
||||
{@single_quote |> concat(string) |> concat(@single_quote), state}
|
||||
|
||||
@@ -450,7 +443,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({:__block__, meta, [string]}, _context, state) when is_binary(string) do
|
||||
if meta[:delimiter] == ~s["""] do
|
||||
if meta[:format] == :bin_heredoc do
|
||||
string = escape_heredoc(string)
|
||||
{@double_heredoc |> concat(string) |> concat(@double_heredoc) |> force_unfit(), state}
|
||||
else
|
||||
@@ -465,11 +458,11 @@ defmodule Code.Formatter do
|
||||
|
||||
defp quoted_to_algebra({:__block__, meta, [integer]}, _context, state)
|
||||
when is_integer(integer) do
|
||||
{integer_to_algebra(Keyword.fetch!(meta, :token)), state}
|
||||
{integer_to_algebra(Keyword.fetch!(meta, :original)), state}
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({:__block__, meta, [float]}, _context, state) when is_float(float) do
|
||||
{float_to_algebra(Keyword.fetch!(meta, :token)), state}
|
||||
{float_to_algebra(Keyword.fetch!(meta, :original)), state}
|
||||
end
|
||||
|
||||
defp quoted_to_algebra(
|
||||
@@ -485,12 +478,8 @@ defmodule Code.Formatter do
|
||||
quoted_to_algebra(arg, context, state)
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({:__block__, _meta, []}, _context, state) do
|
||||
{"nil", state}
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({:__block__, meta, _} = block, _context, state) do
|
||||
{block, state} = block_to_algebra(block, line(meta), closing_line(meta), state)
|
||||
{block, state} = block_to_algebra(block, line(meta), end_line(meta), state)
|
||||
{surround("(", block, ")"), state}
|
||||
end
|
||||
|
||||
@@ -524,7 +513,7 @@ defmodule Code.Formatter do
|
||||
defp quoted_to_algebra({:not, meta, [{:in, _, [left, right]} = arg]}, context, state) do
|
||||
%{rename_deprecated_at: since} = state
|
||||
|
||||
# TODO: Remove metadata and always rewrite to left not in right in Elixir v2.0.
|
||||
# TODO: Remove since check on Elixir v2.0 and the OP arrangement is removed.
|
||||
if meta[:operator] == :"not in" || (since && Version.match?(since, "~> 1.5")) do
|
||||
binary_op_to_algebra(:in, "not in", meta, left, right, context, state)
|
||||
else
|
||||
@@ -533,7 +522,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({:fn, meta, [_ | _] = clauses}, _context, state) do
|
||||
anon_fun_to_algebra(clauses, line(meta), closing_line(meta), state, eol?(meta))
|
||||
anon_fun_to_algebra(clauses, line(meta), end_line(meta), state, eol?(meta))
|
||||
end
|
||||
|
||||
defp quoted_to_algebra({fun, meta, args}, context, state) when is_atom(fun) and is_list(args) do
|
||||
@@ -617,14 +606,14 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp block_args_to_algebra(args, min_line, max_line, state) do
|
||||
quoted_to_algebra = fn {kind, meta, _} = arg, _args, state ->
|
||||
newlines = meta[:end_of_expression][:newlines] || 1
|
||||
quoted_to_algebra = fn {kind, meta, _} = arg, _args, doc_newlines, state ->
|
||||
doc_newlines = Keyword.get(meta, :newlines, doc_newlines)
|
||||
{doc, state} = quoted_to_algebra(arg, :block, state)
|
||||
{{doc, block_next_line(kind), newlines}, state}
|
||||
{doc, block_next_line(kind), doc_newlines, state}
|
||||
end
|
||||
|
||||
{args_docs, _comments?, state} =
|
||||
quoted_to_algebra_with_comments(args, [], min_line, max_line, state, quoted_to_algebra)
|
||||
quoted_to_algebra_with_comments(args, [], min_line, max_line, 2, state, quoted_to_algebra)
|
||||
|
||||
case args_docs do
|
||||
[] -> {@empty, state}
|
||||
@@ -679,11 +668,11 @@ defmodule Code.Formatter do
|
||||
|
||||
# There are five kinds of operators.
|
||||
#
|
||||
# 1. no space binary operators, for example, 1..2
|
||||
# 2. no newline binary operators, for example, left in right
|
||||
# 3. strict newlines before a left precedent operator, for example, foo |> bar |> baz
|
||||
# 4. strict newlines before a right precedent operator, for example, foo when bar when baz
|
||||
# 5. flex newlines after the operator, for example, foo ++ bar ++ baz
|
||||
# 1. no space binary operators, e.g. 1..2
|
||||
# 2. no newline binary operators, e.g. left in right
|
||||
# 3. strict newlines before a left precedent operator, e.g. foo |> bar |> baz
|
||||
# 4. strict newlines before a right precedent operator, e.g. foo when bar when baz
|
||||
# 5. flex newlines after the operator, e.g. foo ++ bar ++ baz
|
||||
#
|
||||
# Cases 1, 2 and 5 are handled fairly easily by relying on the
|
||||
# operator precedence and making sure nesting is applied only once.
|
||||
@@ -712,14 +701,14 @@ defmodule Code.Formatter do
|
||||
unwrap_right(right_arg, op, meta, right_context, [{{:root, left_context}, left_arg}])
|
||||
|
||||
operand_to_algebra = fn
|
||||
{{:root, context}, arg}, _args, state ->
|
||||
{{:root, context}, arg}, _args, newlines, state ->
|
||||
{doc, state} = binary_operand_to_algebra(arg, context, state, op, op_info, :left, 2)
|
||||
{{doc, @empty, 1}, state}
|
||||
{doc, @empty, newlines, state}
|
||||
|
||||
{{kind, context}, arg}, _args, state ->
|
||||
{{kind, context}, arg}, _args, newlines, state ->
|
||||
{doc, state} = binary_operand_to_algebra(arg, context, state, op, op_info, kind, 0)
|
||||
doc = doc |> nest_by_length(op_string) |> force_keyword(arg)
|
||||
{{concat(op_string, doc), @empty, 1}, state}
|
||||
{concat(op_string, doc), @empty, newlines, state}
|
||||
end
|
||||
|
||||
{doc, state} =
|
||||
@@ -750,15 +739,15 @@ defmodule Code.Formatter do
|
||||
unwrap_pipes(left_arg, meta, left_context, [{{op, right_context}, right_arg}])
|
||||
|
||||
operand_to_algebra = fn
|
||||
{{:root, context}, arg}, _args, state ->
|
||||
{{:root, context}, arg}, _args, newlines, state ->
|
||||
{doc, state} = binary_operand_to_algebra(arg, context, state, op, op_info, :left, 2)
|
||||
{{doc, @empty, 1}, state}
|
||||
{doc, @empty, newlines, state}
|
||||
|
||||
{{op, context}, arg}, _args, state ->
|
||||
{{op, context}, arg}, _args, newlines, state ->
|
||||
op_info = Code.Identifier.binary_op(op)
|
||||
op_string = Atom.to_string(op) <> " "
|
||||
{doc, state} = binary_operand_to_algebra(arg, context, state, op, op_info, :right, 0)
|
||||
{{concat(op_string, doc), @empty, 1}, state}
|
||||
{concat(op_string, doc), @empty, newlines, state}
|
||||
end
|
||||
|
||||
operand_to_algebra_with_comments(pipes, meta, min_line, max_line, state, operand_to_algebra)
|
||||
@@ -891,7 +880,7 @@ defmodule Code.Formatter do
|
||||
|
||||
defp operand_to_algebra_with_comments(operands, meta, min_line, max_line, state, fun) do
|
||||
{docs, comments?, state} =
|
||||
quoted_to_algebra_with_comments(operands, [], min_line, max_line, state, fun)
|
||||
quoted_to_algebra_with_comments(operands, [], min_line, max_line, 1, state, fun)
|
||||
|
||||
if comments? or eol?(meta) do
|
||||
{docs |> Enum.reduce(&line(&2, &1)) |> force_unfit(), state}
|
||||
@@ -911,11 +900,11 @@ defmodule Code.Formatter do
|
||||
|
||||
# @foo bar
|
||||
# @foo(bar)
|
||||
defp module_attribute_to_algebra(meta, {name, call_meta, [_] = args} = expr, context, state)
|
||||
defp module_attribute_to_algebra(meta, {name, _, [_] = args} = expr, context, state)
|
||||
when is_atom(name) and name not in [:__block__, :__aliases__] do
|
||||
if Code.Identifier.classify(name) == :callable_local do
|
||||
{{call_doc, state}, wrap_in_parens?} =
|
||||
call_args_to_algebra(args, call_meta, context, :skip_unless_many_args, false, state)
|
||||
call_args_to_algebra(args, meta, context, :skip_unless_many_args, false, state)
|
||||
|
||||
doc =
|
||||
"@#{name}"
|
||||
@@ -1006,7 +995,8 @@ defmodule Code.Formatter do
|
||||
fun = remote_fun_to_algebra(target, fun, length(args), state)
|
||||
remote_doc = target_doc |> concat(".") |> concat(string(fun))
|
||||
|
||||
if args == [] and not remote_target_is_a_module?(target) and not meta?(meta, :closing) do
|
||||
if args == [] and not remote_target_is_a_module?(target) and
|
||||
Keyword.get(meta, :no_parens, false) do
|
||||
{remote_doc, state}
|
||||
else
|
||||
{{call_doc, state}, wrap_in_parens?} =
|
||||
@@ -1085,7 +1075,7 @@ defmodule Code.Formatter do
|
||||
defp local_to_algebra(fun, meta, args, context, state) when is_atom(fun) do
|
||||
skip_parens =
|
||||
cond do
|
||||
meta?(meta, :closing) -> :skip_if_only_do_end
|
||||
not Keyword.get(meta, :no_parens, false) -> :skip_if_only_do_end
|
||||
local_without_parens?(fun, args, state) -> :skip_unless_many_args
|
||||
true -> :skip_if_do_end
|
||||
end
|
||||
@@ -1120,7 +1110,7 @@ defmodule Code.Formatter do
|
||||
defp call_args_to_algebra(args, meta, context, parens, list_to_keyword?, state) do
|
||||
{rest, last} = split_last(args)
|
||||
|
||||
if blocks = do_end_blocks(meta, last, state) do
|
||||
if blocks = do_end_blocks(last, state) do
|
||||
{call_doc, state} =
|
||||
case rest do
|
||||
[] when parens == :required ->
|
||||
@@ -1151,7 +1141,7 @@ defmodule Code.Formatter do
|
||||
|
||||
defp call_args_to_algebra_no_blocks(meta, args, skip_parens?, list_to_keyword?, extra, state) do
|
||||
{left, right} = split_last(args)
|
||||
{keyword?, right} = last_arg_to_keyword(right, list_to_keyword?, skip_parens?, state.comments)
|
||||
{keyword?, right} = last_arg_to_keyword(right, list_to_keyword?)
|
||||
|
||||
context =
|
||||
if left == [] and not keyword? do
|
||||
@@ -1279,15 +1269,15 @@ defmodule Code.Formatter do
|
||||
not Enum.any?(args, &match?({:<-, _, [_, _]}, &1))
|
||||
end
|
||||
|
||||
defp do_end_blocks(meta, [{{:__block__, _, [:do]}, _} | rest] = blocks, state) do
|
||||
if meta?(meta, :do) or can_force_do_end_blocks?(rest, state) do
|
||||
defp do_end_blocks([{{:__block__, meta, [:do]}, _} | rest] = blocks, state) do
|
||||
if meta[:format] == :block or can_force_do_end_blocks?(rest, state) do
|
||||
blocks
|
||||
|> Enum.map(fn {{:__block__, meta, [key]}, value} -> {key, line(meta), value} end)
|
||||
|> do_end_blocks_with_range(end_line(meta))
|
||||
end
|
||||
end
|
||||
|
||||
defp do_end_blocks(_, _, _), do: nil
|
||||
defp do_end_blocks(_, _), do: nil
|
||||
|
||||
defp can_force_do_end_blocks?(rest, state) do
|
||||
state.force_do_end_blocks and
|
||||
@@ -1352,7 +1342,7 @@ defmodule Code.Formatter do
|
||||
|
||||
defp list_interpolation_to_algebra([entry | entries], escape, state, acc, last) do
|
||||
{{:., _, [Kernel, :to_string]}, meta, [quoted]} = entry
|
||||
{doc, state} = block_to_algebra(quoted, line(meta), closing_line(meta), state)
|
||||
{doc, state} = block_to_algebra(quoted, line(meta), end_line(meta), state)
|
||||
doc = surround("\#{", doc, "}")
|
||||
list_interpolation_to_algebra(entries, escape, state, concat(acc, doc), last)
|
||||
end
|
||||
@@ -1369,7 +1359,7 @@ defmodule Code.Formatter do
|
||||
|
||||
defp interpolation_to_algebra([entry | entries], escape, state, acc, last) do
|
||||
{:"::", _, [{{:., _, [Kernel, :to_string]}, meta, [quoted]}, {:binary, _, _}]} = entry
|
||||
{doc, state} = block_to_algebra(quoted, line(meta), closing_line(meta), state)
|
||||
{doc, state} = block_to_algebra(quoted, line(meta), end_line(meta), state)
|
||||
doc = surround("\#{", doc, "}")
|
||||
interpolation_to_algebra(entries, escape, state, concat(acc, doc), last)
|
||||
end
|
||||
@@ -1383,22 +1373,22 @@ defmodule Code.Formatter do
|
||||
defp maybe_sigil_to_algebra(fun, meta, args, state) do
|
||||
with <<"sigil_", name>> <- Atom.to_string(fun),
|
||||
[{:<<>>, _, entries}, modifiers] when is_list(modifiers) <- args,
|
||||
opening_delimiter when not is_nil(opening_delimiter) <- meta[:delimiter] do
|
||||
doc = <<?~, name, opening_delimiter::binary>>
|
||||
opening_terminator when not is_nil(opening_terminator) <- Keyword.get(meta, :terminator) do
|
||||
doc = <<?~, name, opening_terminator::binary>>
|
||||
|
||||
if opening_delimiter in [@double_heredoc, @single_heredoc] do
|
||||
closing_delimiter = concat(opening_delimiter, List.to_string(modifiers))
|
||||
if opening_terminator in [@double_heredoc, @single_heredoc] do
|
||||
closing_terminator = concat(opening_terminator, List.to_string(modifiers))
|
||||
|
||||
{doc, state} =
|
||||
entries
|
||||
|> prepend_heredoc_line()
|
||||
|> interpolation_to_algebra(:heredoc, state, doc, closing_delimiter)
|
||||
|> interpolation_to_algebra(:heredoc, state, doc, closing_terminator)
|
||||
|
||||
{force_unfit(doc), state}
|
||||
else
|
||||
escape = closing_sigil_delimiter(opening_delimiter)
|
||||
closing_delimiter = concat(escape, List.to_string(modifiers))
|
||||
interpolation_to_algebra(entries, escape, state, doc, closing_delimiter)
|
||||
escape = closing_sigil_terminator(opening_terminator)
|
||||
closing_terminator = concat(escape, List.to_string(modifiers))
|
||||
interpolation_to_algebra(entries, escape, state, doc, closing_terminator)
|
||||
end
|
||||
else
|
||||
_ ->
|
||||
@@ -1406,11 +1396,11 @@ defmodule Code.Formatter do
|
||||
end
|
||||
end
|
||||
|
||||
defp closing_sigil_delimiter("("), do: ")"
|
||||
defp closing_sigil_delimiter("["), do: "]"
|
||||
defp closing_sigil_delimiter("{"), do: "}"
|
||||
defp closing_sigil_delimiter("<"), do: ">"
|
||||
defp closing_sigil_delimiter(other) when other in ["\"", "'", "|", "/"], do: other
|
||||
defp closing_sigil_terminator("("), do: ")"
|
||||
defp closing_sigil_terminator("["), do: "]"
|
||||
defp closing_sigil_terminator("{"), do: "}"
|
||||
defp closing_sigil_terminator("<"), do: ">"
|
||||
defp closing_sigil_terminator(other) when other in ["\"", "'", "|", "/"], do: other
|
||||
|
||||
## Bitstrings
|
||||
|
||||
@@ -1556,40 +1546,43 @@ defmodule Code.Formatter do
|
||||
|
||||
defp integer_to_algebra(text) do
|
||||
case text do
|
||||
<<?0, ?x, rest::binary>> ->
|
||||
"0x" <> String.upcase(rest)
|
||||
[?0, ?x | rest] ->
|
||||
"0x" <> String.upcase(List.to_string(rest))
|
||||
|
||||
<<?0, base, _::binary>> = digits when base in [?b, ?o] ->
|
||||
digits
|
||||
[?0, base | _rest] = digits when base in [?b, ?o] ->
|
||||
List.to_string(digits)
|
||||
|
||||
<<??, _::binary>> = char ->
|
||||
char
|
||||
[?? | _rest] = char ->
|
||||
List.to_string(char)
|
||||
|
||||
decimal ->
|
||||
insert_underscores(decimal)
|
||||
List.to_string(insert_underscores(decimal))
|
||||
end
|
||||
end
|
||||
|
||||
defp float_to_algebra(text) do
|
||||
[int_part, decimal_part] = :binary.split(text, ".")
|
||||
decimal_part = String.downcase(decimal_part)
|
||||
insert_underscores(int_part) <> "." <> decimal_part
|
||||
{int_part, [?. | decimal_part]} = Enum.split_while(text, &(&1 != ?.))
|
||||
|
||||
decimal_part =
|
||||
decimal_part
|
||||
|> List.to_string()
|
||||
|> String.downcase()
|
||||
|
||||
List.to_string(insert_underscores(int_part)) <> "." <> decimal_part
|
||||
end
|
||||
|
||||
defp insert_underscores(digits) do
|
||||
cond do
|
||||
digits =~ "_" ->
|
||||
?_ in digits ->
|
||||
digits
|
||||
|
||||
byte_size(digits) >= 6 ->
|
||||
length(digits) >= 6 ->
|
||||
digits
|
||||
|> String.to_charlist()
|
||||
|> Enum.reverse()
|
||||
|> Enum.chunk_every(3)
|
||||
|> Enum.intersperse('_')
|
||||
|> List.flatten()
|
||||
|> Enum.reverse()
|
||||
|> List.to_string()
|
||||
|
||||
true ->
|
||||
digits
|
||||
@@ -1635,9 +1628,9 @@ defmodule Code.Formatter do
|
||||
|
||||
defp args_to_algebra_with_comments(args, meta, skip_parens?, last_arg_mode, join, state, fun) do
|
||||
min_line = line(meta)
|
||||
max_line = closing_line(meta)
|
||||
max_line = end_line(meta)
|
||||
|
||||
arg_to_algebra = fn arg, args, state ->
|
||||
arg_to_algebra = fn arg, args, newlines, state ->
|
||||
{doc, state} = fun.(arg, state)
|
||||
|
||||
doc =
|
||||
@@ -1648,7 +1641,7 @@ defmodule Code.Formatter do
|
||||
[] when last_arg_mode == :none -> doc
|
||||
end
|
||||
|
||||
{{doc, @empty, 1}, state}
|
||||
{doc, @empty, newlines, state}
|
||||
end
|
||||
|
||||
# If skipping parens, we cannot extract the comments of the first
|
||||
@@ -1656,15 +1649,15 @@ defmodule Code.Formatter do
|
||||
{args, acc, state} =
|
||||
case args do
|
||||
[head | tail] when skip_parens? ->
|
||||
{doc_triplet, state} = arg_to_algebra.(head, tail, state)
|
||||
{tail, [doc_triplet], state}
|
||||
{head, next_line, newlines, state} = arg_to_algebra.(head, tail, 1, state)
|
||||
{tail, [{head, next_line, newlines}], state}
|
||||
|
||||
_ ->
|
||||
{args, [], state}
|
||||
end
|
||||
|
||||
{args_docs, comments?, state} =
|
||||
quoted_to_algebra_with_comments(args, acc, min_line, max_line, state, arg_to_algebra)
|
||||
quoted_to_algebra_with_comments(args, acc, min_line, max_line, 1, state, arg_to_algebra)
|
||||
|
||||
cond do
|
||||
args_docs == [] ->
|
||||
@@ -1836,7 +1829,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp clause_to_algebra({:->, meta, [[], body]}, _min_line, state) do
|
||||
{body_doc, state} = block_to_algebra(body, line(meta), closing_line(meta), state)
|
||||
{body_doc, state} = block_to_algebra(body, line(meta), end_line(meta), state)
|
||||
{"() ->" |> glue(body_doc) |> nest(2), state}
|
||||
end
|
||||
|
||||
@@ -1847,7 +1840,7 @@ defmodule Code.Formatter do
|
||||
{args_doc, state} = clause_args_to_algebra(args, min_line, state)
|
||||
|
||||
state = %{state | operand_nesting: nesting}
|
||||
{body_doc, state} = block_to_algebra(body, min_line, closing_line(meta), state)
|
||||
{body_doc, state} = block_to_algebra(body, min_line, end_line(meta), state)
|
||||
|
||||
doc =
|
||||
args_doc
|
||||
@@ -1868,13 +1861,13 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp clause_args_to_algebra(args, min_line, state) do
|
||||
arg_to_algebra = fn arg, _args, state ->
|
||||
arg_to_algebra = fn arg, _args, newlines, state ->
|
||||
{doc, state} = clause_args_to_algebra(arg, state)
|
||||
{{doc, @empty, 1}, state}
|
||||
{doc, @empty, newlines, state}
|
||||
end
|
||||
|
||||
{args_docs, comments?, state} =
|
||||
quoted_to_algebra_with_comments([args], [], min_line, @min_line, state, arg_to_algebra)
|
||||
quoted_to_algebra_with_comments([args], [], min_line, @min_line, 1, state, arg_to_algebra)
|
||||
|
||||
if comments? do
|
||||
{Enum.reduce(args_docs, &line(&2, &1)), state}
|
||||
@@ -1902,75 +1895,65 @@ defmodule Code.Formatter do
|
||||
|
||||
## Quoted helpers for comments
|
||||
|
||||
defp quoted_to_algebra_with_comments(args, acc, min_line, max_line, state, fun) do
|
||||
defp quoted_to_algebra_with_comments(args, acc, min_line, max_line, newlines, state, fun) do
|
||||
{pre_comments, state} =
|
||||
get_and_update_in(state.comments, fn comments ->
|
||||
Enum.split_while(comments, fn {line, _, _} -> line <= min_line end)
|
||||
end)
|
||||
|
||||
{docs, comments?, state} =
|
||||
each_quoted_to_algebra_with_comments(args, acc, max_line, state, false, fun)
|
||||
each_quoted_to_algebra_with_comments(args, acc, max_line, newlines, state, false, fun)
|
||||
|
||||
{docs, comments?, update_in(state.comments, &(pre_comments ++ &1))}
|
||||
end
|
||||
|
||||
defp each_quoted_to_algebra_with_comments([], acc, max_line, state, comments?, _fun) do
|
||||
{acc, comments, comments?} = extract_comments_before(max_line, acc, state.comments, comments?)
|
||||
args_docs = merge_algebra_with_comments(Enum.reverse(acc), @empty)
|
||||
{args_docs, comments?, %{state | comments: comments}}
|
||||
defp each_quoted_to_algebra_with_comments([], acc, max_line, _newlines, state, comments?, _fun) do
|
||||
%{comments: comments} = state
|
||||
{current, comments} = Enum.split_with(comments, fn {line, _, _} -> line < max_line end)
|
||||
|
||||
extra = for {_, {previous, _}, doc} <- current, do: {doc, @empty, previous}
|
||||
args_docs = merge_algebra_with_comments(Enum.reverse(acc, extra), @empty)
|
||||
{args_docs, comments? or extra != [], %{state | comments: comments}}
|
||||
end
|
||||
|
||||
defp each_quoted_to_algebra_with_comments([arg | args], acc, max_line, state, comments?, fun) do
|
||||
defp each_quoted_to_algebra_with_comments(args, acc, max_line, newlines, state, comments?, fun) do
|
||||
[arg | args] = args
|
||||
{doc_start, doc_end} = traverse_line(arg, {@max_line, @min_line})
|
||||
|
||||
{acc, comments, comments?} =
|
||||
extract_comments_before(doc_start, acc, state.comments, comments?)
|
||||
{doc_newlines, acc, comments, comments?} =
|
||||
extract_comments_before(doc_start, newlines, acc, state.comments, comments?)
|
||||
|
||||
{doc_triplet, state} = fun.(arg, args, %{state | comments: comments})
|
||||
{doc, next_line, doc_newlines, state} =
|
||||
fun.(arg, args, doc_newlines, %{state | comments: comments})
|
||||
|
||||
{acc, comments, comments?} =
|
||||
extract_comments_trailing(doc_start, doc_end, acc, state.comments, comments?)
|
||||
{doc_newlines, acc, comments, comments?} =
|
||||
extract_comments_trailing(doc_start, doc_end, doc_newlines, acc, state.comments, comments?)
|
||||
|
||||
acc = [adjust_trailing_newlines(doc_triplet, doc_end, comments) | acc]
|
||||
acc = [{doc, next_line, doc_newlines} | acc]
|
||||
state = %{state | comments: comments}
|
||||
each_quoted_to_algebra_with_comments(args, acc, max_line, state, comments?, fun)
|
||||
each_quoted_to_algebra_with_comments(args, acc, max_line, newlines, state, comments?, fun)
|
||||
end
|
||||
|
||||
defp extract_comments_before(max, acc, [{line, _, _} = comment | rest], _) when line < max do
|
||||
defp extract_comments_before(max, _, acc, [{line, _, _} = comment | rest], _) when line < max do
|
||||
{_, {previous, next}, doc} = comment
|
||||
acc = [{doc, @empty, next} | add_previous_to_acc(acc, previous)]
|
||||
extract_comments_before(max, acc, rest, true)
|
||||
acc = [{doc, @empty, previous} | acc]
|
||||
extract_comments_before(max, next, acc, rest, true)
|
||||
end
|
||||
|
||||
defp extract_comments_before(_max, acc, rest, comments?) do
|
||||
{acc, rest, comments?}
|
||||
defp extract_comments_before(_max, newlines, acc, rest, comments?) do
|
||||
{newlines, acc, rest, comments?}
|
||||
end
|
||||
|
||||
defp add_previous_to_acc([{doc, next_line, newlines} | acc], previous) when newlines < previous,
|
||||
do: [{doc, next_line, previous} | acc]
|
||||
|
||||
defp add_previous_to_acc(acc, _previous),
|
||||
do: acc
|
||||
|
||||
defp extract_comments_trailing(min, max, acc, [{line, _, doc_comment} | rest], _)
|
||||
defp extract_comments_trailing(min, max, newlines, acc, [{line, _, doc_comment} | rest], _)
|
||||
when line >= min and line <= max do
|
||||
acc = [{doc_comment, @empty, 1} | acc]
|
||||
extract_comments_trailing(min, max, acc, rest, true)
|
||||
acc = [{doc_comment, @empty, newlines} | acc]
|
||||
extract_comments_trailing(min, max, 1, acc, rest, true)
|
||||
end
|
||||
|
||||
defp extract_comments_trailing(_min, _max, acc, rest, comments?) do
|
||||
{acc, rest, comments?}
|
||||
defp extract_comments_trailing(_min, _max, newlines, acc, rest, comments?) do
|
||||
{newlines, acc, rest, comments?}
|
||||
end
|
||||
|
||||
# If the document is immediately followed by comment which is followed by newlines,
|
||||
# its newlines wouldn't have considered the comment, so we need to adjust it.
|
||||
defp adjust_trailing_newlines({doc, next_line, newlines}, doc_end, [{line, _, _} | _])
|
||||
when newlines > 1 and line == doc_end + 1 do
|
||||
{doc, next_line, 1}
|
||||
end
|
||||
|
||||
defp adjust_trailing_newlines(doc_triplet, _, _), do: doc_triplet
|
||||
|
||||
defp traverse_line({expr, meta, args}, {min, max}) do
|
||||
acc =
|
||||
case Keyword.fetch(meta, :line) do
|
||||
@@ -2000,8 +1983,8 @@ defmodule Code.Formatter do
|
||||
# (except for module attributes)
|
||||
# 3. empty lines are collapsed as to not exceed more than one
|
||||
#
|
||||
defp merge_algebra_with_comments([{doc, next_line, newlines} | docs], left) do
|
||||
right = if newlines >= @newlines, do: line(), else: next_line
|
||||
defp merge_algebra_with_comments([{doc, next_line, _newlines} | docs], left) do
|
||||
right = next_line_separator(docs, next_line)
|
||||
|
||||
doc =
|
||||
if left != @empty do
|
||||
@@ -2082,6 +2065,14 @@ defmodule Code.Formatter do
|
||||
end)
|
||||
end
|
||||
|
||||
defp next_line_separator([{_doc, _next_line, newlines} | _], next_line) do
|
||||
if newlines >= @newlines, do: line(), else: next_line
|
||||
end
|
||||
|
||||
defp next_line_separator([], _) do
|
||||
line()
|
||||
end
|
||||
|
||||
defp module_attribute_read?({:@, _, [{var, _, var_context}]})
|
||||
when is_atom(var) and is_atom(var_context) do
|
||||
Code.Identifier.classify(var) == :callable_local
|
||||
@@ -2136,12 +2127,12 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp next_break_fits?({:<<>>, meta, [_ | _] = entries}, state) do
|
||||
meta[:delimiter] == ~s["""] or
|
||||
meta[:format] == :bin_heredoc or
|
||||
(not interpolated?(entries) and eol_or_comments?(meta, state))
|
||||
end
|
||||
|
||||
defp next_break_fits?({{:., _, [List, :to_charlist]}, meta, [[_ | _]]}, _state) do
|
||||
meta[:delimiter] == ~s[''']
|
||||
meta[:format] == :list_heredoc
|
||||
end
|
||||
|
||||
defp next_break_fits?({{:., _, [_left, :{}]}, _, _}, _state) do
|
||||
@@ -2149,11 +2140,11 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp next_break_fits?({:__block__, meta, [string]}, _state) when is_binary(string) do
|
||||
meta[:delimiter] == ~s["""]
|
||||
meta[:format] == :bin_heredoc
|
||||
end
|
||||
|
||||
defp next_break_fits?({:__block__, meta, [list]}, _state) when is_list(list) do
|
||||
meta[:delimiter] != ~s[']
|
||||
meta[:format] != :charlist
|
||||
end
|
||||
|
||||
defp next_break_fits?({form, _, [_ | _]}, _state) when form in [:fn, :%{}, :%] do
|
||||
@@ -2161,7 +2152,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp next_break_fits?({fun, meta, args}, _state) when is_atom(fun) and is_list(args) do
|
||||
meta[:delimiter] in [@double_heredoc, @single_heredoc] and
|
||||
meta[:terminator] in [@double_heredoc, @single_heredoc] and
|
||||
fun |> Atom.to_string() |> String.starts_with?("sigil_")
|
||||
end
|
||||
|
||||
@@ -2177,47 +2168,23 @@ defmodule Code.Formatter do
|
||||
eol?(meta) or
|
||||
(
|
||||
min_line = line(meta)
|
||||
max_line = closing_line(meta)
|
||||
max_line = end_line(meta)
|
||||
Enum.any?(comments, fn {line, _, _} -> line > min_line and line < max_line end)
|
||||
)
|
||||
end
|
||||
|
||||
# A literal list is a keyword or (... -> ...)
|
||||
defp last_arg_to_keyword([_ | _] = arg, _list_to_keyword?, _skip_parens?, _comments) do
|
||||
defp last_arg_to_keyword([_ | _] = arg, _list_to_keyword?) do
|
||||
{keyword?(arg), arg}
|
||||
end
|
||||
|
||||
# This is a list of tuples, it can be converted to keywords.
|
||||
defp last_arg_to_keyword(
|
||||
{:__block__, meta, [[_ | _] = arg]} = block,
|
||||
true,
|
||||
skip_parens?,
|
||||
comments
|
||||
) do
|
||||
cond do
|
||||
not keyword?(arg) ->
|
||||
{false, block}
|
||||
|
||||
skip_parens? ->
|
||||
block_line = line(meta)
|
||||
{{_, arg_meta, _}, _} = hd(arg)
|
||||
first_line = line(arg_meta)
|
||||
|
||||
case Enum.drop_while(comments, fn {line, _, _} -> line <= block_line end) do
|
||||
[{line, _, _} | _] when line <= first_line ->
|
||||
{false, block}
|
||||
|
||||
_ ->
|
||||
{true, arg}
|
||||
end
|
||||
|
||||
true ->
|
||||
{true, arg}
|
||||
end
|
||||
defp last_arg_to_keyword({:__block__, _, [[_ | _] = arg]} = block, true) do
|
||||
if keyword?(arg), do: {true, arg}, else: {false, block}
|
||||
end
|
||||
|
||||
# Otherwise we don't have a keyword.
|
||||
defp last_arg_to_keyword(arg, _list_to_keyword?, _skip_parens?, _comments) do
|
||||
defp last_arg_to_keyword(arg, _list_to_keyword?) do
|
||||
{false, arg}
|
||||
end
|
||||
|
||||
@@ -2249,24 +2216,28 @@ defmodule Code.Formatter do
|
||||
if force_args?(arg), do: force_unfit(doc), else: doc
|
||||
end
|
||||
|
||||
defp keyword?([{_, _} | list]), do: keyword?(list)
|
||||
defp keyword?(rest), do: rest == []
|
||||
|
||||
defp keyword_key?({:__block__, meta, [atom]}) when is_atom(atom),
|
||||
do: meta[:format] == :keyword
|
||||
|
||||
defp keyword_key?({{:., _, [:erlang, :binary_to_atom]}, meta, [{:<<>>, _, _}, :utf8]}),
|
||||
do: meta[:format] == :keyword
|
||||
|
||||
defp keyword_key?(_),
|
||||
do: false
|
||||
|
||||
defp eol?(meta) do
|
||||
Keyword.get(meta, :newlines, 0) > 0
|
||||
defp keyword?([{key, _} | list]) do
|
||||
keyword_key?(key) and keyword?(list)
|
||||
end
|
||||
|
||||
defp meta?(meta, key) do
|
||||
is_list(meta[key])
|
||||
defp keyword?(rest) do
|
||||
rest == []
|
||||
end
|
||||
|
||||
defp keyword_key?({:__block__, meta, [_]}) do
|
||||
meta[:format] == :keyword
|
||||
end
|
||||
|
||||
defp keyword_key?({{:., _, [:erlang, :binary_to_atom]}, _, [{:<<>>, meta, _}, :utf8]}) do
|
||||
meta[:format] == :keyword
|
||||
end
|
||||
|
||||
defp keyword_key?(_) do
|
||||
false
|
||||
end
|
||||
|
||||
defp eol?(meta) do
|
||||
Keyword.get(meta, :eol, false)
|
||||
end
|
||||
|
||||
defp line(meta) do
|
||||
@@ -2274,10 +2245,6 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp end_line(meta) do
|
||||
meta[:end][:line] || @min_line
|
||||
end
|
||||
|
||||
defp closing_line(meta) do
|
||||
meta[:closing][:line] || @min_line
|
||||
end
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ defmodule Code.Identifier do
|
||||
op in [:|>, :<<<, :>>>, :<~, :~>, :<<~, :~>>, :<~>, :<|>] -> {:left, 170}
|
||||
op in [:in] -> {:left, 180}
|
||||
op in [:^^^] -> {:left, 190}
|
||||
op in [:++, :--, :.., :<>, :+++, :---] -> {:right, 200}
|
||||
op in [:++, :--, :.., :<>] -> {:right, 200}
|
||||
op in [:+, :-] -> {:left, 210}
|
||||
op in [:*, :/] -> {:left, 220}
|
||||
op in [:.] -> {:left, 310}
|
||||
|
||||
@@ -217,8 +217,7 @@ defmodule Code.Typespec do
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:user_type, line, name, args}) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
{name, [line: line], args}
|
||||
typespec_to_quoted({:type, line, name, args})
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, line, :tuple, :any}) do
|
||||
@@ -273,13 +272,13 @@ defmodule Code.Typespec do
|
||||
{{:optional, [], [typespec_to_quoted(k)]}, typespec_to_quoted(v)}
|
||||
end)
|
||||
|
||||
case List.keytake(fields, :__struct__, 0) do
|
||||
{{:__struct__, struct}, fields_pruned} when is_atom(struct) and struct != nil ->
|
||||
map_pruned = {:%{}, [line: line], fields_pruned}
|
||||
{:%, [line: line], [struct, map_pruned]}
|
||||
{struct, fields} = Keyword.pop(fields, :__struct__)
|
||||
map = {:%{}, [line: line], fields}
|
||||
|
||||
_ ->
|
||||
{:%{}, [line: line], fields}
|
||||
if struct do
|
||||
{:%, [line: line], [struct, map]}
|
||||
else
|
||||
map
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ defprotocol Collectable do
|
||||
iex> collector_fun.(updated_acc, :done)
|
||||
#MapSet<[1, 2, 3]>
|
||||
|
||||
To show how the protocol can be implemented, we can again look at the
|
||||
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`.
|
||||
|
||||
@@ -143,7 +143,7 @@ end
|
||||
defimpl Collectable, for: Map do
|
||||
def into(original) do
|
||||
fun = fn
|
||||
map, {:cont, {k, v}} -> Map.put(map, k, v)
|
||||
map, {:cont, {k, v}} -> :maps.put(k, v, map)
|
||||
map, :done -> map
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
+54
-116
@@ -13,7 +13,7 @@ defmodule Config do
|
||||
key1: "value1",
|
||||
key2: "value2"
|
||||
|
||||
import_config "#{config_env()}.exs"
|
||||
import_config "#{Mix.env()}.exs"
|
||||
|
||||
`import Config` will import the functions `config/2`, `config/3`
|
||||
and `import_config/1` to help you manage your configuration.
|
||||
@@ -26,9 +26,9 @@ defmodule Config do
|
||||
|
||||
"value1" = Application.fetch_env!(:some_app, :key1)
|
||||
|
||||
Finally, the line `import_config "#{config_env()}.exs"` will import
|
||||
other config files based on the current configuration environment,
|
||||
such as `config/dev.exs` and `config/test.exs`.
|
||||
Finally, the line `import_config "#{Mix.env()}.exs"` will import other
|
||||
config files, based on the current Mix environment, such as
|
||||
`config/dev.exs` and `config/test.exs`.
|
||||
|
||||
`Config` also provides a low-level API for evaluating and reading
|
||||
configuration, under the `Config.Reader` module.
|
||||
@@ -36,14 +36,14 @@ defmodule Config do
|
||||
**Important:** if you are writing a library to be used by other developers,
|
||||
it is generally recommended to avoid the application environment, as the
|
||||
application environment is effectively a global storage. For more information,
|
||||
read our [library guidelines](library-guidelines.md).
|
||||
read our [library guidelines](library-guidelines.html).
|
||||
|
||||
## Migrating from `use Mix.Config`
|
||||
|
||||
The `Config` module in Elixir was introduced in v1.9 as a replacement to
|
||||
`Mix.Config`, which was specific to Mix and has been deprecated.
|
||||
|
||||
You can leverage `Config` instead of `Mix.Config` in three steps. The first
|
||||
You can leverage `Config` instead of `Mix.Config` in two steps. The first
|
||||
step is to replace `use Mix.Config` at the top of your config files by
|
||||
`import Config`.
|
||||
|
||||
@@ -59,30 +59,43 @@ defmodule Config do
|
||||
import_config config
|
||||
end
|
||||
|
||||
The last step is to replace all `Mix.env()` calls by `config_env()`.
|
||||
## config/releases.exs
|
||||
|
||||
## config/runtime.exs
|
||||
|
||||
For runtime configuration, you can use the `config/runtime.exs` file.
|
||||
It is executed right before applications start in both Mix and releases
|
||||
(assembled with `mix release`).
|
||||
If you are using releases, see `mix release`, there another configuration
|
||||
file called `config/releases.exs`. While `config/config.exs` and friends
|
||||
mentioned in the previous section are executed whenever you run a Mix
|
||||
command, including when you assemble a release, `config/releases.exs` is
|
||||
execute every time your production system boots. Since Mix is not available
|
||||
in a production system, `config/releases.exs` must not use any of the
|
||||
functions from Mix.
|
||||
"""
|
||||
|
||||
@opts_key {__MODULE__, :opts}
|
||||
@config_key {__MODULE__, :config}
|
||||
@imports_key {__MODULE__, :imports}
|
||||
@files_key {__MODULE__, :files}
|
||||
|
||||
defp get_opts!(), do: Process.get(@opts_key)
|
||||
defp put_opts(value), do: Process.put(@opts_key, value)
|
||||
defp delete_opts(), do: Process.delete(@opts_key)
|
||||
defp get_config!() do
|
||||
Process.get(@config_key) || raise_improper_use!()
|
||||
end
|
||||
|
||||
defp get_config!(), do: Process.get(@config_key) || raise_improper_use!()
|
||||
defp put_config(value), do: Process.put(@config_key, value)
|
||||
defp delete_config(), do: Process.delete(@config_key)
|
||||
defp put_config(value) do
|
||||
Process.put(@config_key, value)
|
||||
end
|
||||
|
||||
defp get_imports!(), do: Process.get(@imports_key) || raise_improper_use!()
|
||||
defp put_imports(value), do: Process.put(@imports_key, value)
|
||||
defp delete_imports(), do: Process.delete(@imports_key)
|
||||
defp delete_config() do
|
||||
Process.delete(@config_key)
|
||||
end
|
||||
|
||||
defp get_files!() do
|
||||
Process.get(@files_key) || raise_improper_use!()
|
||||
end
|
||||
|
||||
defp put_files(value) do
|
||||
Process.put(@files_key, value)
|
||||
end
|
||||
|
||||
defp delete_files() do
|
||||
Process.delete(@files_key)
|
||||
end
|
||||
|
||||
defp raise_improper_use!() do
|
||||
raise "could not set configuration via Config. " <>
|
||||
@@ -159,55 +172,6 @@ defmodule Config do
|
||||
|> put_config()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the environment this configuration file is executed on.
|
||||
|
||||
In Mix projects this function returns the environment this configuration
|
||||
file is executed on. In releases, the environment when `mix release` ran.
|
||||
|
||||
This is most often used to execute conditional code:
|
||||
|
||||
if config_env() == :prod do
|
||||
config :my_app, :debug, false
|
||||
end
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
defmacro config_env() do
|
||||
quote do
|
||||
Config.__env__!()
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec __env__!() :: atom()
|
||||
def __env__!() do
|
||||
elem(get_opts!(), 0) || raise "no :env key was given to this configuration file"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the target this configuration file is executed on.
|
||||
|
||||
This is most often used to execute conditional code:
|
||||
|
||||
if config_target() == :host do
|
||||
config :my_app, :debug, false
|
||||
end
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
defmacro config_target() do
|
||||
quote do
|
||||
Config.__target__!()
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec __target__!() :: atom()
|
||||
def __target__!() do
|
||||
elem(get_opts!(), 1) || raise "no :target key was given to this configuration file"
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Imports configuration from the given file.
|
||||
|
||||
@@ -220,11 +184,8 @@ defmodule Config do
|
||||
|
||||
This is often used to emulate configuration across environments:
|
||||
|
||||
import_config "#{config_env()}.exs"
|
||||
import_config "#{Mix.env()}.exs"
|
||||
|
||||
Note, however, some configuration files, such as `config/runtime.exs`
|
||||
does not support imports, as they are meant to be copied across
|
||||
systems.
|
||||
"""
|
||||
@doc since: "1.9.0"
|
||||
defmacro import_config(file) do
|
||||
@@ -235,64 +196,41 @@ defmodule Config do
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec __import__!(Path.t()) :: {term, Code.binding()}
|
||||
@spec __import__!(Path.t()) :: keyword()
|
||||
def __import__!(file) when is_binary(file) do
|
||||
import_config!(file, File.read!(file), true)
|
||||
current_files = get_files!()
|
||||
|
||||
if file in current_files do
|
||||
raise ArgumentError,
|
||||
"attempting to load configuration #{Path.relative_to_cwd(file)} recursively"
|
||||
end
|
||||
|
||||
put_files([file | current_files])
|
||||
Code.eval_file(file)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec __eval__!(Path.t(), binary(), keyword) :: {keyword, [Path.t()] | :disabled}
|
||||
def __eval__!(file, content, opts \\ []) when is_binary(file) and is_list(opts) do
|
||||
env = Keyword.get(opts, :env)
|
||||
target = Keyword.get(opts, :target)
|
||||
imports = Keyword.get(opts, :imports, [])
|
||||
|
||||
previous_opts = put_opts({env, target})
|
||||
@spec __eval__!(Path.t(), [Path.t()]) :: {keyword, [Path.t()]}
|
||||
def __eval__!(file, imported_paths \\ []) when is_binary(file) and is_list(imported_paths) do
|
||||
previous_config = put_config([])
|
||||
previous_imports = put_imports(imports)
|
||||
previous_files = put_files(imported_paths)
|
||||
|
||||
try do
|
||||
{eval_config, _} = import_config!(file, content, false)
|
||||
{eval_config, _} = __import__!(Path.expand(file))
|
||||
|
||||
case get_config!() do
|
||||
[] when is_list(eval_config) ->
|
||||
{validate!(eval_config, file), get_imports!()}
|
||||
{validate!(eval_config, file), get_files!()}
|
||||
|
||||
pdict_config ->
|
||||
{pdict_config, get_imports!()}
|
||||
{pdict_config, get_files!()}
|
||||
end
|
||||
after
|
||||
if previous_opts, do: put_opts(previous_opts), else: delete_opts()
|
||||
if previous_config, do: put_config(previous_config), else: delete_config()
|
||||
if previous_imports, do: put_imports(previous_imports), else: delete_imports()
|
||||
if previous_files, do: put_files(previous_files), else: delete_files()
|
||||
end
|
||||
end
|
||||
|
||||
defp import_config!(file, contents, raise_when_disabled?) do
|
||||
current_imports = get_imports!()
|
||||
|
||||
cond do
|
||||
current_imports == :disabled ->
|
||||
if raise_when_disabled? do
|
||||
raise "import_config/1 is not enabled for this configuration file. " <>
|
||||
"Some configuration files do not allow importing other files " <>
|
||||
"as they are often copied to external systems"
|
||||
end
|
||||
|
||||
file in current_imports ->
|
||||
raise ArgumentError,
|
||||
"attempting to load configuration #{Path.relative_to_cwd(file)} recursively"
|
||||
|
||||
true ->
|
||||
put_imports([file | current_imports])
|
||||
:ok
|
||||
end
|
||||
|
||||
# TODO: Emit a warning if Mix.env() is found in said files in Elixir v1.15.
|
||||
# Note this won't be a deprecation warning as it will always be emitted.
|
||||
Code.eval_string(contents, [], file: file)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def __merge__(config1, config2) when is_list(config1) and is_list(config2) do
|
||||
Keyword.merge(config1, config2, fn _, app1, app2 ->
|
||||
|
||||
@@ -39,15 +39,9 @@ defmodule Config.Provider do
|
||||
end
|
||||
end
|
||||
|
||||
Then when specifying your release, you can specify the provider in
|
||||
the release configuration:
|
||||
Then when specifying your release, you can specify the provider:
|
||||
|
||||
releases: [
|
||||
demo: [
|
||||
# ...,
|
||||
config_providers: [{JSONConfigProvider, "/etc/config.json"}]
|
||||
]
|
||||
]
|
||||
config_providers: [{JSONConfigProvider, "/etc/config.json"}]
|
||||
|
||||
Now once the system boots, it will invoke the provider early in
|
||||
the boot process, save the merged configuration to the disk, and
|
||||
@@ -65,9 +59,8 @@ defmodule Config.Provider do
|
||||
|
||||
* a binary representing an absolute path
|
||||
|
||||
* a `{:system, system_var, path}` tuple where the config is the
|
||||
concatenation of the environment variable `system_var` with
|
||||
the given `path`
|
||||
* a tuple {:system, system_var, path} where the config is the
|
||||
concatenation of the `system_var` with the given `path`
|
||||
|
||||
"""
|
||||
@type config_path :: {:system, binary(), binary()} | binary()
|
||||
@@ -105,16 +98,7 @@ defmodule Config.Provider do
|
||||
@callback load(config, state) :: config
|
||||
|
||||
@doc false
|
||||
defstruct [
|
||||
:providers,
|
||||
:config_path,
|
||||
extra_config: [],
|
||||
prune_runtime_sys_config_after_boot: false,
|
||||
reboot_system_after_config: false,
|
||||
validate_compile_env: false
|
||||
]
|
||||
|
||||
@reserved_apps [:kernel, :stdlib]
|
||||
defstruct [:providers, :config_path, extra_config: [], prune_after_boot: false]
|
||||
|
||||
@doc """
|
||||
Validates a `t:config_path/0`.
|
||||
@@ -149,176 +133,51 @@ defmodule Config.Provider do
|
||||
def resolve_config_path!(path) when is_binary(path), do: path
|
||||
def resolve_config_path!({:system, name, path}), do: System.fetch_env!(name) <> path
|
||||
|
||||
# Private keys
|
||||
@init_key :config_provider_init
|
||||
@booted_key :config_provider_booted
|
||||
|
||||
# Public keys
|
||||
@reboot_mode_key :config_provider_reboot_mode
|
||||
|
||||
@doc false
|
||||
def init(providers, config_path, opts \\ []) when is_list(providers) and is_list(opts) do
|
||||
validate_config_path!(config_path)
|
||||
providers = for {provider, init} <- providers, do: {provider, provider.init(init)}
|
||||
init = struct!(%Config.Provider{config_path: config_path, providers: providers}, opts)
|
||||
[elixir: [{@init_key, init}]]
|
||||
struct!(%Config.Provider{config_path: config_path, providers: providers}, opts)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def boot(reboot_fun \\ &restart_and_sleep/0) do
|
||||
def boot(app, key, restart_fun \\ &System.restart/0) do
|
||||
# The app with the config provider settings may not
|
||||
# have been loaded at this point, so make sure we load
|
||||
# its environment before querying it.
|
||||
_ = :application.load(app)
|
||||
|
||||
# The config provider typically runs very early in the
|
||||
# release process, so we need to make sure Elixir is started
|
||||
# before we go around running Elixir code.
|
||||
{:ok, _} = :application.ensure_all_started(:elixir)
|
||||
|
||||
case Application.fetch_env(:elixir, @booted_key) do
|
||||
case :application.get_env(app, key) do
|
||||
{:ok, %Config.Provider{} = provider} ->
|
||||
path = resolve_config_path!(provider.config_path)
|
||||
validate_no_cyclic_boot!(path)
|
||||
|
||||
read_config!(path)
|
||||
|> Config.__merge__([{app, [{key, booted_key(provider, path)}]} | provider.extra_config])
|
||||
|> run_providers(provider)
|
||||
|> write_config!(path)
|
||||
|
||||
restart_fun.()
|
||||
|
||||
{:ok, {:booted, path}} ->
|
||||
path && File.rm(path)
|
||||
|
||||
with {:ok, %Config.Provider{} = provider} <- Application.fetch_env(:elixir, @init_key) do
|
||||
maybe_validate_compile_env(provider)
|
||||
end
|
||||
File.rm(path)
|
||||
:booted
|
||||
|
||||
{:ok, :booted} ->
|
||||
:booted
|
||||
|
||||
_ ->
|
||||
case Application.fetch_env(:elixir, @init_key) do
|
||||
{:ok, %Config.Provider{} = provider} ->
|
||||
path = resolve_config_path!(provider.config_path)
|
||||
reboot_config = [elixir: [{@booted_key, booted_value(provider, path)}]]
|
||||
boot_providers(path, provider, reboot_config, reboot_fun)
|
||||
|
||||
_ ->
|
||||
:skip
|
||||
end
|
||||
:skip
|
||||
end
|
||||
end
|
||||
|
||||
defp boot_providers(path, provider, reboot_config, reboot_fun) do
|
||||
validate_no_cyclic_boot!(path)
|
||||
original_config = read_config!(path)
|
||||
|
||||
config =
|
||||
original_config
|
||||
|> Config.__merge__(provider.extra_config)
|
||||
|> run_providers(provider)
|
||||
|
||||
if provider.reboot_system_after_config do
|
||||
config
|
||||
|> Config.__merge__(reboot_config)
|
||||
|> write_config!(path)
|
||||
|
||||
reboot_fun.()
|
||||
else
|
||||
for app <- @reserved_apps, config[app] != original_config[app] do
|
||||
abort("""
|
||||
Cannot configure #{inspect(app)} because :reboot_system_after_config has been set \
|
||||
to false and #{inspect(app)} has already been loaded, meaning any further \
|
||||
configuration won't have an effect.
|
||||
|
||||
The configuration for #{inspect(app)} before config providers was:
|
||||
|
||||
#{inspect(original_config[app])}
|
||||
|
||||
The configuration for #{inspect(app)} after config providers was:
|
||||
|
||||
#{inspect(config[app])}
|
||||
""")
|
||||
end
|
||||
|
||||
_ = Application.put_all_env(config, persistent: true)
|
||||
maybe_validate_compile_env(provider)
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_validate_compile_env(provider) do
|
||||
with [_ | _] = compile_env <- provider.validate_compile_env do
|
||||
validate_compile_env(compile_env)
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def validate_compile_env(compile_env, ensure_loaded? \\ true) do
|
||||
for {app, [key | path], compile_return} <- compile_env,
|
||||
ensure_app_loaded?(app, ensure_loaded?) do
|
||||
try do
|
||||
traverse_env(Application.fetch_env(app, key), path)
|
||||
rescue
|
||||
e ->
|
||||
abort("""
|
||||
application #{inspect(app)} failed reading its compile environment #{path(key, path)}:
|
||||
|
||||
#{Exception.format(:error, e, __STACKTRACE__)}
|
||||
|
||||
Expected it to match the compile time value of #{return_to_text(compile_return)}.
|
||||
|
||||
#{compile_env_tips(app)}
|
||||
""")
|
||||
else
|
||||
^compile_return ->
|
||||
:ok
|
||||
|
||||
runtime_return ->
|
||||
abort("""
|
||||
the application #{inspect(app)} has a different value set #{path(key, path)} \
|
||||
during runtime compared to compile time. Since this application environment entry was \
|
||||
marked as compile time, this difference can lead to different behaviour than expected:
|
||||
|
||||
* Compile time value #{return_to_text(compile_return)}
|
||||
* Runtime value #{return_to_text(runtime_return)}
|
||||
|
||||
#{compile_env_tips(app)}
|
||||
""")
|
||||
end
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp ensure_app_loaded?(app, true), do: Application.ensure_loaded(app) == :ok
|
||||
defp ensure_app_loaded?(app, false), do: Application.spec(app, :vsn) != nil
|
||||
|
||||
defp path(key, []), do: "for key #{inspect(key)}"
|
||||
defp path(key, path), do: "for path #{inspect(path)} inside key #{inspect(key)}"
|
||||
|
||||
defp compile_env_tips(app),
|
||||
do: """
|
||||
To fix this error, you might:
|
||||
|
||||
* Make the runtime value match the compile time one
|
||||
|
||||
* Recompile your project. If the misconfigured application is a dependency, \
|
||||
you may need to run "mix deps.compile #{app} --force"
|
||||
|
||||
* Alternatively, you can disable this check. If you are using releases, you can \
|
||||
set :validate_compile_env to false in your release configuration. If you are \
|
||||
using Mix to start your system, you can pass the --no-validate-compile-env flag
|
||||
"""
|
||||
|
||||
defp return_to_text({:ok, value}), do: "was set to: #{inspect(value)}"
|
||||
defp return_to_text(:error), do: "was not set"
|
||||
|
||||
defp traverse_env(return, []), do: return
|
||||
defp traverse_env(:error, _paths), do: :error
|
||||
defp traverse_env({:ok, value}, [key | keys]), do: traverse_env(Access.fetch(value, key), keys)
|
||||
|
||||
@compile {:no_warn_undefined, {:init, :restart, 1}}
|
||||
defp restart_and_sleep() do
|
||||
mode = Application.get_env(:elixir, @reboot_mode_key)
|
||||
|
||||
# TODO: Remove otp_release check once we require Erlang/OTP 23+
|
||||
if :erlang.system_info(:otp_release) >= '23' and mode in [:embedded, :interactive] do
|
||||
:init.restart(mode: mode)
|
||||
else
|
||||
:init.restart()
|
||||
end
|
||||
|
||||
Process.sleep(:infinity)
|
||||
end
|
||||
|
||||
defp booted_value(%{prune_runtime_sys_config_after_boot: true}, path), do: {:booted, path}
|
||||
defp booted_value(%{prune_runtime_sys_config_after_boot: false}, _path), do: {:booted, nil}
|
||||
defp booted_key(%{prune_after_boot: true}, path), do: {:booted, path}
|
||||
defp booted_key(%{prune_after_boot: false}, _path), do: :booted
|
||||
|
||||
defp validate_no_cyclic_boot!(path) do
|
||||
if System.get_env("ELIXIR_CONFIG_PROVIDER_BOOTED") do
|
||||
@@ -363,7 +222,7 @@ defmodule Config.Provider do
|
||||
defp write_config!(config, path) do
|
||||
contents = :io_lib.format("%% coding: utf-8~n~tw.~n", [config])
|
||||
|
||||
case File.write(path, IO.chardata_to_string(contents)) do
|
||||
case File.write(path, contents, [:utf8]) do
|
||||
:ok ->
|
||||
:ok
|
||||
|
||||
@@ -385,6 +244,6 @@ defmodule Config.Provider do
|
||||
|
||||
defp abort(msg) do
|
||||
IO.puts(:stderr, "ERROR! " <> msg)
|
||||
:erlang.raise(:error, "aborting boot", [{Config.Provider, :boot, 2, []}])
|
||||
raise(msg)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,104 +4,59 @@ defmodule Config.Reader do
|
||||
|
||||
## As a provider
|
||||
|
||||
`Config.Reader` can also be used as a `Config.Provider`. When used
|
||||
as a provider, it expects a single argument: the configuration path
|
||||
(as outlined in `t:Config.Provider.config_path/0`) for the file to
|
||||
be read and loaded during the system boot.
|
||||
|
||||
For example, if you expect the target system to have a config file
|
||||
in an absolute path, you can configure your `mix release` as:
|
||||
|
||||
config_providers: [{Config.Reader, "/etc/config.exs"}]
|
||||
|
||||
Or if you want to read a custom path inside the release:
|
||||
|
||||
config_provider: [{Config.Reader, {:system, "RELEASE_ROOT", "/config.exs"}}]
|
||||
|
||||
You can also pass a keyword list of options to the reader,
|
||||
where the `:path` is a required key:
|
||||
|
||||
config_providers: [
|
||||
{Config.Reader,
|
||||
path: "/etc/config.exs",
|
||||
env: :prod,
|
||||
imports: :disabled}
|
||||
]
|
||||
|
||||
Note by default Mix releases supports runtime configuration via
|
||||
a `config/runtime.exs`. If a `config/runtime.exs` exists in your
|
||||
application, it is automatically copied inside the release and
|
||||
automatically set as a config provider.
|
||||
`Config.Reader` can also be used as a `Config.Provider`.
|
||||
When used as a provider, it expects a single argument:
|
||||
which the configuration path (as outlined in
|
||||
`t:Config.Provider.config_path/0`) for the configuration
|
||||
to be read and loaded during the system boot.
|
||||
"""
|
||||
|
||||
@behaviour Config.Provider
|
||||
|
||||
@impl true
|
||||
def init(opts) when is_list(opts) do
|
||||
{path, opts} = Keyword.pop!(opts, :path)
|
||||
Config.Provider.validate_config_path!(path)
|
||||
{path, opts}
|
||||
end
|
||||
|
||||
def init(path) do
|
||||
init(path: path)
|
||||
Config.Provider.validate_config_path!(path)
|
||||
path
|
||||
end
|
||||
|
||||
@impl true
|
||||
def load(config, {path, opts}) do
|
||||
merge(config, path |> Config.Provider.resolve_config_path!() |> read!(opts))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Evaluates the configuration `contents` for the given `file`.
|
||||
|
||||
Accepts the same options as `read!/2`.
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec eval!(Path.t(), binary, keyword) :: keyword
|
||||
def eval!(file, contents, opts \\ [])
|
||||
when is_binary(file) and is_binary(contents) and is_list(opts) do
|
||||
Config.__eval__!(Path.expand(file), contents, opts) |> elem(0)
|
||||
def load(config, path) do
|
||||
merge(config, path |> Config.Provider.resolve_config_path!() |> read!())
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads the configuration file.
|
||||
|
||||
## Options
|
||||
The same as `read_imports!/2` but only returns the configuration
|
||||
in the given file, without returning the imported paths.
|
||||
|
||||
* `:imports` - a list of already imported paths or `:disabled`
|
||||
to disable imports
|
||||
It exists for convenience purposes. For example, you could
|
||||
invoke it inside your `mix.exs` to read some external data
|
||||
you decided to move to a configuration file:
|
||||
|
||||
* `:env` - the environment the configuration file runs on.
|
||||
See `Config.config_env/0` for sample usage
|
||||
|
||||
* `:target` - the target the configuration file runs on.
|
||||
See `Config.config_target/0` for sample usage
|
||||
releases: Config.Reader.read!("rel/releases.exs")
|
||||
|
||||
"""
|
||||
@doc since: "1.9.0"
|
||||
@spec read!(Path.t(), keyword) :: keyword
|
||||
def read!(file, opts \\ []) when is_binary(file) and is_list(opts) do
|
||||
file = Path.expand(file)
|
||||
Config.__eval__!(file, File.read!(file), opts) |> elem(0)
|
||||
@spec read!(Path.t(), [Path.t()]) :: keyword
|
||||
def read!(file, imported_paths \\ [])
|
||||
when is_binary(file) and is_list(imported_paths) do
|
||||
Config.__eval__!(file, imported_paths) |> elem(0)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads the given configuration file and returns the configuration
|
||||
with its imports.
|
||||
Reads the given configuration file alongside its imports.
|
||||
|
||||
Accepts the same options as `read!/2`. Although note the `:imports`
|
||||
option cannot be disabled in `read_imports!/2`.
|
||||
It accepts a list of `imported_paths` that should raise if attempted
|
||||
to be imported again (to avoid recursive imports).
|
||||
|
||||
It returns a tuple with the configuration and the imported paths.
|
||||
"""
|
||||
@doc since: "1.9.0"
|
||||
@spec read_imports!(Path.t(), keyword) :: {keyword, [Path.t()]}
|
||||
def read_imports!(file, opts \\ []) when is_binary(file) and is_list(opts) do
|
||||
if opts[:imports] == :disabled do
|
||||
raise ArgumentError, ":imports must be a list of paths"
|
||||
end
|
||||
|
||||
file = Path.expand(file)
|
||||
Config.__eval__!(file, File.read!(file), opts)
|
||||
@spec read_imports!(Path.t(), [Path.t()]) :: {keyword, [Path.t()]}
|
||||
def read_imports!(file, imported_paths \\ [])
|
||||
when is_binary(file) and is_list(imported_paths) do
|
||||
Config.__eval__!(file, imported_paths)
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
@@ -18,14 +18,11 @@ defmodule Dict do
|
||||
message =
|
||||
"Use the Map module for working with maps or the Keyword module for working with keyword lists"
|
||||
|
||||
@deprecated message
|
||||
defmacro __using__(_) do
|
||||
# Use this import to guarantee proper code expansion
|
||||
import Kernel, except: [size: 1]
|
||||
|
||||
if __CALLER__.module != HashDict do
|
||||
IO.warn("use Dict is deprecated. " <> unquote(message), Macro.Env.stacktrace(__CALLER__))
|
||||
end
|
||||
|
||||
quote do
|
||||
message = "Use maps and the Map module instead"
|
||||
|
||||
@@ -155,13 +152,13 @@ defmodule Dict do
|
||||
end
|
||||
|
||||
@deprecated message
|
||||
def update(dict, key, default, fun) do
|
||||
def update(dict, key, initial, fun) do
|
||||
case fetch(dict, key) do
|
||||
{:ok, value} ->
|
||||
put(dict, key, fun.(value))
|
||||
|
||||
:error ->
|
||||
put(dict, key, default)
|
||||
put(dict, key, initial)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -378,8 +375,8 @@ defmodule Dict do
|
||||
|
||||
@deprecated message
|
||||
@spec update(t, key, value, (value -> value)) :: t
|
||||
def update(dict, key, default, fun) do
|
||||
target(dict).update(dict, key, default, fun)
|
||||
def update(dict, key, initial, fun) do
|
||||
target(dict).update(dict, key, initial, fun)
|
||||
end
|
||||
|
||||
@deprecated message
|
||||
|
||||
@@ -11,8 +11,9 @@ defmodule DynamicSupervisor do
|
||||
|
||||
## Examples
|
||||
|
||||
A dynamic supervisor is started with no children, a supervision strategy
|
||||
(the only strategy currently supported is `:one_for_one`), and a name:
|
||||
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}
|
||||
@@ -148,9 +149,12 @@ defmodule DynamicSupervisor do
|
||||
}
|
||||
|
||||
@typedoc "Option values used by the `start*` functions"
|
||||
@type option :: GenServer.option()
|
||||
@type option :: {:name, Supervisor.name()} | init_option()
|
||||
|
||||
@typedoc "Options given to `start_link/1` and `init/1`"
|
||||
@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()}
|
||||
@@ -207,7 +211,7 @@ defmodule DynamicSupervisor do
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@behaviour DynamicSupervisor
|
||||
unless Module.has_attribute?(__MODULE__, :doc) do
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
@@ -251,7 +255,7 @@ defmodule DynamicSupervisor do
|
||||
with `:normal` reason.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_link([option | init_option]) :: Supervisor.on_start()
|
||||
@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)
|
||||
@@ -277,7 +281,7 @@ defmodule DynamicSupervisor do
|
||||
section in the `GenServer` module docs.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_link(module, term, [option]) :: Supervisor.on_start()
|
||||
@spec start_link(module, term, GenServer.options()) :: Supervisor.on_start()
|
||||
def start_link(mod, init_arg, opts \\ []) do
|
||||
GenServer.start_link(__MODULE__, {mod, init_arg, opts[:name]}, opts)
|
||||
end
|
||||
@@ -286,7 +290,7 @@ defmodule DynamicSupervisor do
|
||||
Dynamically adds a child specification to `supervisor` and starts that child.
|
||||
|
||||
`child_spec` should be a valid child specification as detailed in the
|
||||
"Child specification" section of the documentation for `Supervisor`. The child
|
||||
"child_spec/1" section of the documentation for `Supervisor`. The child
|
||||
process will be started as defined in the child specification.
|
||||
|
||||
If the child process start function returns `{:ok, child}` or `{:ok, child,
|
||||
@@ -306,13 +310,7 @@ defmodule DynamicSupervisor do
|
||||
this function returns `{:error, :max_children}`.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_child(
|
||||
Supervisor.supervisor(),
|
||||
Supervisor.child_spec()
|
||||
| {module, term}
|
||||
| module
|
||||
| (old_erlang_child_spec :: :supervisor.child_spec())
|
||||
) ::
|
||||
@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)
|
||||
@@ -418,8 +416,7 @@ defmodule DynamicSupervisor do
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec which_children(Supervisor.supervisor()) :: [
|
||||
# module() | :dynamic here because :supervisor.modules() is not exported
|
||||
{:undefined, pid | :restarting, :worker | :supervisor, module() | :dynamic}
|
||||
{:undefined, pid | :restarting, :worker | :supervisor, :supervisor.modules()}
|
||||
]
|
||||
def which_children(supervisor) do
|
||||
call(supervisor, :which_children)
|
||||
@@ -476,7 +473,7 @@ defmodule DynamicSupervisor do
|
||||
module-based supervisors. See the "Module-based supervisors" section
|
||||
in the module documentation for more information.
|
||||
|
||||
The `options` received by this function are also supported by `start_link/1`.
|
||||
The `options` received by this function are also supported by `start_link/2`.
|
||||
|
||||
This function returns a tuple containing the supervisor options.
|
||||
|
||||
@@ -748,20 +745,7 @@ defmodule DynamicSupervisor do
|
||||
end
|
||||
|
||||
def handle_info(msg, state) do
|
||||
:logger.error(
|
||||
%{
|
||||
label: {DynamicSupervisor, :unexpected_msg},
|
||||
report: %{
|
||||
msg: msg
|
||||
}
|
||||
},
|
||||
%{
|
||||
domain: [:otp, :elixir],
|
||||
error_logger: %{tag: :error_msg},
|
||||
report_cb: &__MODULE__.format_report/1
|
||||
}
|
||||
)
|
||||
|
||||
:error_logger.error_msg('DynamicSupervisor received unexpected message: ~p~n', [msg])
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
@@ -1004,22 +988,12 @@ defmodule DynamicSupervisor do
|
||||
end
|
||||
|
||||
defp report_error(error, reason, pid, child, %{name: name, extra_arguments: extra}) do
|
||||
:logger.error(
|
||||
%{
|
||||
label: {:supervisor, error},
|
||||
report: [
|
||||
{:supervisor, name},
|
||||
{:errorContext, error},
|
||||
{:reason, reason},
|
||||
{:offender, extract_child(pid, child, extra)}
|
||||
]
|
||||
},
|
||||
%{
|
||||
domain: [:otp, :sasl],
|
||||
report_cb: &:logger.format_otp_report/1,
|
||||
logger_formatter: %{title: "SUPERVISOR REPORT"},
|
||||
error_logger: %{tag: :error_report, type: :supervisor_report}
|
||||
}
|
||||
:error_logger.error_report(
|
||||
:supervisor_report,
|
||||
supervisor: name,
|
||||
errorContext: error,
|
||||
reason: reason,
|
||||
offender: extract_child(pid, child, extra)
|
||||
)
|
||||
end
|
||||
|
||||
@@ -1050,12 +1024,4 @@ defmodule DynamicSupervisor do
|
||||
defp call(supervisor, req) do
|
||||
GenServer.call(supervisor, req, :infinity)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def format_report(%{
|
||||
label: {__MODULE__, :unexpected_msg},
|
||||
report: %{msg: msg}
|
||||
}) do
|
||||
{'DynamicSupervisor received unexpected message: ~p~n', [msg]}
|
||||
end
|
||||
end
|
||||
|
||||
+213
-653
File diff suppressed because it is too large
Load Diff
+77
-124
@@ -21,15 +21,15 @@ defmodule Exception do
|
||||
|
||||
@typedoc "The kind handled by formatting functions"
|
||||
@type kind :: :error | non_error_kind
|
||||
@type non_error_kind :: :exit | :throw | {:EXIT, pid}
|
||||
@typep non_error_kind :: :exit | :throw | {:EXIT, pid}
|
||||
|
||||
@type stacktrace :: [stacktrace_entry]
|
||||
@type stacktrace_entry ::
|
||||
{module, atom, arity_or_args, location}
|
||||
| {(... -> any), arity_or_args, location}
|
||||
|
||||
@type arity_or_args :: non_neg_integer | list
|
||||
@type location :: keyword
|
||||
@typep arity_or_args :: non_neg_integer | list
|
||||
@typep location :: keyword
|
||||
|
||||
@callback exception(term) :: t
|
||||
@callback message(t) :: String.t()
|
||||
@@ -46,8 +46,6 @@ defmodule Exception do
|
||||
@doc """
|
||||
Returns `true` if the given `term` is an exception.
|
||||
"""
|
||||
# TODO: Remove this on Elixir v1.15
|
||||
@doc deprecated: "Use Kernel.is_exception/1 instead"
|
||||
def exception?(term)
|
||||
def exception?(%_{__exception__: true}), do: true
|
||||
def exception?(_), do: false
|
||||
@@ -190,7 +188,7 @@ defmodule Exception do
|
||||
Where `definition` is `:def`, `:defp`, `:defmacro` or `:defmacrop`.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec blame_mfa(module, function :: atom, args :: [term]) ::
|
||||
@spec blame_mfa(module, function, args :: [term]) ::
|
||||
{:ok, :def | :defp | :defmacro | :defmacrop, [{args :: [term], guards :: [term]}]}
|
||||
| :error
|
||||
def blame_mfa(module, function, args)
|
||||
@@ -239,11 +237,7 @@ defmodule Exception do
|
||||
binding = :orddict.store(:VAR, call_arg, binding)
|
||||
|
||||
try do
|
||||
ann = :erl_anno.new(0)
|
||||
|
||||
{:value, _, binding} =
|
||||
:erl_eval.expr({:match, ann, erl_arg, {:var, ann, :VAR}}, binding, :none)
|
||||
|
||||
{:value, _, binding} = :erl_eval.expr({:match, 0, erl_arg, {:var, 0, :VAR}}, binding, :none)
|
||||
{true, binding}
|
||||
rescue
|
||||
_ -> {false, binding}
|
||||
@@ -267,13 +261,7 @@ defmodule Exception do
|
||||
blame_guard(right, scope, binding)
|
||||
]
|
||||
|
||||
kernel_op =
|
||||
case op do
|
||||
:orelse -> :or
|
||||
:andalso -> :and
|
||||
end
|
||||
|
||||
{kernel_op, meta, guards}
|
||||
{rewrite_guard_call(op), meta, guards}
|
||||
end
|
||||
|
||||
defp blame_guard(ex_guard, scope, binding) do
|
||||
@@ -292,17 +280,32 @@ defmodule Exception do
|
||||
|
||||
defp rewrite_guard(guard) do
|
||||
Macro.prewalk(guard, fn
|
||||
{{:., _, [mod, fun]}, meta, args} -> erl_to_ex(mod, fun, args, meta)
|
||||
other -> other
|
||||
{{:., _, [: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 erl_to_ex(mod, fun, args, meta) do
|
||||
case :elixir_rewrite.erl_to_ex(mod, fun, args) do
|
||||
{Kernel, fun, args} -> {fun, meta, args}
|
||||
{mod, fun, args} -> {{:., [], [mod, fun]}, meta, args}
|
||||
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}
|
||||
|
||||
@@ -541,17 +544,8 @@ defmodule Exception do
|
||||
defp format_application(module) do
|
||||
# We cannot use Application due to bootstrap issues
|
||||
case :application.get_application(module) do
|
||||
{:ok, app} ->
|
||||
case :application.get_key(app, :vsn) do
|
||||
{:ok, vsn} when is_list(vsn) ->
|
||||
"(" <> Atom.to_string(app) <> " " <> List.to_string(vsn) <> ") "
|
||||
|
||||
_ ->
|
||||
"(" <> Atom.to_string(app) <> ") "
|
||||
end
|
||||
|
||||
:undefined ->
|
||||
""
|
||||
{:ok, app} -> "(" <> Atom.to_string(app) <> ") "
|
||||
:undefined -> ""
|
||||
end
|
||||
end
|
||||
|
||||
@@ -635,7 +629,6 @@ defmodule Exception do
|
||||
|
||||
@doc """
|
||||
Formats the given `file` and `line` as shown in stacktraces.
|
||||
|
||||
If any of the values are `nil`, they are omitted.
|
||||
|
||||
## Examples
|
||||
@@ -651,42 +644,14 @@ defmodule Exception do
|
||||
|
||||
"""
|
||||
def format_file_line(file, line, suffix \\ "") do
|
||||
cond do
|
||||
is_nil(file) -> ""
|
||||
is_nil(line) or line == 0 -> "#{file}:#{suffix}"
|
||||
true -> "#{file}:#{line}:#{suffix}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Formats the given `file`, `line`, and `column` as shown in stacktraces.
|
||||
|
||||
If any of the values are `nil`, they are omitted.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Exception.format_file_line_column("foo", 1, 2)
|
||||
"foo:1:2:"
|
||||
|
||||
iex> Exception.format_file_line_column("foo", 1, nil)
|
||||
"foo:1:"
|
||||
|
||||
iex> Exception.format_file_line_column("foo", nil, nil)
|
||||
"foo:"
|
||||
|
||||
iex> Exception.format_file_line_column("foo", nil, 2)
|
||||
"foo:"
|
||||
|
||||
iex> Exception.format_file_line_column(nil, nil, nil)
|
||||
if file do
|
||||
if line && line != 0 do
|
||||
"#{file}:#{line}:#{suffix}"
|
||||
else
|
||||
"#{file}:#{suffix}"
|
||||
end
|
||||
else
|
||||
""
|
||||
|
||||
"""
|
||||
def format_file_line_column(file, line, column, suffix \\ "") do
|
||||
cond do
|
||||
is_nil(file) -> ""
|
||||
is_nil(line) or line == 0 -> "#{file}:#{suffix}"
|
||||
is_nil(column) or column == 0 -> "#{file}:#{line}:#{suffix}"
|
||||
true -> "#{file}:#{line}:#{column}:#{suffix}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -718,7 +683,7 @@ defmodule ArgumentError do
|
||||
not is_atom(module) and is_atom(function) and args == [] ->
|
||||
"you attempted to apply #{inspect(function)} on #{inspect(module)}. " <>
|
||||
"If you are using apply/3, make sure the module is an atom. " <>
|
||||
"If you are using the dot syntax, such as map.field or module.function(), " <>
|
||||
"If you are using the dot syntax, such as map.field or module.function, " <>
|
||||
"make sure the left side of the dot is an atom or a map"
|
||||
|
||||
not is_atom(module) ->
|
||||
@@ -792,22 +757,21 @@ defmodule SystemLimitError do
|
||||
end
|
||||
|
||||
defmodule SyntaxError do
|
||||
defexception [:file, :line, :column, description: "syntax error"]
|
||||
defexception [:file, :line, description: "syntax error"]
|
||||
|
||||
@impl true
|
||||
def message(%{file: file, line: line, column: column, description: description}) do
|
||||
Exception.format_file_line_column(Path.relative_to_cwd(file), line, column) <>
|
||||
" " <> description
|
||||
def message(exception) do
|
||||
Exception.format_file_line(Path.relative_to_cwd(exception.file), exception.line) <>
|
||||
" " <> exception.description
|
||||
end
|
||||
end
|
||||
|
||||
defmodule TokenMissingError do
|
||||
defexception [:file, :line, :column, description: "expression is incomplete"]
|
||||
defexception [:file, :line, description: "expression is incomplete"]
|
||||
|
||||
@impl true
|
||||
def message(%{file: file, line: line, column: column, description: description}) do
|
||||
Exception.format_file_line_column(file && Path.relative_to_cwd(file), line, column) <>
|
||||
" " <> description
|
||||
def message(%{file: file, line: line, description: description}) do
|
||||
Exception.format_file_line(file && Path.relative_to_cwd(file), line) <> " " <> description
|
||||
end
|
||||
end
|
||||
|
||||
@@ -977,7 +941,7 @@ defmodule UndefinedFunctionError do
|
||||
end
|
||||
|
||||
defp hint(nil, _function, 0, _loaded?) do
|
||||
". If you are using the dot syntax, such as map.field or module.function(), " <>
|
||||
". If you are using the dot syntax, such as map.field or module.function, " <>
|
||||
"make sure the left side of the dot is an atom or a map"
|
||||
end
|
||||
|
||||
@@ -1089,8 +1053,6 @@ end
|
||||
defmodule FunctionClauseError do
|
||||
defexception [:module, :function, :arity, :kind, :args, :clauses]
|
||||
|
||||
@clause_limit 10
|
||||
|
||||
@impl true
|
||||
def message(exception) do
|
||||
case exception do
|
||||
@@ -1136,46 +1098,37 @@ defmodule FunctionClauseError do
|
||||
|
||||
mfa = Exception.format_mfa(module, function, arity)
|
||||
|
||||
format_clause_fun = fn {args, guards} ->
|
||||
code = Enum.reduce(guards, {function, [], args}, &{:when, [], [&2, &1]})
|
||||
" #{kind} " <> Macro.to_string(code, ast_fun) <> "\n"
|
||||
end
|
||||
formatted_args =
|
||||
args
|
||||
|> Enum.with_index(1)
|
||||
|> Enum.map(fn {arg, i} ->
|
||||
["\n # ", Integer.to_string(i), "\n ", pad(inspect_fun.(arg)), "\n"]
|
||||
end)
|
||||
|
||||
"\n\nThe following arguments were given to #{mfa}:\n" <>
|
||||
"#{format_args(args, inspect_fun)}" <>
|
||||
"#{format_clauses(clauses, format_clause_fun, @clause_limit)}"
|
||||
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 format_args(args, inspect_fun) do
|
||||
args
|
||||
|> Enum.with_index(1)
|
||||
|> Enum.map(fn {arg, i} ->
|
||||
[pad("\n# "), Integer.to_string(i), pad("\n"), pad(inspect_fun.(arg)), "\n"]
|
||||
end)
|
||||
end
|
||||
|
||||
defp format_clauses(clauses, format_clause_fun, limit)
|
||||
defp format_clauses(nil, _, _), do: ""
|
||||
defp format_clauses([], _, _), do: ""
|
||||
|
||||
defp format_clauses(clauses, format_clause_fun, limit) do
|
||||
top_clauses =
|
||||
clauses
|
||||
|> Enum.take(limit)
|
||||
|> Enum.map(format_clause_fun)
|
||||
|
||||
[
|
||||
"\nAttempted function clauses (showing #{length(top_clauses)} out of #{length(clauses)}):",
|
||||
"\n\n",
|
||||
top_clauses,
|
||||
non_visible_clauses(length(clauses) - limit)
|
||||
]
|
||||
end
|
||||
|
||||
defp non_visible_clauses(n) when n <= 0, do: []
|
||||
defp non_visible_clauses(1), do: [" ...\n (1 clause not shown)\n"]
|
||||
defp non_visible_clauses(n), do: [" ...\n (#{n} clauses not shown)\n"]
|
||||
|
||||
defp pad(string) do
|
||||
String.replace(string, "\n", "\n ")
|
||||
end
|
||||
@@ -1356,7 +1309,7 @@ defmodule File.CopyError do
|
||||
formatted = IO.iodata_to_binary(:file.format_error(exception.reason))
|
||||
|
||||
location =
|
||||
case exception.on do
|
||||
case exception.on() do
|
||||
"" -> ""
|
||||
on -> ". #{on}"
|
||||
end
|
||||
@@ -1374,7 +1327,7 @@ defmodule File.RenameError do
|
||||
formatted = IO.iodata_to_binary(:file.format_error(exception.reason))
|
||||
|
||||
location =
|
||||
case exception.on do
|
||||
case exception.on() do
|
||||
"" -> ""
|
||||
on -> ". #{on}"
|
||||
end
|
||||
|
||||
+13
-23
@@ -6,7 +6,7 @@ defmodule File do
|
||||
to interact with files or IO devices, like `open/2`,
|
||||
`copy/3` and others. This module also provides higher
|
||||
level functions that work with filenames and have their naming
|
||||
based on Unix variants. For example, one can copy a file
|
||||
based on UNIX variants. For example, one can copy a file
|
||||
via `cp/3` and remove files and directories recursively
|
||||
via `rm_rf/1`.
|
||||
|
||||
@@ -110,7 +110,6 @@ defmodule File do
|
||||
|
||||
@type stream_mode ::
|
||||
encoding_mode()
|
||||
| :append
|
||||
| :trim_bom
|
||||
| {:read_ahead, pos_integer | false}
|
||||
| {:delayed_write, non_neg_integer, non_neg_integer}
|
||||
@@ -586,7 +585,7 @@ defmodule File do
|
||||
File.touch!("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
|
||||
#=> :ok
|
||||
File.touch!("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
|
||||
** (File.Error) could not touch "/fakedir/b.txt": no such file or directory
|
||||
#=> ** (File.Error) could not touch "/fakedir/b.txt": no such file or directory
|
||||
|
||||
File.touch!("/tmp/a.txt", 1544519753)
|
||||
|
||||
@@ -723,7 +722,7 @@ defmodule File do
|
||||
|
||||
Returns `:ok` in case of success, `{:error, reason}` otherwise.
|
||||
|
||||
Note: The command `mv` in Unix-like systems behaves differently depending on
|
||||
Note: The command `mv` in Unix systems behaves differently depending on
|
||||
whether `source` is a file and the `destination` is an existing directory.
|
||||
We have chosen to explicitly disallow this behaviour.
|
||||
|
||||
@@ -736,7 +735,6 @@ defmodule File do
|
||||
File.rename("samples", "tmp")
|
||||
|
||||
"""
|
||||
@doc since: "1.1.0"
|
||||
@spec rename(Path.t(), Path.t()) :: :ok | {:error, posix}
|
||||
def rename(source, destination) do
|
||||
:file.rename(source, destination)
|
||||
@@ -780,7 +778,7 @@ defmodule File do
|
||||
or do a straight copy from a source to a destination without
|
||||
preserving modes, check `copy/3` instead.
|
||||
|
||||
Note: The command `cp` in Unix-like systems behaves differently depending on
|
||||
Note: The command `cp` in Unix systems behaves differently depending on
|
||||
whether the destination is an existing directory or not. We have chosen to
|
||||
explicitly disallow copying to a destination which is a directory,
|
||||
and an error will be returned if tried.
|
||||
@@ -848,7 +846,7 @@ defmodule File do
|
||||
success, `files_and_directories` lists all files and directories copied in no
|
||||
specific order. It returns `{:error, reason, file}` otherwise.
|
||||
|
||||
Note: The command `cp` in Unix-like systems behaves differently depending on
|
||||
Note: The command `cp` in Unix systems behaves differently depending on
|
||||
whether `destination` is an existing directory or not. We have chosen to
|
||||
explicitly disallow this behaviour. If `source` is a `file` and `destination`
|
||||
is a directory, `{:error, :eisdir}` will be returned.
|
||||
@@ -1245,7 +1243,7 @@ defmodule File do
|
||||
end
|
||||
|
||||
# On Windows, symlinks are treated as directory and must be removed
|
||||
# with rmdir/1. But on Unix-like systems, we remove them via rm/1. So we first try
|
||||
# with rmdir/1. But on Unix, we remove them via rm/1. So we first try
|
||||
# to remove it as a directory and, if we get :enotdir, we fall back to
|
||||
# a file removal.
|
||||
defp do_rm_directory(path, {:ok, acc} = entry) do
|
||||
@@ -1312,7 +1310,7 @@ defmodule File do
|
||||
|
||||
The allowed modes:
|
||||
|
||||
* `:binary` - opens the file in binary mode, disabling special handling of Unicode sequences
|
||||
* `:binary` - opens the file in binary mode, disabling special handling of unicode sequences
|
||||
(default mode).
|
||||
|
||||
* `:read` - the file, which must exist, is opened for reading.
|
||||
@@ -1357,11 +1355,9 @@ defmodule File do
|
||||
* `{:ok, io_device}` - the file has been opened in the requested mode.
|
||||
|
||||
`io_device` is actually the PID of the process which handles the file.
|
||||
This process monitors the process that originally opened the file (the
|
||||
owner process). If the owner process terminates, the file is closed and
|
||||
the process itself terminates too. If any process to which the `io_device`
|
||||
is linked terminates, the file will be closed and the process itself will
|
||||
be terminated.
|
||||
This process is linked to the process which originally opened the file.
|
||||
If any process to which the `io_device` is linked terminates, the file
|
||||
will be closed and the process itself will be terminated.
|
||||
|
||||
An `io_device` returned from this call can be used as an argument to the
|
||||
`IO` module functions.
|
||||
@@ -1466,7 +1462,7 @@ defmodule File do
|
||||
@doc """
|
||||
Gets the current working directory.
|
||||
|
||||
In rare circumstances, this function can fail on Unix-like systems. It may happen
|
||||
In rare circumstances, this function can fail on Unix. It may happen
|
||||
if read permissions do not exist for the parent directories of the
|
||||
current directory. For this reason, returns `{:ok, cwd}` in case
|
||||
of success, `{:error, reason}` otherwise.
|
||||
@@ -1505,12 +1501,6 @@ defmodule File do
|
||||
@doc """
|
||||
Sets the current working directory.
|
||||
|
||||
The current working directory is set for the BEAM globally. This can lead to
|
||||
race conditions if multiple processes are changing the current working
|
||||
directory concurrently. To run an external command in a given directory
|
||||
without changing the global current working directory, use the `:cd` option
|
||||
of `System.cmd/3` and `Port.open/2`.
|
||||
|
||||
Returns `:ok` if successful, `{:error, reason}` otherwise.
|
||||
"""
|
||||
@spec cd(Path.t()) :: :ok | {:error, posix}
|
||||
@@ -1620,7 +1610,7 @@ defmodule File do
|
||||
in raw mode for performance reasons. Therefore, Elixir **will** open
|
||||
streams in `:raw` mode with the `:read_ahead` option unless an encoding
|
||||
is specified. This means any data streamed into the file must be
|
||||
converted to `t:iodata/0` type. If you pass, for example, `[encoding: :utf8]`
|
||||
converted to `t:iodata/0` type. If you pass e.g. `[encoding: :utf8]`
|
||||
or `[encoding: {:utf16, :little}]` in the modes parameter,
|
||||
the underlying stream will use `IO.write/2` and the `String.Chars` protocol
|
||||
to convert the data. See `IO.binwrite/2` and `IO.write/2` .
|
||||
@@ -1645,7 +1635,7 @@ defmodule File do
|
||||
|
||||
See `Stream.run/1` for an example of streaming into a file.
|
||||
"""
|
||||
@spec stream!(Path.t(), [stream_mode], :line | pos_integer) :: File.Stream.t()
|
||||
@spec stream!(Path.t(), stream_mode, :line | pos_integer) :: File.Stream.t()
|
||||
def stream!(path, modes \\ [], line_or_bytes \\ :line) do
|
||||
modes = normalize_modes(modes, true)
|
||||
File.Stream.__build__(IO.chardata_to_string(path), modes, line_or_bytes)
|
||||
|
||||
@@ -23,7 +23,7 @@ defmodule File.Stat do
|
||||
* `mtime` - the last time the file was written.
|
||||
|
||||
* `ctime` - the interpretation of this time field depends on the operating
|
||||
system. On Unix-like operating systems, it is the last time the file or the inode was changed.
|
||||
system. On Unix, it is the last time the file or the inode was changed.
|
||||
In Windows, it is the time of creation.
|
||||
|
||||
* `mode` - the file permissions.
|
||||
@@ -35,17 +35,17 @@ defmodule File.Stat do
|
||||
In Windows, the number indicates a drive as follows: 0 means A:, 1 means
|
||||
B:, and so on.
|
||||
|
||||
* `minor_device` - only valid for character devices on Unix-like systems. In all other
|
||||
* `minor_device` - only valid for character devices on Unix. In all other
|
||||
cases, this field is zero.
|
||||
|
||||
* `inode` - gives the inode number. On non-Unix-like file systems, this field
|
||||
* `inode` - gives the inode number. On non-Unix file systems, this field
|
||||
will be zero.
|
||||
|
||||
* `uid` - indicates the owner of the file. Will be zero for non-Unix-like file
|
||||
* `uid` - indicates the owner of the file. Will be zero for non-Unix file
|
||||
systems.
|
||||
|
||||
* `gid` - indicates the group that owns the file. Will be zero for
|
||||
non-Unix-like file systems.
|
||||
non-Unix file systems.
|
||||
|
||||
The time type returned in `atime`, `mtime`, and `ctime` is dependent on the
|
||||
time type set in options. `{:time, type}` where type can be `:local`,
|
||||
|
||||
@@ -2,59 +2,11 @@ defmodule Function do
|
||||
@moduledoc """
|
||||
A set of functions for working with functions.
|
||||
|
||||
Anonymous functions are typically created by using `fn`:
|
||||
|
||||
iex> add = fn a, b -> a + b end
|
||||
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
|
||||
|
||||
## The capture operator
|
||||
|
||||
It is also possible to capture public module functions and pass them
|
||||
around as if they were anonymous functions by using the capture
|
||||
operator `Kernel.SpecialForms.&/1`:
|
||||
|
||||
iex> add = &Kernel.+/2
|
||||
iex> add.(1, 2)
|
||||
3
|
||||
|
||||
iex> length = &String.length/1
|
||||
iex> length.("hello")
|
||||
5
|
||||
|
||||
To capture a definition within the current module, you can skip the
|
||||
module prefix, such as `&my_fun/2`. In those cases, the captured
|
||||
function can be public (`def`) or private (`defp`).
|
||||
|
||||
The capture operator can also be used to create anonymous functions
|
||||
that expect at least one argument:
|
||||
|
||||
iex> add = &(&1 + &2)
|
||||
iex> add.(1, 2)
|
||||
3
|
||||
|
||||
In such cases, using the capture operator is no different than using `fn`.
|
||||
|
||||
## Internal and external functions
|
||||
|
||||
We say that functions that point to definitions residing in modules, such
|
||||
as `&String.length/1`, are **external** functions. All other functions are
|
||||
**local** and they are always bound to the file or module that defined them.
|
||||
|
||||
Besides the functions in this module to work with functions, `Kernel` also
|
||||
has an `apply/2` function that invokes a function with a dynamic number of
|
||||
arguments, as well as `is_function/1` and `is_function/2`, to check
|
||||
respectively if a given value is a function or a function of a given arity.
|
||||
There are two types of captured functions: **external** and **local**.
|
||||
External functions are functions residing in modules that are captured
|
||||
with `&/1`, such as `&String.length/1`. Local functions are anonymous functions
|
||||
defined with `fn/1` or with the capture operator `&/1` using `&1`, `&2`,
|
||||
and so on as replacements.
|
||||
"""
|
||||
|
||||
@type information ::
|
||||
@@ -182,27 +134,4 @@ defmodule Function do
|
||||
@doc since: "1.7.0"
|
||||
@spec info(fun, item) :: {item, term} when item: information
|
||||
def info(fun, item), do: :erlang.fun_info(fun, item)
|
||||
|
||||
@doc """
|
||||
Returns its input `value`. This function can be passed as an anonymous function
|
||||
to transformation functions.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Function.identity("Hello world!")
|
||||
"Hello world!"
|
||||
|
||||
iex> 'abcdaabccc' |> Enum.sort() |> Enum.chunk_by(&Function.identity/1)
|
||||
['aaa', 'bb', 'cccc', 'd']
|
||||
|
||||
iex> Enum.group_by('abracadabra', &Function.identity/1)
|
||||
%{97 => 'aaaaa', 98 => 'bb', 99 => 'c', 100 => 'd', 114 => 'rr'}
|
||||
|
||||
iex> Enum.map([1, 2, 3, 4], &Function.identity/1)
|
||||
[1, 2, 3, 4]
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec identity(value) :: value when value: var
|
||||
def identity(value), do: value
|
||||
end
|
||||
|
||||
@@ -7,7 +7,7 @@ defmodule GenEvent do
|
||||
If you are interested in implementing an event manager, please read the
|
||||
"Alternatives" section below. If you have to implement an event handler to
|
||||
integrate with an existing system, such as Elixir's Logger, please use
|
||||
[`:gen_event`](https://erlang.org/doc/man/gen_event.html) instead.
|
||||
`:gen_event` instead.
|
||||
|
||||
## Alternatives
|
||||
|
||||
|
||||
@@ -280,10 +280,6 @@ defmodule GenServer do
|
||||
GenServer.call(__MODULE__, {:add, a, b})
|
||||
end
|
||||
|
||||
def subtract(a, b) do
|
||||
GenServer.call(__MODULE__, {:subtract, a, b})
|
||||
end
|
||||
|
||||
def handle_call({:add, a, b}, _from, state) do
|
||||
{:reply, a + b, state}
|
||||
end
|
||||
@@ -633,7 +629,7 @@ defmodule GenServer do
|
||||
Therefore it is not guaranteed that `c:terminate/2` is called when a `GenServer`
|
||||
exits. For such reasons, we usually recommend important clean-up rules to
|
||||
happen in separated processes either by use of monitoring or by links
|
||||
themselves. There is no cleanup needed when the `GenServer` controls a `port` (for example,
|
||||
themselves. There is no cleanup needed when the `GenServer` controls a `port` (e.g.
|
||||
`:gen_tcp.socket`) or `t:File.io_device/0`, because these will be closed on
|
||||
receiving a `GenServer`'s exit signal and do not need to be closed manually
|
||||
in `c:terminate/2`.
|
||||
@@ -644,7 +640,7 @@ defmodule GenServer do
|
||||
This callback is optional.
|
||||
"""
|
||||
@callback terminate(reason, state :: term) :: term
|
||||
when reason: :normal | :shutdown | {:shutdown, term} | term
|
||||
when reason: :normal | :shutdown | {:shutdown, term}
|
||||
|
||||
@doc """
|
||||
Invoked to change the state of the `GenServer` when a different version of a
|
||||
@@ -741,7 +737,7 @@ defmodule GenServer do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@behaviour GenServer
|
||||
|
||||
unless Module.has_attribute?(__MODULE__, :doc) do
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
@@ -789,22 +785,8 @@ defmodule GenServer do
|
||||
{_, name} -> name
|
||||
end
|
||||
|
||||
:logger.error(
|
||||
%{
|
||||
label: {GenServer, :no_handle_info},
|
||||
report: %{
|
||||
module: __MODULE__,
|
||||
message: msg,
|
||||
name: proc
|
||||
}
|
||||
},
|
||||
%{
|
||||
domain: [:otp, :elixir],
|
||||
error_logger: %{tag: :error_msg},
|
||||
report_cb: &GenServer.format_report/1
|
||||
}
|
||||
)
|
||||
|
||||
pattern = '~p ~p received unexpected message in handle_info/2: ~p~n'
|
||||
:error_logger.error_msg(pattern, [__MODULE__, proc, msg])
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
@@ -1181,11 +1163,8 @@ defmodule GenServer do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the `pid` or `{name, node}` of a GenServer process, `nil` otherwise.
|
||||
|
||||
To be precise, `nil` is returned whenever a `pid` or `{name, node}` cannot
|
||||
be returned. Note there is no guarantee the returned `pid` or `{name, node}`
|
||||
is alive, as a process could terminate immediately after it is looked up.
|
||||
Returns the `pid` or `{name, node}` of a GenServer process, or `nil` if
|
||||
no process is associated with the given `server`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1226,12 +1205,4 @@ defmodule GenServer do
|
||||
def whereis({name, node} = server) when is_atom(name) and is_atom(node) do
|
||||
server
|
||||
end
|
||||
|
||||
@doc false
|
||||
def format_report(%{
|
||||
label: {GenServer, :no_handle_info},
|
||||
report: %{module: mod, message: msg, name: proc}
|
||||
}) do
|
||||
{'~p ~p received unexpected message in handle_info/2: ~p~n', [mod, proc, msg]}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -48,8 +48,8 @@ defmodule HashDict do
|
||||
end
|
||||
|
||||
@deprecated message
|
||||
def update(%HashDict{root: root, size: size}, key, default, fun) when is_function(fun, 1) do
|
||||
{root, counter} = do_update(root, key, fn -> default end, fun, key_hash(key))
|
||||
def update(%HashDict{root: root, size: size}, key, initial, fun) when is_function(fun, 1) do
|
||||
{root, counter} = do_update(root, key, fn -> initial end, fun, key_hash(key))
|
||||
%HashDict{root: root, size: size + counter}
|
||||
end
|
||||
|
||||
@@ -135,25 +135,25 @@ defmodule HashDict do
|
||||
end
|
||||
end
|
||||
|
||||
defp do_update(node, key, default, fun, hash) do
|
||||
defp do_update(node, key, initial, fun, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] ->
|
||||
{put_elem(node, index, [key | default.()]), 1}
|
||||
{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 | default.()])
|
||||
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, default, fun, key_shift(hash))
|
||||
{n, counter} = do_update(n, key, initial, fun, key_shift(hash))
|
||||
{put_elem(node, index, {k, v, n}), counter}
|
||||
end
|
||||
end
|
||||
|
||||
+25
-43
@@ -31,17 +31,16 @@ defprotocol Inspect do
|
||||
end
|
||||
end
|
||||
|
||||
The [`concat/1`](`Inspect.Algebra.concat/1`) function comes from
|
||||
`Inspect.Algebra` and it concatenates algebra documents together.
|
||||
In the example above it is concatenating the string `"#MapSet<"`,
|
||||
the document returned by `Inspect.Algebra.to_doc/2`, and the final
|
||||
string `">"`. We prefix the module name `#` to denote the inspect
|
||||
presentation is not actually valid Elixir syntax.
|
||||
The [`concat/1`](`Inspect.Algebra.concat/1`) function comes from `Inspect.Algebra` and it
|
||||
concatenates algebra documents together. In the example above,
|
||||
it is concatenating the string `"MapSet<"` (all strings are
|
||||
valid algebra documents that keep their formatting when pretty
|
||||
printed), the document returned by `Inspect.Algebra.to_doc/2` and the
|
||||
other string `">"`.
|
||||
|
||||
Finally, note strings themselves are valid algebra documents that
|
||||
keep their formatting when pretty printed. This means your `Inspect`
|
||||
implementation may simply return a string, although that will devoid
|
||||
it of any pretty-printing.
|
||||
Since regular strings are valid entities in an algebra document,
|
||||
an implementation of the `Inspect` protocol may simply return a
|
||||
string, although that will devoid it of any pretty-printing.
|
||||
|
||||
## Error handling
|
||||
|
||||
@@ -254,7 +253,7 @@ defimpl Inspect, for: Map do
|
||||
end
|
||||
|
||||
def inspect(map, name, opts) do
|
||||
map = Map.to_list(map)
|
||||
map = :maps.to_list(map)
|
||||
open = color("%" <> name <> "{", :map, opts)
|
||||
sep = color(",", :map, opts)
|
||||
close = color("}", :map, opts)
|
||||
@@ -410,7 +409,11 @@ end
|
||||
|
||||
defimpl Inspect, for: Any do
|
||||
defmacro __deriving__(module, struct, options) do
|
||||
fields = Map.keys(struct) -- [:__exception__, :__struct__]
|
||||
fields =
|
||||
struct
|
||||
|> Map.drop([:__exception__, :__struct__])
|
||||
|> Map.keys()
|
||||
|
||||
only = Keyword.get(options, :only, fields)
|
||||
except = Keyword.get(options, :except, [])
|
||||
|
||||
@@ -421,17 +424,17 @@ defimpl Inspect, for: Any do
|
||||
|
||||
inspect_module =
|
||||
if fields == only and except == [] do
|
||||
Inspect.Map
|
||||
quote(do: Inspect.Map)
|
||||
else
|
||||
Inspect.Any
|
||||
quote(do: Inspect.Any)
|
||||
end
|
||||
|
||||
quote do
|
||||
defimpl Inspect, for: unquote(module) do
|
||||
def inspect(var!(struct), var!(opts)) do
|
||||
var!(map) = Map.take(var!(struct), unquote(filtered_fields))
|
||||
var!(name) = Identifier.inspect_as_atom(unquote(module))
|
||||
unquote(inspect_module).inspect(var!(map), var!(name), var!(opts))
|
||||
def inspect(struct, opts) do
|
||||
map = Map.take(struct, unquote(filtered_fields))
|
||||
name = Identifier.inspect_as_atom(unquote(module))
|
||||
unquote(inspect_module).inspect(map, name, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -439,13 +442,13 @@ defimpl Inspect, for: Any do
|
||||
|
||||
def inspect(%module{} = struct, opts) do
|
||||
try do
|
||||
module.__struct__()
|
||||
module.__struct__
|
||||
rescue
|
||||
_ -> Inspect.Map.inspect(struct, opts)
|
||||
else
|
||||
dunder ->
|
||||
if Map.keys(dunder) == Map.keys(struct) do
|
||||
pruned = Map.drop(struct, [:__struct__, :__exception__])
|
||||
if :maps.keys(dunder) == :maps.keys(struct) do
|
||||
pruned = :maps.remove(:__exception__, :maps.remove(:__struct__, struct))
|
||||
Inspect.Map.inspect(pruned, Identifier.inspect_as_atom(module), opts)
|
||||
else
|
||||
Inspect.Map.inspect(struct, opts)
|
||||
@@ -457,7 +460,7 @@ defimpl Inspect, for: Any do
|
||||
# Use the :limit option and an extra element to force
|
||||
# `container_doc/6` to append "...".
|
||||
opts = %{opts | limit: min(opts.limit, map_size(map))}
|
||||
map = Map.to_list(map) ++ ["..."]
|
||||
map = :maps.to_list(map) ++ ["..."]
|
||||
|
||||
open = color("#" <> name <> "<", :map, opts)
|
||||
sep = color(",", :map, opts)
|
||||
@@ -466,24 +469,3 @@ defimpl Inspect, for: Any do
|
||||
container_doc(open, map, close, opts, &Inspect.List.keyword/2, separator: sep, break: :strict)
|
||||
end
|
||||
end
|
||||
|
||||
require Protocol
|
||||
|
||||
Protocol.derive(
|
||||
Inspect,
|
||||
Macro.Env,
|
||||
only: [
|
||||
:module,
|
||||
:file,
|
||||
:line,
|
||||
:function,
|
||||
:context,
|
||||
:aliases,
|
||||
:requires,
|
||||
:functions,
|
||||
:macros,
|
||||
:macro_aliases,
|
||||
:context_modules,
|
||||
:lexical_tracker
|
||||
]
|
||||
)
|
||||
|
||||
@@ -4,15 +4,13 @@ defmodule Inspect.Opts do
|
||||
|
||||
The following fields are available:
|
||||
|
||||
* `:base` - prints integers as `:binary`, `:octal`, `:decimal`, or `:hex`,
|
||||
defaults to `:decimal`. When inspecting binaries any `:base` other than
|
||||
`:decimal` implies `binaries: :as_binaries`.
|
||||
* `:structs` - when `false`, structs are not formatted by the inspect
|
||||
protocol, they are instead printed as maps, defaults to `true`.
|
||||
|
||||
* `:binaries` - when `:as_binaries` all binaries will be printed in bit
|
||||
syntax.
|
||||
* `:binaries` - when `:as_strings` all binaries will be printed as strings,
|
||||
non-printable bytes will be escaped.
|
||||
|
||||
When `:as_strings` all binaries will be printed as strings, non-printable
|
||||
bytes will be escaped.
|
||||
When `:as_binaries` all binaries will be printed in bit syntax.
|
||||
|
||||
When the default `:infer`, the binary will be printed as a string if it
|
||||
is printable, otherwise in bit syntax. See `String.printable?/1` to learn
|
||||
@@ -27,83 +25,81 @@ defmodule Inspect.Opts do
|
||||
is printable, otherwise as list. See `List.ascii_printable?/1` to learn
|
||||
when a charlist is printable.
|
||||
|
||||
* `:custom_options` (since v1.9.0) - a keyword list storing custom user-defined
|
||||
options. Useful when implementing the `Inspect` protocol for nested structs
|
||||
to pass the custom options through.
|
||||
|
||||
* `:inspect_fun` (since v1.9.0) - a function to build algebra documents.
|
||||
Defaults to `Inspect.inspect/2`.
|
||||
|
||||
* `:limit` - limits the number of items that are inspected for tuples,
|
||||
bitstrings, maps, lists and any other collection of items, with the exception of
|
||||
printable strings and printable charlists which use the `:printable_limit` option.
|
||||
bitstrings, maps, lists and any other collection of items. It does not
|
||||
apply to printable strings nor printable charlists and defaults to 50.
|
||||
If you don't want to limit the number of items to a particular number,
|
||||
use `:infinity`. It accepts a positive integer or `:infinity`.
|
||||
Defaults to `50`.
|
||||
|
||||
* `:pretty` - if set to `true` enables pretty printing. Defaults to `false`.
|
||||
use `:infinity`.
|
||||
|
||||
* `:printable_limit` - limits the number of characters that are inspected
|
||||
on printable strings and printable charlists. You can use `String.printable?/1`
|
||||
and `List.ascii_printable?/1` to check if a given string or charlist is
|
||||
printable. If you don't want to limit the number of characters to a particular
|
||||
number, use `:infinity`. It accepts a positive integer or `:infinity`.
|
||||
Defaults to `4096`.
|
||||
printable. Defaults to 4096. If you don't want to limit the number of
|
||||
characters to a particular number, use `:infinity`.
|
||||
|
||||
* `:pretty` - if set to `true` enables pretty printing, defaults to `false`.
|
||||
|
||||
* `:width` - defaults to 80 characters, used when pretty is `true` or when
|
||||
printing to IO devices. Set to 0 to force each item to be printed on its
|
||||
own line. If you don't want to limit the number of items to a particular
|
||||
number, use `:infinity`.
|
||||
|
||||
* `:base` - prints integers as `:binary`, `:octal`, `:decimal`, or `:hex`,
|
||||
defaults to `:decimal`. When inspecting binaries any `:base` other than
|
||||
`:decimal` implies `binaries: :as_binaries`.
|
||||
|
||||
* `:safe` - when `false`, failures while inspecting structs will be raised
|
||||
as errors instead of being wrapped in the `Inspect.Error` exception. This
|
||||
is useful when debugging failures and crashes for custom inspect
|
||||
implementations.
|
||||
|
||||
* `:structs` - when `false`, structs are not formatted by the inspect
|
||||
protocol, they are instead printed as maps. Defaults to `true`.
|
||||
|
||||
* `:syntax_colors` - when set to a keyword list of colors the output is
|
||||
colorized. The keys are types and the values are the colors to use for
|
||||
each type (for example, `[number: :red, atom: :blue]`). Types can include
|
||||
`:atom`, `:binary`, `:boolean`, `:list`, `:map`, `:number`, `:regex`,
|
||||
`:string`, and `:tuple`. Custom data types may provide their own options.
|
||||
`:number`, `:atom`, `regex`, `:tuple`, `:map`, `:list`, and `:reset`.
|
||||
Colors can be any `t:IO.ANSI.ansidata/0` as accepted by `IO.ANSI.format/1`.
|
||||
|
||||
* `:width` - number of characters per line used when pretty is `true` or when
|
||||
printing to IO devices. Set to `0` to force each item to be printed on its
|
||||
own line. If you don't want to limit the number of items to a particular
|
||||
number, use `:infinity`. Defaults to `80`.
|
||||
* `:inspect_fun` (since v1.9.0) - a function to build algebra documents,
|
||||
defaults to `Inspect.inspect/2`
|
||||
|
||||
* `:custom_options` (since v1.9.0) - a keyword list storing custom user-defined
|
||||
options. Useful when implementing the `Inspect` protocol for nested structs
|
||||
to pass the custom options through.
|
||||
|
||||
"""
|
||||
|
||||
# TODO: Remove :char_lists key on v2.0
|
||||
defstruct base: :decimal,
|
||||
defstruct structs: true,
|
||||
binaries: :infer,
|
||||
char_lists: :infer,
|
||||
charlists: :infer,
|
||||
custom_options: [],
|
||||
inspect_fun: &Inspect.inspect/2,
|
||||
char_lists: :infer,
|
||||
limit: 50,
|
||||
pretty: false,
|
||||
printable_limit: 4096,
|
||||
width: 80,
|
||||
base: :decimal,
|
||||
pretty: false,
|
||||
safe: true,
|
||||
structs: true,
|
||||
syntax_colors: [],
|
||||
width: 80
|
||||
inspect_fun: &Inspect.inspect/2,
|
||||
custom_options: []
|
||||
|
||||
@type color_key :: atom
|
||||
|
||||
# TODO: Remove :char_lists key and :as_char_lists value on v2.0
|
||||
@type t :: %__MODULE__{
|
||||
base: :decimal | :binary | :hex | :octal,
|
||||
binaries: :infer | :as_binaries | :as_strings,
|
||||
char_lists: :infer | :as_lists | :as_char_lists,
|
||||
charlists: :infer | :as_lists | :as_charlists,
|
||||
custom_options: keyword,
|
||||
inspect_fun: (any, t -> Inspect.Algebra.t()),
|
||||
limit: non_neg_integer | :infinity,
|
||||
pretty: boolean,
|
||||
printable_limit: non_neg_integer | :infinity,
|
||||
safe: boolean,
|
||||
structs: boolean,
|
||||
binaries: :infer | :as_binaries | :as_strings,
|
||||
charlists: :infer | :as_lists | :as_charlists,
|
||||
char_lists: :infer | :as_lists | :as_char_lists,
|
||||
limit: pos_integer | :infinity,
|
||||
printable_limit: pos_integer | :infinity,
|
||||
width: pos_integer | :infinity,
|
||||
base: :decimal | :binary | :hex | :octal,
|
||||
pretty: boolean,
|
||||
safe: boolean,
|
||||
syntax_colors: [{color_key, IO.ANSI.ansidata()}],
|
||||
width: non_neg_integer | :infinity
|
||||
inspect_fun: (any, t -> Inspect.Algebra.t()),
|
||||
custom_options: keyword
|
||||
}
|
||||
end
|
||||
|
||||
@@ -150,7 +146,7 @@ defmodule Inspect.Algebra do
|
||||
iex> Inspect.Algebra.format(doc, 80)
|
||||
["a", " ", "b"]
|
||||
|
||||
Note that the break was represented as is, because we haven't reached
|
||||
Notice the break was represented as is, because we haven't reached
|
||||
a line limit. Once we do, it is replaced by a newline:
|
||||
|
||||
iex> doc = Inspect.Algebra.glue(String.duplicate("a", 20), " ", "b")
|
||||
@@ -195,17 +191,17 @@ defmodule Inspect.Algebra do
|
||||
|
||||
@type t ::
|
||||
binary
|
||||
| :doc_line
|
||||
| :doc_nil
|
||||
| doc_break
|
||||
| doc_collapse
|
||||
| doc_color
|
||||
| doc_cons
|
||||
| doc_fits
|
||||
| doc_force
|
||||
| doc_group
|
||||
| doc_nest
|
||||
| :doc_line
|
||||
| doc_string
|
||||
| doc_cons
|
||||
| doc_nest
|
||||
| doc_break
|
||||
| doc_group
|
||||
| doc_color
|
||||
| doc_force
|
||||
| doc_fits
|
||||
| doc_collapse
|
||||
|
||||
@typep doc_string :: {:doc_string, t, non_neg_integer}
|
||||
defmacrop doc_string(string, length) do
|
||||
@@ -253,24 +249,21 @@ defmodule Inspect.Algebra do
|
||||
end
|
||||
|
||||
@docs [
|
||||
:doc_break,
|
||||
:doc_collapse,
|
||||
:doc_color,
|
||||
:doc_string,
|
||||
:doc_cons,
|
||||
:doc_fits,
|
||||
:doc_force,
|
||||
:doc_group,
|
||||
:doc_nest,
|
||||
:doc_string
|
||||
:doc_break,
|
||||
:doc_group,
|
||||
:doc_color,
|
||||
:doc_force,
|
||||
:doc_fits,
|
||||
:doc_collapse
|
||||
]
|
||||
|
||||
defguard is_doc(doc)
|
||||
when is_binary(doc) or doc in [:doc_nil, :doc_line] or
|
||||
(is_tuple(doc) and elem(doc, 0) in @docs)
|
||||
|
||||
defguardp is_limit(limit) when limit == :infinity or (is_integer(limit) and limit >= 0)
|
||||
defguardp is_width(limit) when limit == :infinity or (is_integer(limit) and limit >= 0)
|
||||
|
||||
# Elixir + Inspect.Opts conveniences
|
||||
|
||||
@doc """
|
||||
@@ -402,14 +395,13 @@ defmodule Inspect.Algebra do
|
||||
{:lists.reverse(["..." | acc]), simple?}
|
||||
end
|
||||
|
||||
defp container_each([term | terms], limit, opts, fun, acc, simple?)
|
||||
when is_list(terms) and is_limit(limit) do
|
||||
defp container_each([term | terms], limit, opts, fun, acc, simple?) when is_list(terms) do
|
||||
limit = decrement(limit)
|
||||
doc = fun.(term, %{opts | limit: limit})
|
||||
container_each(terms, limit, opts, fun, [doc | acc], simple? and simple?(doc))
|
||||
end
|
||||
|
||||
defp container_each([left | right], limit, opts, fun, acc, simple?) when is_limit(limit) do
|
||||
defp container_each([left | right], limit, opts, fun, acc, simple?) do
|
||||
limit = decrement(limit)
|
||||
left = fun.(left, %{opts | limit: limit})
|
||||
right = fun.(right, %{opts | limit: limit})
|
||||
@@ -601,7 +593,7 @@ defmodule Inspect.Algebra do
|
||||
iex> Inspect.Algebra.format(doc, 80)
|
||||
["a", "\t", "b"]
|
||||
|
||||
Note that the break was represented with the given string, because we didn't
|
||||
Notice the break was represented with the given string, because we didn't
|
||||
reach a line limit. Once we do, it is replaced by a newline:
|
||||
|
||||
iex> break = Inspect.Algebra.break("\t")
|
||||
@@ -890,7 +882,7 @@ defmodule Inspect.Algebra do
|
||||
|
||||
"""
|
||||
@spec format(t, non_neg_integer | :infinity) :: iodata
|
||||
def format(doc, width) when is_doc(doc) and is_width(width) do
|
||||
def format(doc, width) when is_doc(doc) and (width == :infinity or width >= 0) do
|
||||
format(width, 0, [{0, :flat, doc}])
|
||||
end
|
||||
|
||||
@@ -906,12 +898,7 @@ defmodule Inspect.Algebra do
|
||||
#
|
||||
@typep mode :: :flat | :flat_no_break | :break | :break_no_flat
|
||||
|
||||
@spec fits?(
|
||||
width :: non_neg_integer(),
|
||||
column :: non_neg_integer(),
|
||||
break? :: boolean(),
|
||||
entries
|
||||
) :: boolean()
|
||||
@spec fits?(width :: integer(), column :: integer(), break? :: boolean(), entries) :: boolean()
|
||||
when entries:
|
||||
maybe_improper_list({integer(), mode(), t()}, {:tail, boolean(), entries} | [])
|
||||
|
||||
@@ -972,9 +959,7 @@ defmodule Inspect.Algebra do
|
||||
defp fits?(w, k, b?, [{i, m, doc_group(x, _)} | t]),
|
||||
do: fits?(w, k, b?, [{i, m, x} | {:tail, b?, t}])
|
||||
|
||||
@spec format(width :: non_neg_integer() | :infinity, column :: non_neg_integer(), [
|
||||
{integer, mode, t}
|
||||
]) :: [binary]
|
||||
@spec format(integer | :infinity, integer, [{integer, mode, t}]) :: [binary]
|
||||
defp format(_, _, []), do: []
|
||||
defp format(w, k, [{_, _, :doc_nil} | t]), do: format(w, k, t)
|
||||
defp format(w, _, [{i, _, :doc_line} | t]), do: [indent(i) | format(w, i, t)]
|
||||
|
||||
@@ -233,7 +233,7 @@ defmodule Integer do
|
||||
raise ArgumentError, "invalid base #{inspect(base)}"
|
||||
end
|
||||
|
||||
def parse(binary, base) when is_binary(binary) do
|
||||
def parse(binary, base) do
|
||||
case count_digits(binary, base) do
|
||||
0 ->
|
||||
:error
|
||||
@@ -244,14 +244,14 @@ defmodule Integer do
|
||||
end
|
||||
end
|
||||
|
||||
defp count_digits(<<sign, rest::bits>>, base) when sign in '+-' do
|
||||
defp count_digits(<<sign, rest::binary>>, base) when sign in '+-' do
|
||||
case count_digits_nosign(rest, base, 1) do
|
||||
1 -> 0
|
||||
count -> count
|
||||
end
|
||||
end
|
||||
|
||||
defp count_digits(<<rest::bits>>, base) do
|
||||
defp count_digits(<<rest::binary>>, base) do
|
||||
count_digits_nosign(rest, base, 0)
|
||||
end
|
||||
|
||||
@@ -261,13 +261,13 @@ defmodule Integer do
|
||||
char <- chars do
|
||||
digit = char + diff
|
||||
|
||||
defp count_digits_nosign(<<unquote(char), rest::bits>>, base, count)
|
||||
defp count_digits_nosign(<<unquote(char), rest::binary>>, base, count)
|
||||
when base > unquote(digit) do
|
||||
count_digits_nosign(rest, base, count + 1)
|
||||
end
|
||||
end
|
||||
|
||||
defp count_digits_nosign(<<_::bits>>, _, count), do: count
|
||||
defp count_digits_nosign(<<_::binary>>, _, count), do: count
|
||||
|
||||
# TODO: Remove Integer.to_string/1 once the minimum supported version is
|
||||
# Erlang/OTP 22, since it is covered by the now BIF Integer.to_string/2.
|
||||
|
||||
+12
-44
@@ -84,7 +84,7 @@ defmodule IO do
|
||||
Building IO data is cheaper than concatenating binaries. Concatenating multiple
|
||||
pieces of IO data just means putting them together inside a list since IO data
|
||||
can be arbitrarily nested, and that's a cheap and efficient operation. Most of
|
||||
the IO-based APIs, such as `:gen_tcp` and `IO`, receive IO data and write it
|
||||
the IO-based APIs, such as `:gen_tcp`, `IO`, etc, receive IO data and write it
|
||||
to the socket directly without converting it to binary.
|
||||
|
||||
One drawback of IO data is that you can't do things like pattern match on the
|
||||
@@ -98,14 +98,14 @@ defmodule IO do
|
||||
|
||||
Erlang and Elixir also have the idea of `t:chardata/0`. Chardata is very
|
||||
similar to IO data: the only difference is that integers in IO data represent
|
||||
bytes while integers in chardata represent Unicode code points. Bytes
|
||||
(`t:byte/0`) are integers in the `0..255` range, while Unicode code points
|
||||
bytes while integers in chardata represent Unicode codepoints. Bytes
|
||||
(`t:byte/0`) are integers in the `0..255` range, while Unicode codepoints
|
||||
(`t:char/0`) are integers in the range `0..0x10FFFF`. The `IO` module provides
|
||||
the `chardata_to_string/1` function for chardata as the "counter-part" of the
|
||||
`iodata_to_binary/1` function for IO data.
|
||||
|
||||
If you try to use `iodata_to_binary/1` on chardata, it will result in an
|
||||
argument error. For example, let's try to put a code point that is not
|
||||
argument error. For example, let's try to put a codepoint that is not
|
||||
representable with one byte, like `?π`, inside IO data:
|
||||
|
||||
iex> IO.iodata_to_binary(["The symbol for pi is: ", ?π])
|
||||
@@ -148,7 +148,7 @@ defmodule IO do
|
||||
def read(device \\ :stdio, line_or_chars)
|
||||
|
||||
def read(device, :all) do
|
||||
do_read_all(map_dev(device), :empty)
|
||||
do_read_all(map_dev(device), "")
|
||||
end
|
||||
|
||||
def read(device, :line) do
|
||||
@@ -161,27 +161,12 @@ defmodule IO do
|
||||
|
||||
defp do_read_all(mapped_dev, acc) do
|
||||
case :io.get_line(mapped_dev, "") do
|
||||
line when is_binary(line) or is_list(line) -> do_read_all(mapped_dev, concat(acc, line))
|
||||
:eof -> read_eof(mapped_dev, acc)
|
||||
line when is_binary(line) -> do_read_all(mapped_dev, acc <> line)
|
||||
:eof -> acc
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
|
||||
defp concat(:empty, line), do: line
|
||||
defp concat(acc, line) when is_binary(acc), do: acc <> line
|
||||
defp concat(acc, line) when is_list(acc), do: acc ++ line
|
||||
|
||||
defp read_eof(device, :empty) do
|
||||
with [_ | _] = opts <- :io.getopts(device),
|
||||
false <- Keyword.get(opts, :binary, true) do
|
||||
''
|
||||
else
|
||||
_ -> ""
|
||||
end
|
||||
end
|
||||
|
||||
defp read_eof(_device, acc), do: acc
|
||||
|
||||
@doc """
|
||||
Reads from the IO `device`. The operation is Unicode unsafe.
|
||||
|
||||
@@ -317,7 +302,7 @@ defmodule IO do
|
||||
@spec warn(chardata | String.Chars.t(), Exception.stacktrace()) :: :ok
|
||||
def warn(message, []) do
|
||||
message = [to_chardata(message), ?\n]
|
||||
:elixir_errors.io_warn(0, nil, message, message)
|
||||
:elixir_errors.io_warn(nil, nil, message, message)
|
||||
end
|
||||
|
||||
def warn(message, [{_, _, _, opts} | _] = stacktrace) do
|
||||
@@ -327,35 +312,18 @@ defmodule IO do
|
||||
file = opts[:file]
|
||||
|
||||
:elixir_errors.io_warn(
|
||||
line || 0,
|
||||
line,
|
||||
file && List.to_string(file),
|
||||
message,
|
||||
[message, ?\n, " ", formatted_trace, ?\n]
|
||||
)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def warn_once(key, message, stacktrace_drop_levels) do
|
||||
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
|
||||
stacktrace = Enum.drop(stacktrace, stacktrace_drop_levels)
|
||||
|
||||
if :elixir_config.warn(key, stacktrace) do
|
||||
warn(message, stacktrace)
|
||||
else
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Writes a `message` to stderr, along with the current stacktrace.
|
||||
|
||||
It returns `:ok` if it succeeds.
|
||||
|
||||
Do not call this function at the tail of another function. Due to tail
|
||||
call optimization, a stacktrace entry would not be added and the
|
||||
stacktrace would be incorrectly trimmed. Therefore make sure at least
|
||||
one expression (or an atom such as `:ok`) follows the `IO.warn/1` call.
|
||||
|
||||
## Examples
|
||||
|
||||
IO.warn("variable bar is unused")
|
||||
@@ -447,8 +415,8 @@ defmodule IO do
|
||||
See `IO.getn/3` for a description of return values.
|
||||
|
||||
"""
|
||||
@spec getn(device | chardata | String.Chars.t(), pos_integer | 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
|
||||
@@ -599,7 +567,7 @@ defmodule IO do
|
||||
|
||||
The operation is Unicode unsafe.
|
||||
|
||||
Note that this function treats integers in the given IO data as
|
||||
Notice that this function treats integers in the given IO data as
|
||||
raw bytes and does not perform any kind of encoding conversion.
|
||||
If you want to convert from a charlist to a UTF-8-encoded string,
|
||||
use `chardata_to_string/1` instead. For more information about
|
||||
|
||||
@@ -21,31 +21,6 @@ defmodule IO.ANSI do
|
||||
[ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code)
|
||||
are characters embedded in text used to control formatting, color, and
|
||||
other output options on video text terminals.
|
||||
|
||||
ANSI escapes are typically enabled on all Unix terminals. They are also
|
||||
available on Windows consoles from Windows 10, although it must be
|
||||
explicitly enabled for the current user in the registry by running the
|
||||
following command:
|
||||
|
||||
reg add HKCU\\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
|
||||
|
||||
After running the command above, you must restart your current console.
|
||||
|
||||
## Examples
|
||||
|
||||
Because the ANSI escape sequences are embedded in text, the normal usage of
|
||||
these functions is to concatenate their output with text.
|
||||
|
||||
formatted_text = IO.ANSI.blue_background() <> "Example" <> IO.ANSI.reset()
|
||||
IO.puts(formatted_text)
|
||||
|
||||
A higher level and more convenient API is also available via `IO.ANSI.format/1`,
|
||||
where you use atoms to represent each ANSI escape sequence and by default
|
||||
checks if ANSI is enabled:
|
||||
|
||||
IO.puts(IO.ANSI.format([:blue_background, "Example"]))
|
||||
|
||||
In case ANSI is disabled, the ANSI escape sequences are simply discarded.
|
||||
"""
|
||||
|
||||
import IO.ANSI.Sequence
|
||||
|
||||
+56
-336
@@ -1,7 +1,6 @@
|
||||
defmodule IO.ANSI.Docs do
|
||||
@moduledoc false
|
||||
|
||||
@bullet_text "• "
|
||||
@bullets [?*, ?-, ?+]
|
||||
@spaces [" ", "\n", "\t"]
|
||||
|
||||
@@ -15,7 +14,6 @@ defmodule IO.ANSI.Docs do
|
||||
* `:doc_code` - code blocks (cyan)
|
||||
* `:doc_headings` - h1, h2, h3, h4, h5, h6 headings (yellow)
|
||||
* `:doc_metadata` - documentation metadata keys (yellow)
|
||||
* `:doc_quote` - leading quote character `> ` (light black)
|
||||
* `:doc_inline_code` - inline code (cyan)
|
||||
* `:doc_table_heading` - the style for table headings
|
||||
* `:doc_title` - top level heading (reverse, yellow)
|
||||
@@ -33,7 +31,6 @@ defmodule IO.ANSI.Docs do
|
||||
doc_code: [:cyan],
|
||||
doc_headings: [:yellow],
|
||||
doc_metadata: [:yellow],
|
||||
doc_quote: [:light_black],
|
||||
doc_inline_code: [:cyan],
|
||||
doc_table_heading: [:reverse],
|
||||
doc_title: [:reverse, :yellow],
|
||||
@@ -47,20 +44,15 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
See `default_options/0` for docs on the supported options.
|
||||
"""
|
||||
@spec print_headings([String.t()], keyword) :: :ok
|
||||
def print_headings(headings, options \\ []) do
|
||||
@spec print_heading(String.t(), keyword) :: :ok
|
||||
def print_heading(heading, options \\ []) do
|
||||
IO.puts(IO.ANSI.reset())
|
||||
options = Keyword.merge(default_options(), options)
|
||||
newline_after_block(options)
|
||||
width = options[:width]
|
||||
|
||||
for heading <- headings do
|
||||
padding = div(width + String.length(heading), 2)
|
||||
heading = String.pad_leading(heading, padding)
|
||||
heading = if options[:enabled], do: String.pad_trailing(heading, width), else: heading
|
||||
write(:doc_title, heading, options)
|
||||
end
|
||||
|
||||
newline_after_block(options)
|
||||
padding = div(width + String.length(heading), 2)
|
||||
heading = heading |> String.pad_leading(padding) |> String.pad_trailing(width)
|
||||
write(:doc_title, heading, options)
|
||||
newline_after_block()
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -81,14 +73,14 @@ defmodule IO.ANSI.Docs do
|
||||
{key, value}, _printed when is_binary(value) and key in @metadata_filter ->
|
||||
label = metadata_label(key, options)
|
||||
indent = String.duplicate(" ", length_without_escape(label, 0) + 1)
|
||||
write_with_wrap([label | String.split(value, @spaces)], options[:width], indent, true, "")
|
||||
write_with_wrap([label | String.split(value, @spaces)], options[:width], indent, true)
|
||||
|
||||
{key, value}, _printed when is_boolean(value) and key in @metadata_filter ->
|
||||
IO.puts([metadata_label(key, options), ?\s, to_string(value)])
|
||||
IO.puts([metadata_label(key, options), ' ', to_string(value)])
|
||||
|
||||
{:delegate_to, {m, f, a}}, _printed ->
|
||||
label = metadata_label(:delegate_to, options)
|
||||
IO.puts([label, ?\s, Exception.format_mfa(m, f, a)])
|
||||
IO.puts([label, ' ', Exception.format_mfa(m, f, a)])
|
||||
|
||||
_metadata, printed ->
|
||||
printed
|
||||
@@ -96,204 +88,21 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp metadata_label(key, options) do
|
||||
"#{color(:doc_metadata, options)}#{key}:#{maybe_reset(options)}"
|
||||
if options[:enabled] do
|
||||
"#{color(:doc_metadata, options)}#{key}:#{IO.ANSI.reset()}"
|
||||
else
|
||||
"#{key}:"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Prints the documentation body `doc` according to `format`.
|
||||
Prints the documentation body.
|
||||
|
||||
It takes a set of `options` defined in `default_options/0`.
|
||||
In addition to the printing string, takes a set of `options`
|
||||
defined in `default_options/0`.
|
||||
"""
|
||||
@spec print(term(), String.t(), keyword) :: :ok
|
||||
def print(doc, format, options \\ [])
|
||||
|
||||
def print(doc, "text/markdown", options) when is_binary(doc) and is_list(options) do
|
||||
print_markdown(doc, options)
|
||||
end
|
||||
|
||||
def print(doc, "application/erlang+html", options) when is_list(options) do
|
||||
print_erlang_html(doc, options)
|
||||
end
|
||||
|
||||
def print(_doc, format, options) when is_binary(format) and is_list(options) do
|
||||
IO.puts("\nUnknown documentation format #{inspect(format)}\n")
|
||||
end
|
||||
|
||||
## Erlang+html
|
||||
|
||||
def print_erlang_html(doc, options) do
|
||||
options = Keyword.merge(default_options(), options)
|
||||
IO.write(traverse_erlang_html(doc, "", options))
|
||||
end
|
||||
|
||||
defp traverse_erlang_html(text, _indent, _options) when is_binary(text) do
|
||||
text
|
||||
end
|
||||
|
||||
defp traverse_erlang_html(nodes, indent, options) when is_list(nodes) do
|
||||
for node <- nodes do
|
||||
traverse_erlang_html(node, indent, options)
|
||||
end
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:div, [class: class] ++ _, entries}, indent, options) do
|
||||
prefix = indent <> quote_prefix(options)
|
||||
|
||||
content =
|
||||
entries
|
||||
|> traverse_erlang_html(indent, options)
|
||||
|> IO.iodata_to_binary()
|
||||
|> String.trim_trailing()
|
||||
|
||||
[
|
||||
prefix,
|
||||
class |> to_string() |> String.upcase(),
|
||||
"\n#{prefix}\n#{prefix}" | String.replace(content, "\n", "\n#{prefix}")
|
||||
]
|
||||
|> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:p, _, entries}, indent, options) do
|
||||
[indent | handle_erlang_html_text(entries, indent, options)]
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:h1, _, entries}, indent, options) do
|
||||
entries |> traverse_erlang_html(indent, options) |> heading(1, options) |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:h2, _, entries}, indent, options) do
|
||||
entries |> traverse_erlang_html(indent, options) |> heading(2, options) |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:h3, _, entries}, indent, options) do
|
||||
entries |> traverse_erlang_html(indent, options) |> heading(3, options) |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:h4, _, entries}, indent, options) do
|
||||
entries |> traverse_erlang_html(indent, options) |> heading(4, options) |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:h5, _, entries}, indent, options) do
|
||||
entries |> traverse_erlang_html(indent, options) |> heading(5, options) |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:h6, _, entries}, indent, options) do
|
||||
entries |> traverse_erlang_html(indent, options) |> heading(6, options) |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:br, _, []}, _indent, _options) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:i, _, entries}, indent, options) do
|
||||
inline_text("_", traverse_erlang_html(entries, indent, options), options)
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:em, _, entries}, indent, options) do
|
||||
inline_text("*", traverse_erlang_html(entries, indent, options), options)
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:code, _, entries}, indent, options) do
|
||||
inline_text("`", traverse_erlang_html(entries, indent, options), options)
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:pre, _, [{:code, _, entries}]}, indent, options) do
|
||||
string =
|
||||
entries
|
||||
|> traverse_erlang_html(indent, options)
|
||||
|> IO.iodata_to_binary()
|
||||
|
||||
["#{indent} ", String.replace(string, "\n", "\n#{indent} ")] |> newline_cons()
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:a, attributes, entries}, indent, options) do
|
||||
if href = attributes[:href] do
|
||||
[traverse_erlang_html(entries, indent, options), ?\s, ?(, href, ?)]
|
||||
else
|
||||
traverse_erlang_html(entries, indent, options)
|
||||
end
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:dl, _, entries}, indent, options) do
|
||||
traverse_erlang_html(entries, indent, options)
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:dt, _, entries}, indent, options) do
|
||||
["#{indent} ", @bullet_text | handle_erlang_html_text(entries, indent <> " ", options)]
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:dd, _, entries}, indent, options) do
|
||||
["#{indent} " | handle_erlang_html_text(entries, indent <> " ", options)]
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:ul, attributes, entries}, indent, options) do
|
||||
if attributes[:class] == "types" do
|
||||
types =
|
||||
for {:li, _, lines} <- entries,
|
||||
line <- lines,
|
||||
do: ["#{indent} ", traverse_erlang_html(line, indent <> " ", options), ?\n]
|
||||
|
||||
if types != [] do
|
||||
["#{indent}Typespecs:\n\n", types, ?\n]
|
||||
else
|
||||
[]
|
||||
end
|
||||
else
|
||||
for {:li, _, lines} <- entries do
|
||||
["#{indent} ", @bullet_text | handle_erlang_html_text(lines, indent <> " ", options)]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({:ol, _, entries}, indent, options) do
|
||||
for {{:li, _, lines}, i} <- Enum.with_index(entries, 1) do
|
||||
[
|
||||
"#{indent} ",
|
||||
Integer.to_string(i),
|
||||
". " | handle_erlang_html_text(lines, indent <> " ", options)
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
defp traverse_erlang_html({tag, _, entries}, indent, options) do
|
||||
[
|
||||
indent <> "<#{tag}>\n",
|
||||
traverse_erlang_html(entries, indent <> " ", options)
|
||||
|> IO.iodata_to_binary()
|
||||
|> String.trim_trailing(),
|
||||
"\n" <> indent <> "</#{tag}>"
|
||||
]
|
||||
|> newline_cons()
|
||||
end
|
||||
|
||||
defp newline_cons(text) do
|
||||
[text | "\n\n"]
|
||||
end
|
||||
|
||||
defp handle_erlang_html_text(entries, indent, options) do
|
||||
if Enum.all?(entries, &inline_html?/1) do
|
||||
entries
|
||||
|> traverse_erlang_html(indent, options)
|
||||
|> IO.iodata_to_binary()
|
||||
|> String.split(@spaces)
|
||||
|> wrap_text(options[:width], indent, true, "", [])
|
||||
|> tl()
|
||||
|> newline_cons()
|
||||
else
|
||||
entries
|
||||
|> traverse_erlang_html(indent, options)
|
||||
|> IO.iodata_to_binary()
|
||||
|> String.trim_leading()
|
||||
end
|
||||
end
|
||||
|
||||
defp inline_html?(binary) when is_binary(binary), do: true
|
||||
defp inline_html?({tag, _, _}) when tag in [:a, :code, :em, :i, :br], do: true
|
||||
defp inline_html?(_), do: false
|
||||
|
||||
## Markdown
|
||||
|
||||
def print_markdown(doc, options) do
|
||||
@spec print(String.t(), keyword) :: :ok
|
||||
def print(doc, options \\ []) do
|
||||
options = Keyword.merge(default_options(), options)
|
||||
|
||||
doc
|
||||
@@ -330,11 +139,6 @@ defmodule IO.ANSI.Docs do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
|
||||
defp process([">" <> line | rest], text, indent, options) do
|
||||
write_text(text, indent, options)
|
||||
process_quote(rest, [line], indent, options)
|
||||
end
|
||||
|
||||
defp process(["" | rest], text, indent, options) do
|
||||
write_text(text, indent, options)
|
||||
process(rest, [], indent, options)
|
||||
@@ -370,61 +174,22 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
end
|
||||
|
||||
### Headings
|
||||
## Headings
|
||||
|
||||
defp write_heading(heading, rest, text, indent, options) do
|
||||
write_text(text, indent, options)
|
||||
write(:doc_headings, heading, options)
|
||||
newline_after_block(options)
|
||||
newline_after_block()
|
||||
process(rest, [], "", options)
|
||||
end
|
||||
|
||||
### Quotes
|
||||
|
||||
defp process_quote([], lines, indent, options) do
|
||||
write_quote(lines, indent, options, false)
|
||||
end
|
||||
|
||||
defp process_quote([">", ">" <> line | rest], lines, indent, options) do
|
||||
write_quote(lines, indent, options, true)
|
||||
write_empty_quote_line(options)
|
||||
process_quote(rest, [line], indent, options)
|
||||
end
|
||||
|
||||
defp process_quote([">" <> line | rest], lines, indent, options) do
|
||||
process_quote(rest, [line | lines], indent, options)
|
||||
end
|
||||
|
||||
defp process_quote(rest, lines, indent, options) do
|
||||
write_quote(lines, indent, options, false)
|
||||
process(rest, [], indent, options)
|
||||
end
|
||||
|
||||
defp write_quote(lines, indent, options, no_wrap) do
|
||||
lines
|
||||
|> Enum.map(&String.trim/1)
|
||||
|> Enum.reverse()
|
||||
|> write_lines(
|
||||
indent,
|
||||
options,
|
||||
no_wrap,
|
||||
quote_prefix(options)
|
||||
)
|
||||
end
|
||||
|
||||
defp write_empty_quote_line(options) do
|
||||
options
|
||||
|> quote_prefix()
|
||||
|> IO.puts()
|
||||
end
|
||||
|
||||
### Lists
|
||||
## Lists
|
||||
|
||||
defp process_rest(stripped, rest, count, text, indent, options) do
|
||||
case stripped do
|
||||
<<bullet, ?\s, item::binary>> when bullet in @bullets ->
|
||||
write_text(text, indent, options)
|
||||
process_list(@bullet_text, item, rest, count, indent, options)
|
||||
process_list("• ", item, rest, count, indent, options)
|
||||
|
||||
<<d1, ?., ?\s, item::binary>> when d1 in ?0..?9 ->
|
||||
write_text(text, indent, options)
|
||||
@@ -444,12 +209,10 @@ defmodule IO.ANSI.Docs do
|
||||
entry = if indent == "", do: " " <> entry, else: entry
|
||||
new_indent = indent <> String.duplicate(" ", String.length(entry))
|
||||
|
||||
{contents, rest, done} =
|
||||
process_list_next(rest, count, byte_size(new_indent) - byte_size(indent), [])
|
||||
|
||||
{contents, rest, done} = process_list_next(rest, count, byte_size(new_indent), [])
|
||||
process(contents, [indent <> entry <> line, :no_wrap], new_indent, options)
|
||||
|
||||
if done, do: newline_after_block(options)
|
||||
if done, do: newline_after_block()
|
||||
process(rest, [], indent, options)
|
||||
end
|
||||
|
||||
@@ -490,7 +253,7 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
end
|
||||
|
||||
### Text
|
||||
## Text
|
||||
|
||||
defp write_text(text, indent, options) do
|
||||
case Enum.reverse(text) do
|
||||
@@ -504,26 +267,17 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp write_text(lines, indent, options, no_wrap) do
|
||||
write_lines(lines, indent, options, no_wrap, "")
|
||||
end
|
||||
|
||||
defp write_lines(lines, indent, options, no_wrap, prefix) do
|
||||
lines
|
||||
|> Enum.join(" ")
|
||||
|> format_text(options)
|
||||
|> String.split(@spaces)
|
||||
|> write_with_wrap(options[:width] - byte_size(indent), indent, no_wrap, prefix)
|
||||
|
||||
unless no_wrap, do: newline_after_block(options)
|
||||
end
|
||||
|
||||
defp format_text(text, options) do
|
||||
text
|
||||
|> handle_links()
|
||||
|> handle_links
|
||||
|> handle_inline(options)
|
||||
|> String.split(@spaces)
|
||||
|> write_with_wrap(options[:width] - byte_size(indent), indent, no_wrap)
|
||||
|
||||
unless no_wrap, do: newline_after_block()
|
||||
end
|
||||
|
||||
### Code blocks
|
||||
## Code blocks
|
||||
|
||||
defp process_code([], code, indent, options) do
|
||||
write_code(code, indent, options)
|
||||
@@ -562,15 +316,15 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
defp write_code(code, indent, options) do
|
||||
write(:doc_code, "#{indent} #{Enum.join(Enum.reverse(code), "\n#{indent} ")}", options)
|
||||
newline_after_block(options)
|
||||
newline_after_block()
|
||||
end
|
||||
|
||||
### Tables
|
||||
## Tables
|
||||
|
||||
defp process_table(lines, indent, options) do
|
||||
{table, rest} = Enum.split_while(lines, &table_line?/1)
|
||||
table_lines(table, options)
|
||||
newline_after_block(options)
|
||||
newline_after_block()
|
||||
process(rest, [], indent, options)
|
||||
end
|
||||
|
||||
@@ -594,17 +348,17 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
defp split_into_columns(line, options) do
|
||||
line
|
||||
|> String.trim(" ")
|
||||
|> String.trim("|")
|
||||
|> String.split(~r{(?<!\\)\|})
|
||||
|> String.trim()
|
||||
|> String.split(" | ")
|
||||
|> Enum.map(&render_column(&1, options))
|
||||
end
|
||||
|
||||
defp render_column(col, options) do
|
||||
col =
|
||||
col
|
||||
|> String.trim()
|
||||
|> String.replace("\\\|", "|")
|
||||
|> String.trim()
|
||||
|> handle_links
|
||||
|> handle_inline(options)
|
||||
|
||||
@@ -696,7 +450,7 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp table_line?(line) do
|
||||
line =~ ~r/[:\ -]\|[:\ -]/
|
||||
line =~ " | "
|
||||
end
|
||||
|
||||
## Helpers
|
||||
@@ -713,30 +467,17 @@ defmodule IO.ANSI.Docs do
|
||||
defp strip_spaces(rest, acc, _max), do: {rest, acc}
|
||||
|
||||
defp write(style, string, options) do
|
||||
IO.puts([color(style, options), string, maybe_reset(options)])
|
||||
IO.puts([color(style, options), string, IO.ANSI.reset()])
|
||||
end
|
||||
|
||||
defp write_with_wrap([], _available, _indent, _first, _prefix) do
|
||||
defp write_with_wrap([], _available, _indent, _first) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp write_with_wrap(words, available, indent, first, prefix) do
|
||||
words
|
||||
|> wrap_text(available, indent, first, prefix, [])
|
||||
|> tl()
|
||||
|> IO.puts()
|
||||
end
|
||||
|
||||
defp wrap_text([], _available, _indent, _first, _prefix, wrapped_lines) do
|
||||
Enum.reverse(wrapped_lines)
|
||||
end
|
||||
|
||||
defp wrap_text(words, available, indent, first, prefix, wrapped_lines) do
|
||||
prefix_length = length_without_escape(prefix, 0)
|
||||
{words, rest} = take_words(words, available - prefix_length, [])
|
||||
line = [if(first, do: "", else: indent), prefix, Enum.join(words, " ")]
|
||||
|
||||
wrap_text(rest, available, indent, false, prefix, [line, ?\n | wrapped_lines])
|
||||
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, " "))
|
||||
write_with_wrap(rest, available, indent, false)
|
||||
end
|
||||
|
||||
defp take_words([word | words], available, acc) do
|
||||
@@ -810,7 +551,7 @@ defmodule IO.ANSI.Docs do
|
||||
@delimiters [?\s, ?', ?", ?!, ?@, ?#, ?$, ?%, ?^, ?&] ++
|
||||
[?-, ?+, ?(, ?), ?[, ?], ?{, ?}, ?<, ?>, ?.]
|
||||
|
||||
### Inline start
|
||||
# Inline start
|
||||
|
||||
defp handle_inline(<<?*, ?*, rest::binary>>, options) do
|
||||
handle_inline(rest, ?d, ["**"], [], options)
|
||||
@@ -824,7 +565,7 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(rest, nil, [], [], options)
|
||||
end
|
||||
|
||||
### Inline delimiters
|
||||
# Inline delimiters
|
||||
|
||||
defp handle_inline(<<delimiter, ?*, ?*, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and delimiter in @delimiters do
|
||||
@@ -841,7 +582,7 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(rest, ?`, ["`"], [Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
### Clauses for handling escape
|
||||
# Clauses for handling escape
|
||||
|
||||
defp handle_inline(<<?\\, ?\\, ?*, ?*, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" do
|
||||
@@ -862,7 +603,7 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(rest, limit, [mark | buffer], acc, options)
|
||||
end
|
||||
|
||||
### Inline end
|
||||
# Inline end
|
||||
|
||||
defp handle_inline(<<?*, ?*, delimiter, rest::binary>>, ?d, buffer, acc, options)
|
||||
when delimiter in @delimiters do
|
||||
@@ -890,7 +631,7 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(rest, nil, [], [inline_buffer(buffer, options) | acc], options)
|
||||
end
|
||||
|
||||
### Catch all
|
||||
# Catch all
|
||||
|
||||
defp handle_inline(<<char, rest::binary>>, mark, buffer, acc, options) do
|
||||
handle_inline(rest, mark, [char | buffer], acc, options)
|
||||
@@ -901,24 +642,8 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp inline_buffer(buffer, options) do
|
||||
[mark | t] = Enum.reverse(buffer)
|
||||
inline_text(mark, t, options)
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
defp quote_prefix(options), do: "#{color(:doc_quote, options)}> #{maybe_reset(options)}"
|
||||
|
||||
defp heading(text, n, options) do
|
||||
[color(:doc_headings, options), String.duplicate("#", n), " ", text, maybe_reset(options)]
|
||||
end
|
||||
|
||||
defp inline_text(mark, text, options) do
|
||||
if options[:enabled] do
|
||||
[[color_for(mark, options) | text] | IO.ANSI.reset()]
|
||||
else
|
||||
[[mark | text] | mark]
|
||||
end
|
||||
[h | t] = Enum.reverse([IO.ANSI.reset() | buffer])
|
||||
[color_for(h, options) | t]
|
||||
end
|
||||
|
||||
defp color_for(mark, colors) do
|
||||
@@ -931,14 +656,9 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp color(style, colors) do
|
||||
IO.ANSI.format_fragment(colors[style], colors[:enabled])
|
||||
color = colors[style]
|
||||
IO.ANSI.format_fragment(color, colors[:enabled])
|
||||
end
|
||||
|
||||
defp newline_after_block(options) do
|
||||
IO.puts(maybe_reset(options))
|
||||
end
|
||||
|
||||
defp maybe_reset(options) do
|
||||
if options[:enabled], do: IO.ANSI.reset(), else: ""
|
||||
end
|
||||
defp newline_after_block, do: IO.puts(IO.ANSI.reset())
|
||||
end
|
||||
|
||||
+203
-585
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,6 @@
|
||||
defmodule Kernel.CLI do
|
||||
@moduledoc false
|
||||
|
||||
@compile {:no_warn_undefined, [Logger, IEx]}
|
||||
|
||||
@blank_config %{
|
||||
commands: [],
|
||||
output: ".",
|
||||
@@ -12,8 +10,7 @@ defmodule Kernel.CLI do
|
||||
errors: [],
|
||||
pa: [],
|
||||
pz: [],
|
||||
verbose_compile: false,
|
||||
profile: nil
|
||||
verbose_compile: false
|
||||
}
|
||||
|
||||
@doc """
|
||||
@@ -102,7 +99,7 @@ defmodule Kernel.CLI do
|
||||
Function invoked across nodes for `--rpc-eval`.
|
||||
"""
|
||||
def rpc_eval(expr) do
|
||||
wrapper(fn -> Code.eval_string(expr) end)
|
||||
wrapper(fn -> :elixir.eval(to_charlist(expr), [], []) end)
|
||||
catch
|
||||
kind, reason -> {kind, reason, __STACKTRACE__}
|
||||
end
|
||||
@@ -357,12 +354,6 @@ defmodule Kernel.CLI do
|
||||
parse_compiler(t, %{config | verbose_compile: true})
|
||||
end
|
||||
|
||||
# Private compiler options
|
||||
|
||||
defp parse_compiler(["--profile", "time" | t], config) do
|
||||
parse_compiler(t, %{config | profile: :time})
|
||||
end
|
||||
|
||||
defp parse_compiler([h | t] = list, config) do
|
||||
case h do
|
||||
"-" <> _ ->
|
||||
@@ -496,25 +487,13 @@ defmodule Kernel.CLI do
|
||||
wrapper(fn ->
|
||||
Code.compiler_options(config.compiler_options)
|
||||
|
||||
verbose_opts =
|
||||
opts =
|
||||
if config.verbose_compile do
|
||||
[each_file: &IO.puts("Compiling #{Path.relative_to_cwd(&1)}")]
|
||||
else
|
||||
[
|
||||
each_long_compilation:
|
||||
&IO.puts("Compiling #{Path.relative_to_cwd(&1)} (it's taking more than 10s)")
|
||||
]
|
||||
end
|
||||
|
||||
profile_opts =
|
||||
if config.profile do
|
||||
[profile: config.profile]
|
||||
[each_long_compilation: &IO.puts("Compiling #{&1} (it's taking more than 15s)")]
|
||||
else
|
||||
[]
|
||||
end
|
||||
|
||||
opts = verbose_opts ++ profile_opts
|
||||
|
||||
case Kernel.ParallelCompiler.compile_to_path(files, config.output, opts) do
|
||||
{:ok, _, _} -> :ok
|
||||
{:error, _, _} -> exit({:shutdown, 1})
|
||||
@@ -528,7 +507,6 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp filter_patterns(pattern) do
|
||||
pattern
|
||||
|> Path.expand()
|
||||
|> Path.wildcard()
|
||||
|> :lists.usort()
|
||||
|> Enum.filter(&File.regular?/1)
|
||||
|
||||
@@ -6,14 +6,21 @@
|
||||
# any of the `GenServer.Behaviour` conveniences.
|
||||
defmodule Kernel.LexicalTracker do
|
||||
@moduledoc false
|
||||
@timeout :infinity
|
||||
@timeout 30000
|
||||
@behaviour :gen_server
|
||||
|
||||
@doc """
|
||||
Returns all references in this lexical scope.
|
||||
Returns all remotes referenced in this lexical scope.
|
||||
"""
|
||||
def references(pid) do
|
||||
:gen_server.call(pid, :references, @timeout)
|
||||
def remote_references(pid) do
|
||||
:gen_server.call(pid, :remote_references, @timeout)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all remote dispatches in this lexical scope.
|
||||
"""
|
||||
def remote_dispatches(pid) do
|
||||
:gen_server.call(pid, :remote_dispatches, @timeout)
|
||||
end
|
||||
|
||||
# Internal API
|
||||
@@ -29,11 +36,6 @@ defmodule Kernel.LexicalTracker do
|
||||
:gen_server.call(pid, :stop)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def add_require(pid, module) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:add_require, module})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def add_import(pid, module, fas, line, warn) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:add_import, module, fas, line, warn})
|
||||
@@ -45,13 +47,23 @@ defmodule Kernel.LexicalTracker do
|
||||
end
|
||||
|
||||
@doc false
|
||||
def remote_dispatch(pid, module, mode) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:remote_dispatch, module, mode})
|
||||
def remote_reference(pid, module, mode) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:remote_reference, module, mode})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def import_dispatch(pid, module, fa, mode) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:import_dispatch, module, fa, mode})
|
||||
def remote_dispatch(pid, module, fa, line, mode) when is_atom(module) 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})
|
||||
end
|
||||
|
||||
@doc false
|
||||
@@ -59,11 +71,6 @@ defmodule Kernel.LexicalTracker do
|
||||
:gen_server.cast(pid, {:alias_dispatch, module})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def add_compile_env(pid, app, path, return) do
|
||||
:gen_server.cast(pid, {:compile_env, app, path, return})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def set_file(pid, file) do
|
||||
:gen_server.cast(pid, {:set_file, file})
|
||||
@@ -106,9 +113,10 @@ defmodule Kernel.LexicalTracker do
|
||||
state = %{
|
||||
directives: %{},
|
||||
references: %{},
|
||||
exports: %{},
|
||||
compile: %{},
|
||||
runtime: %{},
|
||||
structs: %{},
|
||||
cache: %{},
|
||||
compile_env: :ordsets.new(),
|
||||
file: nil
|
||||
}
|
||||
|
||||
@@ -125,13 +133,17 @@ defmodule Kernel.LexicalTracker do
|
||||
{:reply, Enum.sort(directives), state}
|
||||
end
|
||||
|
||||
def handle_call(:references, _from, state) do
|
||||
{compile, runtime} = partition(Map.to_list(state.references), [], [])
|
||||
{:reply, {compile, Map.keys(state.exports), runtime, state.compile_env}, state}
|
||||
def handle_call(:remote_references, _from, state) do
|
||||
{compile, runtime} = partition(:maps.to_list(state.references), [], [])
|
||||
{:reply, {compile, :maps.keys(state.structs), runtime}, state}
|
||||
end
|
||||
|
||||
def handle_call(:remote_dispatches, _from, state) do
|
||||
{:reply, {state.compile, state.runtime}, state}
|
||||
end
|
||||
|
||||
def handle_call({:read_cache, key}, _from, %{cache: cache} = state) do
|
||||
{:reply, Map.get(cache, key), state}
|
||||
{:reply, :maps.get(key, cache), state}
|
||||
end
|
||||
|
||||
def handle_call(:stop, _from, state) do
|
||||
@@ -139,16 +151,31 @@ defmodule Kernel.LexicalTracker do
|
||||
end
|
||||
|
||||
def handle_cast({:write_cache, key, value}, %{cache: cache} = state) do
|
||||
{:noreply, %{state | cache: Map.put(cache, key, value)}}
|
||||
{:noreply, %{state | cache: :maps.put(key, value, cache)}}
|
||||
end
|
||||
|
||||
def handle_cast({:remote_dispatch, module, mode}, state) do
|
||||
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__, 0}, 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)
|
||||
{:noreply, %{state | references: references}}
|
||||
end
|
||||
|
||||
def handle_cast({:import_dispatch, module, {function, arity}, mode}, state) do
|
||||
state = add_import_dispatch(state, module, function, arity, mode)
|
||||
def handle_cast({:import_dispatch, module, {function, arity} = fa, line, mode}, state) do
|
||||
state =
|
||||
state
|
||||
|> add_import_dispatch(module, function, arity)
|
||||
|> add_remote_dispatch(module, fa, line, mode)
|
||||
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
@@ -164,19 +191,11 @@ defmodule Kernel.LexicalTracker do
|
||||
{:noreply, %{state | file: nil}}
|
||||
end
|
||||
|
||||
def handle_cast({:compile_env, app, path, return}, state) do
|
||||
{:noreply, update_in(state.compile_env, &:ordsets.add_element({app, path, return}, &1))}
|
||||
end
|
||||
|
||||
def handle_cast({:add_require, module}, state) do
|
||||
{:noreply, put_in(state.exports[module], true)}
|
||||
end
|
||||
|
||||
def handle_cast({:add_import, module, fas, line, warn}, state) do
|
||||
directives =
|
||||
state.directives
|
||||
|> Enum.reject(&match?({{:import, {^module, _, _}}, _}, &1))
|
||||
|> Map.new()
|
||||
|> :maps.from_list()
|
||||
|> add_directive(module, line, warn, :import)
|
||||
|
||||
directives =
|
||||
@@ -217,22 +236,37 @@ defmodule Kernel.LexicalTracker do
|
||||
# Callbacks helpers
|
||||
|
||||
defp add_reference(references, module, :compile) when is_atom(module),
|
||||
do: Map.put(references, module, :compile)
|
||||
do: :maps.put(module, :compile, references)
|
||||
|
||||
defp add_reference(references, module, :runtime) when is_atom(module) do
|
||||
case Map.fetch(references, module) do
|
||||
case :maps.find(module, references) do
|
||||
{:ok, _} -> references
|
||||
:error -> Map.put(references, module, :runtime)
|
||||
:error -> :maps.put(module, :runtime, references)
|
||||
end
|
||||
end
|
||||
|
||||
defp add_import_dispatch(state, module, function, arity, mode) do
|
||||
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 =
|
||||
state.directives
|
||||
|> add_dispatch(module, :import)
|
||||
add_dispatch(state.directives, module, :import)
|
||||
|> add_dispatch({module, function, arity}, :import)
|
||||
|
||||
references = add_reference(state.references, module, mode)
|
||||
# Always compile time because we depend
|
||||
# on the module at compile time
|
||||
references = add_reference(state.references, module, :compile)
|
||||
|
||||
%{state | directives: directives, references: references}
|
||||
end
|
||||
|
||||
@@ -241,10 +275,17 @@ defmodule Kernel.LexicalTracker do
|
||||
# If the value is true, it was imported/aliased and used
|
||||
defp add_directive(directives, module_or_mfa, line, warn, tag) do
|
||||
marker = if warn, do: line, else: true
|
||||
Map.put(directives, {tag, module_or_mfa}, marker)
|
||||
:maps.put({tag, module_or_mfa}, marker, directives)
|
||||
end
|
||||
|
||||
defp add_dispatch(directives, module_or_mfa, tag) do
|
||||
Map.put(directives, {tag, module_or_mfa}, true)
|
||||
:maps.put({tag, module_or_mfa}, true, directives)
|
||||
end
|
||||
|
||||
defp map_update(key, initial, map, fun) do
|
||||
case :maps.find(key, map) do
|
||||
{:ok, val} -> :maps.put(key, fun.(val), map)
|
||||
:error -> :maps.put(key, initial, map)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -15,7 +15,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
always awaited on by calling `Task.await/1`
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
def async(fun) when is_function(fun, 0) do
|
||||
def async(fun) when is_function(fun) do
|
||||
if parent = :erlang.get(:elixir_compiler_pid) do
|
||||
file = :erlang.get(:elixir_compiler_file)
|
||||
dest = :erlang.get(:elixir_compiler_dest)
|
||||
@@ -62,28 +62,16 @@ defmodule Kernel.ParallelCompiler do
|
||||
the file, module and the module bytecode
|
||||
|
||||
* `:each_cycle` - after the given files are compiled, invokes this function
|
||||
that should return the following values:
|
||||
* `{:compile, modules, warnings}` - to continue compilation with a list of
|
||||
further modules to compile
|
||||
* `{:runtime, modules, warnings}` - to stop compilation and verify the list
|
||||
of modules because dependent modules have changed
|
||||
that return a list with potentially more files to compile
|
||||
|
||||
* `:long_compilation_threshold` - the timeout (in seconds) to check for modules
|
||||
taking too long to compile. For each file that exceeds the threshold, the
|
||||
`:each_long_compilation` callback is invoked. From Elixir v1.11, only the time
|
||||
spent compiling the actual module is taken into account by the threshold, the
|
||||
time spent waiting is not considered. Defaults to `10` seconds.
|
||||
|
||||
* `:profile` - if set to `:time` measure the compilation time of each compilation cycle
|
||||
and group pass checker
|
||||
* `: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 `compile/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.
|
||||
|
||||
* `:beam_timestamp` - the modification timestamp to give all BEAM files
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
def compile(files, options \\ []) when is_list(options) do
|
||||
@@ -140,47 +128,37 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
defp spawn_workers(files, output, options) do
|
||||
{:module, _} = :code.ensure_loaded(Kernel.ErrorHandler)
|
||||
compiler_pid = self()
|
||||
:elixir_code_server.cast({:reset_warnings, compiler_pid})
|
||||
schedulers = max(:erlang.system_info(:schedulers_online), 2)
|
||||
beam_timestamp = Keyword.get(options, :beam_timestamp)
|
||||
threshold = Keyword.get(options, :long_compilation_threshold, 10) * 1000
|
||||
timer_ref = Process.send_after(self(), :threshold_check, threshold)
|
||||
|
||||
{outcome, state} =
|
||||
result =
|
||||
spawn_workers(files, 0, [], [], %{}, [], %{
|
||||
dest: Keyword.get(options, :dest),
|
||||
each_cycle: Keyword.get(options, :each_cycle, fn -> {:runtime, [], []} end),
|
||||
each_cycle: Keyword.get(options, :each_cycle, fn -> [] end),
|
||||
each_file: Keyword.get(options, :each_file, fn _, _ -> :ok end) |> each_file(),
|
||||
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),
|
||||
profile: profile_init(Keyword.get(options, :profile)),
|
||||
output: output,
|
||||
timer_ref: timer_ref,
|
||||
long_compilation_threshold: threshold,
|
||||
long_compilation_threshold: Keyword.get(options, :long_compilation_threshold, 15),
|
||||
schedulers: schedulers
|
||||
})
|
||||
|
||||
Process.cancel_timer(state.timer_ref)
|
||||
# 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})
|
||||
|
||||
receive do
|
||||
:threshold_check -> :ok
|
||||
after
|
||||
0 -> :ok
|
||||
end
|
||||
|
||||
case {outcome, Code.get_compiler_option(:warnings_as_errors)} do
|
||||
{{:ok, _, [_ | _] = warnings}, true} ->
|
||||
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, []}
|
||||
|
||||
{{:ok, outcome, warnings}, _} ->
|
||||
{:ok, write_module_binaries(outcome, output, beam_timestamp), warnings}
|
||||
|
||||
{{:error, errors, warnings}, true} ->
|
||||
{{:error, errors, warnings}, :error} ->
|
||||
{:error, errors ++ warnings, []}
|
||||
|
||||
{{:error, errors, warnings}, _} ->
|
||||
{:error, errors, warnings}
|
||||
_ ->
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
@@ -197,77 +175,6 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
end
|
||||
|
||||
defp write_module_binaries(result, {:compile, path}, timestamp) do
|
||||
Enum.flat_map(result, fn
|
||||
{{:module, module}, {binary, _map}} ->
|
||||
full_path = Path.join(path, Atom.to_string(module) <> ".beam")
|
||||
File.write!(full_path, binary)
|
||||
if timestamp, do: File.touch!(full_path, timestamp)
|
||||
[module]
|
||||
|
||||
_ ->
|
||||
[]
|
||||
end)
|
||||
end
|
||||
|
||||
defp write_module_binaries(result, _output, _timestamp) do
|
||||
for {{:module, module}, _} <- result, do: module
|
||||
end
|
||||
|
||||
## Verification
|
||||
|
||||
defp verify_modules(result, warnings, dependent_modules, state) do
|
||||
checker_warnings = maybe_check_modules(result, dependent_modules, state)
|
||||
warnings = Enum.reverse(warnings, checker_warnings)
|
||||
{{:ok, result, warnings}, state}
|
||||
end
|
||||
|
||||
defp maybe_check_modules(result, runtime_modules, state) do
|
||||
%{schedulers: schedulers, profile: profile} = state
|
||||
|
||||
if :elixir_config.get(:bootstrap) do
|
||||
[]
|
||||
else
|
||||
compiled_modules = checker_compiled_modules(result)
|
||||
runtime_modules = checker_runtime_modules(runtime_modules)
|
||||
|
||||
profile_checker(profile, compiled_modules, runtime_modules, fn ->
|
||||
Module.ParallelChecker.verify(compiled_modules, runtime_modules, schedulers)
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
defp checker_compiled_modules(result) do
|
||||
for {{:module, _module}, {binary, module_map}} <- result do
|
||||
{module_map, binary}
|
||||
end
|
||||
end
|
||||
|
||||
defp checker_runtime_modules(modules) do
|
||||
for module <- modules,
|
||||
path = :code.which(module),
|
||||
is_list(path) and path != [] do
|
||||
{module, File.read!(path)}
|
||||
end
|
||||
end
|
||||
|
||||
defp profile_init(:time), do: {:time, System.monotonic_time(), 0}
|
||||
defp profile_init(nil), do: :none
|
||||
|
||||
defp profile_checker({:time, _, _}, compiled_modules, runtime_modules, fun) do
|
||||
{time, result} = :timer.tc(fun)
|
||||
time = div(time, 1000)
|
||||
num_modules = length(compiled_modules) + length(runtime_modules)
|
||||
IO.puts(:stderr, "[profile] Finished group pass check of #{num_modules} modules in #{time}ms")
|
||||
result
|
||||
end
|
||||
|
||||
defp profile_checker(:none, _compiled_modules, _runtime_modules, fun) do
|
||||
fun.()
|
||||
end
|
||||
|
||||
## Compiler worker spawning
|
||||
|
||||
# We already have n=schedulers currently running, don't spawn new ones
|
||||
defp spawn_workers(
|
||||
queue,
|
||||
@@ -284,23 +191,23 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
# Release waiting processes
|
||||
defp spawn_workers([{ref, found} | t], spawned, waiting, files, result, warnings, state) do
|
||||
{files, waiting} =
|
||||
waiting =
|
||||
case List.keytake(waiting, ref, 2) do
|
||||
{{_kind, pid, ^ref, _on, _defining, _deadlock}, waiting} ->
|
||||
send(pid, {ref, found})
|
||||
{update_timing(files, pid, :waiting), waiting}
|
||||
waiting
|
||||
|
||||
nil ->
|
||||
# In case the waiting process died (for example, it was an async process),
|
||||
# it will no longer be on the list. So we need to take it into account here.
|
||||
{files, waiting}
|
||||
waiting
|
||||
end
|
||||
|
||||
spawn_workers(t, spawned, waiting, files, result, warnings, state)
|
||||
end
|
||||
|
||||
defp spawn_workers([file | queue], spawned, waiting, files, result, warnings, state) do
|
||||
%{output: output, dest: dest} = state
|
||||
%{output: output, long_compilation_threshold: threshold, dest: dest} = state
|
||||
parent = self()
|
||||
file = Path.expand(file)
|
||||
|
||||
@@ -311,9 +218,25 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
try do
|
||||
case output do
|
||||
{:compile, path} -> compile_file(file, path, parent)
|
||||
:compile -> compile_file(file, dest, parent)
|
||||
:require -> require_file(file, parent)
|
||||
{:compile, path} ->
|
||||
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
|
||||
:erlang.put(:elixir_compiler_dest, path)
|
||||
:elixir_compiler.file_to_path(file, path, &each_file(&1, &2, parent))
|
||||
|
||||
:compile ->
|
||||
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
|
||||
:erlang.put(:elixir_compiler_dest, dest)
|
||||
:elixir_compiler.file(file, &each_file(&1, &2, parent))
|
||||
|
||||
:require ->
|
||||
case :elixir_code_server.call({:acquire, file}) do
|
||||
:required ->
|
||||
send(parent, {:file_cancel, self()})
|
||||
|
||||
:proceed ->
|
||||
:elixir_compiler.file(file, &each_file(&1, &2, parent))
|
||||
:elixir_code_server.cast({:required, file})
|
||||
end
|
||||
end
|
||||
catch
|
||||
kind, reason ->
|
||||
@@ -323,34 +246,21 @@ defmodule Kernel.ParallelCompiler do
|
||||
exit(:shutdown)
|
||||
end)
|
||||
|
||||
file_data = %{
|
||||
pid: pid,
|
||||
ref: ref,
|
||||
file: file,
|
||||
timestamp: System.monotonic_time(),
|
||||
compiling: 0,
|
||||
waiting: 0,
|
||||
warned: false
|
||||
}
|
||||
|
||||
files = [file_data | files]
|
||||
timer_ref = Process.send_after(self(), {:timed_out, pid}, threshold * 1000)
|
||||
files = [{pid, ref, file, timer_ref} | files]
|
||||
spawn_workers(queue, spawned + 1, waiting, files, result, warnings, state)
|
||||
end
|
||||
|
||||
# No more queue, nothing waiting, this cycle is done
|
||||
defp spawn_workers([], 0, [], [], result, warnings, state) do
|
||||
cycle_return = each_cycle_return(state.each_cycle.())
|
||||
state = cycle_timing(result, state)
|
||||
case state.each_cycle.() do
|
||||
[] ->
|
||||
modules = for {{:module, mod}, _} <- result, do: mod
|
||||
warnings = Enum.reverse(warnings)
|
||||
{:ok, modules, warnings}
|
||||
|
||||
case cycle_return do
|
||||
{:runtime, dependent_modules, extra_warnings} ->
|
||||
verify_modules(result, extra_warnings ++ warnings, dependent_modules, state)
|
||||
|
||||
{:compile, [], extra_warnings} ->
|
||||
verify_modules(result, extra_warnings ++ warnings, [], state)
|
||||
|
||||
{:compile, more, extra_warnings} ->
|
||||
spawn_workers(more, 0, [], [], result, extra_warnings ++ warnings, state)
|
||||
more ->
|
||||
spawn_workers(more, 0, [], [], result, warnings, state)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -361,7 +271,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
[],
|
||||
1,
|
||||
[{_, pid, ref, _, _, _}] = waiting,
|
||||
[%{pid: pid}] = files,
|
||||
[{pid, _, _, _}] = files,
|
||||
result,
|
||||
warnings,
|
||||
state
|
||||
@@ -375,7 +285,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
# There is potentially a deadlock. We will release modules with
|
||||
# the following order:
|
||||
#
|
||||
# 1. Code.ensure_compiled/1 checks (deadlock = soft)
|
||||
# 1. Code.ensure_compiled?/1 checks (deadlock = soft)
|
||||
# 2. Struct checks (deadlock = hard)
|
||||
# 3. Modules without a known definition
|
||||
# 4. Code invocation (deadlock = raise)
|
||||
@@ -392,7 +302,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
true ->
|
||||
errors = handle_deadlock(waiting, files)
|
||||
{{:error, errors, warnings}, state}
|
||||
{:error, errors, warnings}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -401,64 +311,19 @@ defmodule Kernel.ParallelCompiler do
|
||||
wait_for_messages([], spawned, waiting, files, result, warnings, state)
|
||||
end
|
||||
|
||||
defp compile_file(file, path, parent) do
|
||||
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
|
||||
:erlang.put(:elixir_compiler_dest, path)
|
||||
:elixir_compiler.file(file, &each_file(&1, &2, parent))
|
||||
end
|
||||
|
||||
defp require_file(file, parent) do
|
||||
case :elixir_code_server.call({:acquire, file}) do
|
||||
:required ->
|
||||
send(parent, {:file_cancel, self()})
|
||||
|
||||
:proceed ->
|
||||
:elixir_compiler.file(file, &each_file(&1, &2, parent))
|
||||
:elixir_code_server.cast({:required, file})
|
||||
end
|
||||
end
|
||||
|
||||
defp cycle_timing(_result, %{profile: :none} = state) do
|
||||
state
|
||||
end
|
||||
|
||||
defp cycle_timing(result, %{profile: {:time, cycle_start, module_counter}} = state) do
|
||||
num_modules = count_modules(result)
|
||||
diff_modules = num_modules - module_counter
|
||||
now = System.monotonic_time()
|
||||
time = System.convert_time_unit(now - cycle_start, :native, :millisecond)
|
||||
|
||||
IO.puts(
|
||||
:stderr,
|
||||
"[profile] Finished compilation cycle of #{diff_modules} modules in #{time}ms"
|
||||
)
|
||||
|
||||
%{state | profile: {:time, now, num_modules}}
|
||||
end
|
||||
|
||||
defp count_modules(result) do
|
||||
Enum.count(result, &match?({{:module, _}, _}, &1))
|
||||
end
|
||||
|
||||
# TODO: Deprecate other returns on v1.14
|
||||
defp each_cycle_return({kind, modules, warnings}), do: {kind, modules, warnings}
|
||||
defp each_cycle_return({kind, modules}), do: {kind, modules, []}
|
||||
defp each_cycle_return(modules) when is_list(modules), do: {:compile, modules, []}
|
||||
|
||||
# The goal of this function is to find leaves in the dependency graph,
|
||||
# i.e. to find code that depends on code that we know is not being defined.
|
||||
# Note that not all files have been compile yet, so they may not be in waiting.
|
||||
defp without_definition(waiting, files) do
|
||||
nillify_empty(
|
||||
for %{pid: pid} <- files,
|
||||
{_, ^pid, ref, on, _, _} <- List.wrap(List.keyfind(waiting, pid, 1)),
|
||||
for {pid, _, _, _} <- files,
|
||||
{_, ^pid, ref, on, _, _} = List.keyfind(waiting, pid, 1),
|
||||
not Enum.any?(waiting, fn {_, _, _, _, defining, _} -> on in defining end),
|
||||
do: {ref, :not_found}
|
||||
)
|
||||
end
|
||||
|
||||
defp deadlocked(waiting, type) do
|
||||
nillify_empty(for {_, _, ref, _, _, ^type} <- waiting, do: {ref, :deadlock})
|
||||
nillify_empty(for {_, _, ref, _, _, ^type} <- waiting, do: {ref, :not_found})
|
||||
end
|
||||
|
||||
defp nillify_empty([]), do: nil
|
||||
@@ -481,7 +346,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
result = Map.put(result, {kind, module}, true)
|
||||
spawn_workers(available ++ queue, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
{:module_available, child, ref, file, module, binary, module_map} ->
|
||||
{:module_available, child, ref, file, module, binary} ->
|
||||
state.each_module.(file, module, binary)
|
||||
|
||||
# Release the module loader which is waiting for an ack
|
||||
@@ -491,7 +356,8 @@ defmodule Kernel.ParallelCompiler do
|
||||
for {:module, _, ref, ^module, _defining, _deadlock} <- waiting,
|
||||
do: {ref, :found}
|
||||
|
||||
result = Map.put(result, {:module, module}, {binary, module_map})
|
||||
cancel_waiting_timer(files, child)
|
||||
result = Map.put(result, {:module, module}, true)
|
||||
spawn_workers(available ++ queue, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
# If we are simply requiring files, we do not add to waiting.
|
||||
@@ -501,33 +367,24 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
{:waiting, kind, child, ref, on, defining, deadlock?} ->
|
||||
# If we already got what we were waiting for, do not put it on waiting.
|
||||
# If we're waiting on ourselves, send :found so that we can crash with
|
||||
# a better error.
|
||||
{files, waiting} =
|
||||
# Alternatively, we're waiting on ourselves,
|
||||
# send :found so that we can crash with a better error.
|
||||
waiting =
|
||||
if Map.has_key?(result, {kind, on}) or on in defining do
|
||||
send(child, {ref, :found})
|
||||
{files, waiting}
|
||||
waiting
|
||||
else
|
||||
files = update_timing(files, child, :compiling)
|
||||
{files, [{kind, child, ref, on, defining, deadlock?} | waiting]}
|
||||
[{kind, child, ref, on, defining, deadlock?} | waiting]
|
||||
end
|
||||
|
||||
spawn_workers(queue, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
:threshold_check ->
|
||||
files =
|
||||
for data <- files do
|
||||
if data.warned or List.keymember?(waiting, data.pid, 1) do
|
||||
data
|
||||
else
|
||||
data = update_timing(data, :compiling)
|
||||
data = maybe_warn_long_compilation(data, state)
|
||||
data
|
||||
end
|
||||
end
|
||||
{:timed_out, child} ->
|
||||
case List.keyfind(files, child, 0) do
|
||||
{^child, _, file, _} -> state.each_long_compilation.(file)
|
||||
_ -> :ok
|
||||
end
|
||||
|
||||
timer_ref = Process.send_after(self(), :threshold_check, state.long_compilation_threshold)
|
||||
state = %{state | timer_ref: timer_ref}
|
||||
spawn_workers(queue, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
{:warning, file, line, message} ->
|
||||
@@ -539,9 +396,10 @@ defmodule Kernel.ParallelCompiler do
|
||||
{:file_ok, child_pid, ref, file, lexical} ->
|
||||
state.each_file.(file, lexical)
|
||||
send(child_pid, ref)
|
||||
cancel_waiting_timer(files, child_pid)
|
||||
|
||||
discard_down(child_pid)
|
||||
new_files = discard_and_maybe_log_file(files, child_pid, state)
|
||||
new_files = List.keydelete(files, child_pid, 0)
|
||||
|
||||
# Sometimes we may have spurious entries in the waiting list
|
||||
# because someone invoked try/rescue UndefinedFunctionError
|
||||
@@ -549,77 +407,28 @@ defmodule Kernel.ParallelCompiler do
|
||||
spawn_workers(queue, spawned - 1, new_waiting, new_files, result, warnings, state)
|
||||
|
||||
{:file_cancel, child_pid} ->
|
||||
cancel_waiting_timer(files, child_pid)
|
||||
discard_down(child_pid)
|
||||
new_files = Enum.reject(files, &(&1.pid == child_pid))
|
||||
new_files = List.keydelete(files, child_pid, 0)
|
||||
spawn_workers(queue, spawned - 1, waiting, new_files, result, warnings, state)
|
||||
|
||||
{:file_error, child_pid, file, {kind, reason, stack}} ->
|
||||
print_error(file, kind, reason, stack)
|
||||
cancel_waiting_timer(files, child_pid)
|
||||
discard_down(child_pid)
|
||||
files |> Enum.reject(&(&1.pid == child_pid)) |> terminate()
|
||||
{{:error, [to_error(file, kind, reason, stack)], warnings}, state}
|
||||
files |> List.keydelete(child_pid, 0) |> terminate()
|
||||
{:error, [to_error(file, kind, reason, stack)], warnings}
|
||||
|
||||
{:DOWN, ref, :process, pid, reason} ->
|
||||
waiting = List.keydelete(waiting, pid, 1)
|
||||
|
||||
case handle_down(files, ref, reason) do
|
||||
:ok -> wait_for_messages(queue, spawned - 1, waiting, files, result, warnings, state)
|
||||
{:error, errors} -> {{:error, errors, warnings}, state}
|
||||
{:error, errors} -> {:error, errors, warnings}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp update_timing(files, pid, key) do
|
||||
Enum.map(files, fn data ->
|
||||
if data.pid == pid do
|
||||
time = System.monotonic_time()
|
||||
%{data | key => data[key] + time - data.timestamp, timestamp: time}
|
||||
else
|
||||
data
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp update_timing(data, key) do
|
||||
time = System.monotonic_time()
|
||||
%{data | key => data[key] + time - data.timestamp, timestamp: time}
|
||||
end
|
||||
|
||||
defp maybe_warn_long_compilation(data, state) do
|
||||
compiling = System.convert_time_unit(data.compiling, :native, :millisecond)
|
||||
|
||||
if not data.warned and compiling >= state.long_compilation_threshold do
|
||||
state.each_long_compilation.(data.file)
|
||||
%{data | warned: true}
|
||||
else
|
||||
data
|
||||
end
|
||||
end
|
||||
|
||||
defp discard_and_maybe_log_file(files, pid, state) do
|
||||
Enum.reject(files, fn data ->
|
||||
if data.pid == pid do
|
||||
data = update_timing(data, :compiling)
|
||||
data = maybe_warn_long_compilation(data, state)
|
||||
|
||||
if state.profile != :none do
|
||||
compiling = System.convert_time_unit(data.compiling, :native, :millisecond)
|
||||
waiting = System.convert_time_unit(data.waiting, :native, :millisecond)
|
||||
extra = if waiting > 0, do: " (plus #{waiting}ms waiting)", else: ""
|
||||
|
||||
IO.puts(
|
||||
:stderr,
|
||||
"[profile] #{Path.relative_to_cwd(data.file)} compiled in #{compiling}ms" <> extra
|
||||
)
|
||||
end
|
||||
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp discard_down(pid) do
|
||||
receive do
|
||||
{:DOWN, _, :process, ^pid, _} -> :ok
|
||||
@@ -631,20 +440,24 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
|
||||
defp handle_down(files, ref, reason) do
|
||||
case Enum.find(files, &(&1.ref == ref)) do
|
||||
%{pid: pid, file: file} ->
|
||||
case List.keyfind(files, ref, 1) do
|
||||
{child_pid, ^ref, file, _timer_ref} ->
|
||||
print_error(file, :exit, reason, [])
|
||||
files |> Enum.reject(&(&1.pid == pid)) |> terminate()
|
||||
|
||||
files
|
||||
|> List.keydelete(child_pid, 0)
|
||||
|> terminate()
|
||||
|
||||
{:error, [to_error(file, :exit, reason, [])]}
|
||||
|
||||
nil ->
|
||||
_ ->
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_deadlock(waiting, files) do
|
||||
deadlock =
|
||||
for %{pid: pid, file: file} <- files do
|
||||
for {pid, _, file, _} <- files do
|
||||
{:current_stacktrace, stacktrace} = Process.info(pid, :current_stacktrace)
|
||||
Process.exit(pid, :kill)
|
||||
|
||||
@@ -679,8 +492,8 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
|
||||
defp terminate(files) do
|
||||
for %{pid: pid} <- files, do: Process.exit(pid, :kill)
|
||||
for %{pid: pid} <- files, do: discard_down(pid)
|
||||
for {pid, _, _, _} <- files, do: Process.exit(pid, :kill)
|
||||
for {pid, _, _, _} <- files, do: discard_down(pid)
|
||||
:ok
|
||||
end
|
||||
|
||||
@@ -691,6 +504,22 @@ defmodule Kernel.ParallelCompiler do
|
||||
])
|
||||
end
|
||||
|
||||
defp cancel_waiting_timer(files, child_pid) do
|
||||
case List.keyfind(files, child_pid, 0) do
|
||||
{^child_pid, _ref, _file, timer_ref} ->
|
||||
Process.cancel_timer(timer_ref)
|
||||
# Let's flush the message in case it arrived before we canceled the timeout.
|
||||
receive do
|
||||
{:timed_out, ^child_pid} -> :ok
|
||||
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)
|
||||
@@ -708,12 +537,6 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
end
|
||||
|
||||
defp get_line(file, _reason, [{_, _, _, [file: 'expanding macro']}, {_, _, _, 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)
|
||||
|
||||
@@ -3,21 +3,14 @@ defmodule Kernel.SpecialForms do
|
||||
Special forms are the basic building blocks of Elixir, and therefore
|
||||
cannot be overridden by the developer.
|
||||
|
||||
The `Kernel.SpecialForms` module consists solely of macros that can be
|
||||
invoked anywhere in Elixir code without the use of the
|
||||
`Kernel.SpecialForms.` prefix. This is possible because they all have
|
||||
been automatically imported, in the same fashion as the functions and
|
||||
macros from the `Kernel` module.
|
||||
|
||||
These building blocks are defined in this module. Some of these special forms are lexical (such as
|
||||
`alias/2` and `case/2`). The macros `{}/1` and `<<>>/1` are also special
|
||||
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
|
||||
forms used to define tuple and binary data structures respectively.
|
||||
|
||||
This module also documents macros that return information about Elixir's
|
||||
compilation environment, such as (`__ENV__/0`, `__MODULE__/0`, `__DIR__/0`,
|
||||
`__STACKTRACE__/0`, and `__CALLER__/0`).
|
||||
compilation environment, such as (`__ENV__/0`, `__MODULE__/0`, `__DIR__/0` and `__CALLER__/0`).
|
||||
|
||||
Additionally, it documents two special forms, `__block__/1` and
|
||||
Finally, it also documents two special forms, `__block__/1` and
|
||||
`__aliases__/1`, which are not intended to be called directly by the
|
||||
developer but they appear in quoted contents since they are essential
|
||||
in Elixir's constructs.
|
||||
@@ -187,7 +180,13 @@ defmodule Kernel.SpecialForms do
|
||||
iex> <<0, "foo">>
|
||||
<<0, 102, 111, 111>>
|
||||
|
||||
Binaries need to be explicitly tagged as `binary`:
|
||||
Variables or any other type need to be explicitly tagged:
|
||||
|
||||
iex> rest = "oo"
|
||||
iex> <<102, rest>>
|
||||
** (ArgumentError) argument error
|
||||
|
||||
We can solve this by explicitly tagging it as `binary`:
|
||||
|
||||
iex> rest = "oo"
|
||||
iex> <<102, rest::binary>>
|
||||
@@ -201,12 +200,6 @@ defmodule Kernel.SpecialForms do
|
||||
iex> <<"foo"::utf32>>
|
||||
<<0, 0, 0, 102, 0, 0, 0, 111, 0, 0, 0, 111>>
|
||||
|
||||
Otherwise we get an `ArgumentError` when construcing the binary:
|
||||
|
||||
rest = "oo"
|
||||
<<102, rest>>
|
||||
** (ArgumentError) argument error
|
||||
|
||||
## Options
|
||||
|
||||
Many options can be given by using `-` as separator. Order is
|
||||
@@ -351,8 +344,8 @@ defmodule Kernel.SpecialForms do
|
||||
13::size(8), 10::size(8), 26::size(8), 10::size(8)>>
|
||||
@jpg_signature <<255::size(8), 216::size(8)>>
|
||||
|
||||
def type(<<@png_signature, _rest::binary>>), do: :png
|
||||
def type(<<@jpg_signature, _rest::binary>>), do: :jpg
|
||||
def type(<<@png_signature, rest::binary>>), do: :png
|
||||
def type(<<@jpg_signature, rest::binary>>), do: :jpg
|
||||
def type(_), do: :unknown
|
||||
end
|
||||
|
||||
@@ -371,7 +364,7 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro unquote(:<<>>)(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Dot operator. Defines a remote call, a call to an anonymous function, or an alias.
|
||||
Defines a remote call, a call to an anonymous function, or an alias.
|
||||
|
||||
The dot (`.`) in Elixir can be used for remote calls:
|
||||
|
||||
@@ -438,7 +431,7 @@ defmodule Kernel.SpecialForms do
|
||||
...> end
|
||||
{{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], ["FOO"]}
|
||||
|
||||
Note that we have an inner tuple, containing the atom `:.` representing
|
||||
Notice we have an inner tuple, containing the atom `:.` representing
|
||||
the dot as first element:
|
||||
|
||||
{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}
|
||||
@@ -513,7 +506,7 @@ defmodule Kernel.SpecialForms do
|
||||
Keyword.values #=> uses MyKeyword.values
|
||||
Elixir.Keyword.values #=> uses Keyword.values
|
||||
|
||||
Note that calling `alias` without the `:as` option automatically
|
||||
Notice that calling `alias` without the `:as` option automatically
|
||||
sets an alias based on the last part of the module. For example:
|
||||
|
||||
alias Foo.Bar.Baz
|
||||
@@ -599,7 +592,7 @@ defmodule Kernel.SpecialForms do
|
||||
## Selector
|
||||
|
||||
By default, Elixir imports functions and macros from the given
|
||||
module, except the ones starting with an underscore (which are
|
||||
module, except the ones starting with underscore (which are
|
||||
usually callbacks):
|
||||
|
||||
import List
|
||||
@@ -617,7 +610,7 @@ defmodule Kernel.SpecialForms do
|
||||
import List, only: [flatten: 1]
|
||||
import String, except: [split: 2]
|
||||
|
||||
Note that calling `except` is always exclusive on a previously
|
||||
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:
|
||||
|
||||
@@ -637,7 +630,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
## Lexical scope
|
||||
|
||||
It is important to note that `import/2` is lexical. This means you
|
||||
It is important to notice that `import/2` is lexical. This means you
|
||||
can import specific macros inside specific functions:
|
||||
|
||||
defmodule Math do
|
||||
@@ -721,11 +714,10 @@ defmodule Kernel.SpecialForms do
|
||||
To retrieve the stacktrace of the current process, use
|
||||
`Process.info(self(), :current_stacktrace)` instead.
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
defmacro __STACKTRACE__, do: error!([])
|
||||
|
||||
@doc """
|
||||
Pin operator. Accesses an already bound variable in match clauses.
|
||||
Accesses an already bound variable in match clauses. Also known as the pin operator.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -757,12 +749,12 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro ^var, do: error!([var])
|
||||
|
||||
@doc """
|
||||
Match operator. Matches the value on the right against the pattern on the left.
|
||||
Matches the value on the right against the pattern on the left.
|
||||
"""
|
||||
defmacro left = right, do: error!([left, right])
|
||||
|
||||
@doc """
|
||||
Type operator. Used by types and bitstrings to specify types.
|
||||
Used by types and bitstrings to specify types.
|
||||
|
||||
This operator is used in two distinct occasions in Elixir.
|
||||
It is used in typespecs to specify the type of a variable,
|
||||
@@ -806,7 +798,7 @@ defmodule Kernel.SpecialForms do
|
||||
* The first element of the tuple is always an atom or
|
||||
another tuple in the same representation.
|
||||
|
||||
* The second element of the tuple represents [metadata](`t:Macro.metadata/0`).
|
||||
* The second element of the tuple represents metadata.
|
||||
|
||||
* The third element of the tuple are the arguments for the
|
||||
function call. The third argument may be an atom, which is
|
||||
@@ -828,22 +820,6 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
## Options
|
||||
|
||||
* `:bind_quoted` - passes a binding to the macro. Whenever a binding is
|
||||
given, `unquote/1` is automatically disabled.
|
||||
|
||||
* `:context` - sets the resolution context.
|
||||
|
||||
* `: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`).
|
||||
|
||||
* `:file` - sets the quoted expressions to have the given file.
|
||||
|
||||
* `:line` - sets the quoted expressions to have the given line.
|
||||
|
||||
* `:location` - when set to `:keep`, keeps the current line and file from
|
||||
quote. Read the "Stacktrace information" section below for more information.
|
||||
|
||||
* `:unquote` - when `false`, disables unquoting. This means any `unquote`
|
||||
call will be kept as is in the AST, instead of replaced by the `unquote`
|
||||
arguments. For example:
|
||||
@@ -858,6 +834,21 @@ defmodule Kernel.SpecialForms do
|
||||
...> end
|
||||
{:unquote, [], ["hello"]}
|
||||
|
||||
* `:location` - when set to `:keep`, keeps the current line and file from
|
||||
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`).
|
||||
|
||||
* `:context` - sets the resolution context.
|
||||
|
||||
* `:bind_quoted` - passes a binding to the macro. Whenever a binding is
|
||||
given, `unquote/1` is automatically disabled.
|
||||
|
||||
## Quote and macros
|
||||
|
||||
`quote/2` is commonly used with macros for code generation. As an exercise,
|
||||
@@ -957,7 +948,7 @@ defmodule Kernel.SpecialForms do
|
||||
import Math
|
||||
squared(5)
|
||||
x
|
||||
** (CompileError) undefined variable x or undefined function x/0
|
||||
#=> ** (CompileError) undefined variable x or undefined function x/0
|
||||
|
||||
We can see that `x` did not leak to the user context. This happens
|
||||
because Elixir macros are hygienic, a topic we will discuss at length
|
||||
@@ -1022,7 +1013,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
Hygiene.write()
|
||||
Hygiene.read()
|
||||
** (RuntimeError) undefined variable a or undefined function a/0
|
||||
#=> ** (RuntimeError) undefined variable a or undefined function a/0
|
||||
|
||||
For such, you can explicitly pass the current module scope as
|
||||
argument:
|
||||
@@ -1064,7 +1055,7 @@ defmodule Kernel.SpecialForms do
|
||||
Hygiene.no_interference()
|
||||
#=> %{}
|
||||
|
||||
Note that, even though the alias `M` is not available
|
||||
Notice that, even though the alias `M` is not available
|
||||
in the context the macro is expanded, the code above works
|
||||
because `M` still expands to `Map`.
|
||||
|
||||
@@ -1113,7 +1104,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
require Hygiene
|
||||
Hygiene.no_interference()
|
||||
** (UndefinedFunctionError) ...
|
||||
#=> ** (UndefinedFunctionError) ...
|
||||
|
||||
Hygiene.interference()
|
||||
#=> "world"
|
||||
@@ -1200,8 +1191,8 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
require Sample
|
||||
Sample.add(:one, :two)
|
||||
** (ArithmeticError) bad argument in arithmetic expression
|
||||
adder.ex:5: Sample.add/2
|
||||
#=> ** (ArithmeticError) bad argument in arithmetic expression
|
||||
#=> adder.ex:5: Sample.add/2
|
||||
|
||||
When using `location: :keep` and invalid arguments are given to
|
||||
`Sample.add/2`, the stacktrace information will point to the file
|
||||
@@ -1522,7 +1513,7 @@ defmodule Kernel.SpecialForms do
|
||||
non-matched value:
|
||||
|
||||
with :foo = :bar, do: :ok
|
||||
** (MatchError) no match of right hand side value: :bar
|
||||
#=> ** (MatchError) no match of right hand side value: :bar
|
||||
|
||||
As with any other function or macro call in Elixir, explicit parens can
|
||||
also be used around the arguments before the `do`/`end` block:
|
||||
@@ -1559,8 +1550,6 @@ defmodule Kernel.SpecialForms do
|
||||
@doc """
|
||||
Defines an anonymous function.
|
||||
|
||||
See `Function` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> add = fn a, b -> a + b end
|
||||
@@ -1598,7 +1587,7 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro unquote(:__block__)(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Caputure operator. Captures or creates an anonymous function.
|
||||
Captures or creates an anonymous function.
|
||||
|
||||
## Capture
|
||||
|
||||
@@ -1689,7 +1678,7 @@ defmodule Kernel.SpecialForms do
|
||||
unambiguously identified by the operator `:.`. For example:
|
||||
|
||||
iex> quote do
|
||||
...> Foo.bar()
|
||||
...> Foo.bar
|
||||
...> end
|
||||
{{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}
|
||||
|
||||
@@ -1748,7 +1737,8 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
## Variable handling
|
||||
|
||||
Note that variables bound in a clause do not leak to the outer context:
|
||||
Notice that variables bound in a clause "head" do not leak to the
|
||||
outer context:
|
||||
|
||||
case data do
|
||||
{:ok, value} -> value
|
||||
@@ -1758,8 +1748,8 @@ defmodule Kernel.SpecialForms do
|
||||
value
|
||||
#=> unbound variable value
|
||||
|
||||
When binding variables with the same names as variables in the outer context,
|
||||
the variables in the outer context are not affected.
|
||||
However, variables explicitly bound in the clause "body" are
|
||||
accessible from the outer context:
|
||||
|
||||
value = 7
|
||||
|
||||
@@ -1769,11 +1759,12 @@ defmodule Kernel.SpecialForms do
|
||||
end
|
||||
|
||||
value
|
||||
#=> 7
|
||||
#=> 7 or 13
|
||||
|
||||
In the example above, `value` is going to be `7` regardless of the value of
|
||||
`lucky?`. The variable `value` bound in the clause and the variable `value`
|
||||
bound in the outer context are two entirely separate variables.
|
||||
In the example above, `value` is going to be `7` or `13` depending on
|
||||
the value of `lucky?`. In case `value` has no previous value before
|
||||
case, clauses that do not explicitly bind a value have the variable
|
||||
bound to `nil`.
|
||||
|
||||
If you want to pattern match against an existing variable,
|
||||
you need to use the `^/1` operator:
|
||||
|
||||
@@ -22,9 +22,9 @@ defmodule Kernel.Typespec do
|
||||
{:docs_v1, _, _, _, _, _, docs} ->
|
||||
for {{:type, name, arity}, _, _, doc, _} <- docs do
|
||||
case doc do
|
||||
%{"en" => doc_string} -> {{name, arity}, doc_string}
|
||||
:none -> {{name, arity}, nil}
|
||||
:hidden -> {{name, arity}, false}
|
||||
_ -> {{name, arity}, nil}
|
||||
%{"en" => doc_string} -> {{name, arity}, doc_string}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -83,7 +83,7 @@ defmodule Kernel.Typespec do
|
||||
store_typespec(bag, kind, expr, pos)
|
||||
|
||||
case :ets.lookup(set, {:function, name, arity}) do
|
||||
[{{:function, ^name, ^arity}, _, line, _, doc, doc_meta}] ->
|
||||
[{{:function, ^name, ^arity}, line, _, doc, doc_meta}] ->
|
||||
store_doc(set, kind, name, arity, line, :doc, doc, doc_meta)
|
||||
|
||||
_ ->
|
||||
@@ -130,18 +130,11 @@ defmodule Kernel.Typespec do
|
||||
store_typespec(bag, kind, expr, pos)
|
||||
end
|
||||
|
||||
@reserved_signatures [required: 1, optional: 1]
|
||||
def deftypespec(kind, expr, line, file, module, pos)
|
||||
when kind in [:type, :typep, :opaque] do
|
||||
{set, bag} = :elixir_module.data_tables(module)
|
||||
|
||||
case type_to_signature(expr) do
|
||||
{name, arity} = signature when signature in @reserved_signatures ->
|
||||
compile_error(
|
||||
:elixir_locals.get_cached_env(pos),
|
||||
"type #{name}/#{arity} is a reserved type and it cannot be defined"
|
||||
)
|
||||
|
||||
{name, arity} when kind == :typep ->
|
||||
{line, doc} = get_doc_info(set, :typedoc, line)
|
||||
|
||||
@@ -257,13 +250,7 @@ defmodule Kernel.Typespec do
|
||||
end
|
||||
|
||||
if Map.has_key?(type_pairs, type_pair) do
|
||||
{error_full_path, error_line} = type_pairs[type_pair]
|
||||
error_relative_path = Path.relative_to_cwd(error_full_path)
|
||||
|
||||
compile_error(
|
||||
env,
|
||||
"type #{name}/#{arity} is already defined in #{error_relative_path}:#{error_line}"
|
||||
)
|
||||
compile_error(env, "type #{name}/#{arity} is already defined")
|
||||
end
|
||||
|
||||
Map.put(type_pairs, type_pair, {file, line})
|
||||
@@ -298,7 +285,7 @@ defmodule Kernel.Typespec do
|
||||
if is_atom(args) do
|
||||
[]
|
||||
else
|
||||
:lists.map(&variable/1, args)
|
||||
for(arg <- args, do: variable(arg))
|
||||
end
|
||||
|
||||
vars = :lists.filter(&match?({:var, _, _}, &1), args)
|
||||
@@ -477,7 +464,7 @@ defmodule Kernel.Typespec do
|
||||
_,
|
||||
state
|
||||
)
|
||||
when is_atom(ctx1) and is_atom(ctx2) and unit in 1..256 do
|
||||
when is_atom(ctx1) and is_atom(ctx2) and is_integer(unit) and unit >= 0 do
|
||||
line = line(meta)
|
||||
{{:type, line, :binary, [{:integer, line, 0}, {:integer, line(unit_meta), unit}]}, state}
|
||||
end
|
||||
@@ -502,7 +489,7 @@ defmodule Kernel.Typespec do
|
||||
state
|
||||
)
|
||||
when is_atom(ctx1) and is_atom(ctx2) and is_atom(ctx3) and is_integer(size) and
|
||||
size >= 0 and unit in 1..256 do
|
||||
is_integer(unit) and size >= 0 and unit >= 0 do
|
||||
args = [{:integer, line(size_meta), size}, {:integer, line(unit_meta), unit}]
|
||||
{{:type, line(meta), :binary, args}, state}
|
||||
end
|
||||
@@ -510,7 +497,7 @@ defmodule Kernel.Typespec do
|
||||
defp typespec({:<<>>, _meta, _args}, _vars, caller, _state) do
|
||||
message =
|
||||
"invalid binary specification, expected <<_::size>>, <<_::_*unit>>, " <>
|
||||
"or <<_::size, _::_*unit>> with size being non-negative integers, and unit being an integer between 1 and 256"
|
||||
"or <<_::size, _::_*unit>> with size and unit being non-negative integers"
|
||||
|
||||
compile_error(caller, message)
|
||||
end
|
||||
@@ -674,7 +661,7 @@ defmodule Kernel.Typespec do
|
||||
:elixir_errors.erl_warn(caller.line, caller.file, message)
|
||||
|
||||
# This may be generating an invalid typespec but we need to generate it
|
||||
# to avoid breaking existing code that was valid but only broke Dialyzer
|
||||
# to avoid breaking existing code that was valid but only broke dialyzer
|
||||
{right, state} = typespec(expr, vars, caller, state)
|
||||
{{:ann_type, line(meta), [{:var, line(var_meta), var_name}, right]}, state}
|
||||
|
||||
@@ -693,7 +680,7 @@ defmodule Kernel.Typespec do
|
||||
:elixir_errors.erl_warn(caller.line, caller.file, message)
|
||||
|
||||
# This may be generating an invalid typespec but we need to generate it
|
||||
# to avoid breaking existing code that was valid but only broke Dialyzer
|
||||
# to avoid breaking existing code that was valid but only broke dialyzer
|
||||
state = %{state | undefined_type_error_enabled?: false}
|
||||
{left, state} = typespec(left, vars, caller, state)
|
||||
state = %{state | undefined_type_error_enabled?: true}
|
||||
@@ -738,19 +725,14 @@ defmodule Kernel.Typespec do
|
||||
# aliases in typespecs as compile time dependencies.
|
||||
remote = Macro.expand(remote, %{caller | function: {:typespec, 0}})
|
||||
|
||||
cond do
|
||||
not is_atom(remote) ->
|
||||
compile_error(caller, "invalid remote in typespec: #{Macro.to_string(orig)}")
|
||||
|
||||
remote == caller.module ->
|
||||
typespec({name, meta, args}, vars, caller, state)
|
||||
|
||||
true ->
|
||||
{remote_spec, state} = typespec(remote, vars, caller, state)
|
||||
{name_spec, state} = typespec(name, vars, caller, state)
|
||||
type = {remote_spec, meta, name_spec, args}
|
||||
remote_type(type, vars, caller, state)
|
||||
unless is_atom(remote) do
|
||||
compile_error(caller, "invalid remote in typespec: #{Macro.to_string(orig)}")
|
||||
end
|
||||
|
||||
{remote_spec, state} = typespec(remote, vars, caller, state)
|
||||
{name_spec, state} = typespec(name, vars, caller, state)
|
||||
type = {remote_spec, meta, name_spec, args}
|
||||
remote_type(type, vars, caller, state)
|
||||
end
|
||||
|
||||
# Handle tuples
|
||||
@@ -846,10 +828,7 @@ defmodule Kernel.Typespec do
|
||||
false ->
|
||||
if state.undefined_type_error_enabled? and
|
||||
not Map.has_key?(state.defined_type_pairs, {name, arity}) do
|
||||
compile_error(
|
||||
caller,
|
||||
"type #{name}/#{arity} undefined (no such type in #{inspect(caller.module)})"
|
||||
)
|
||||
compile_error(caller, "type #{name}/#{arity} undefined")
|
||||
end
|
||||
|
||||
state =
|
||||
|
||||
@@ -94,9 +94,6 @@ defmodule Kernel.Utils do
|
||||
fields = :lists.map(mapper, fields)
|
||||
enforce_keys = List.wrap(Module.get_attribute(module, :enforce_keys))
|
||||
|
||||
# TODO: Make it raise on v2.0
|
||||
warn_on_duplicate_struct_key(:lists.keysort(1, fields))
|
||||
|
||||
foreach = fn
|
||||
key when is_atom(key) ->
|
||||
:ok
|
||||
@@ -111,19 +108,6 @@ defmodule Kernel.Utils do
|
||||
{struct, enforce_keys, Module.get_attribute(module, :derive)}
|
||||
end
|
||||
|
||||
defp warn_on_duplicate_struct_key([]) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp warn_on_duplicate_struct_key([{key, _} | [{key, _} | _] = rest]) do
|
||||
IO.warn("duplicate key #{inspect(key)} found in struct")
|
||||
warn_on_duplicate_struct_key(rest)
|
||||
end
|
||||
|
||||
defp warn_on_duplicate_struct_key([_ | rest]) do
|
||||
warn_on_duplicate_struct_key(rest)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Announcing callback for defstruct.
|
||||
"""
|
||||
|
||||
+126
-242
@@ -1,13 +1,10 @@
|
||||
defmodule Keyword do
|
||||
@moduledoc """
|
||||
A keyword list is a list that consists exclusively of two-element tuples.
|
||||
A set of functions for working with keywords.
|
||||
|
||||
The first element of these tuples is known as the *key*, and it must be an atom.
|
||||
The second element, known as the *value*, can be any term.
|
||||
|
||||
Keywords are mostly used to work with optional values.
|
||||
|
||||
## Examples
|
||||
A keyword list is a list of two-element tuples where the first
|
||||
element of the tuple is an atom and the second element
|
||||
can be any value.
|
||||
|
||||
For example, the following is a keyword list:
|
||||
|
||||
@@ -18,82 +15,62 @@ defmodule Keyword do
|
||||
|
||||
[exit_on_close: true, active: :once, packet_size: 1024]
|
||||
|
||||
The two syntaxes are completely equivalent. Like atoms, keyword
|
||||
lists keys must be composed of Unicode characters such as letters,
|
||||
numbers, underscore, and `@`. If the keyword has a character that
|
||||
does not belong to the category above, such as spaces, you can wrap
|
||||
it in quotes:
|
||||
This is also the syntax that Elixir uses to inspect keyword lists:
|
||||
|
||||
iex> [{:active, :once}]
|
||||
[active: :once]
|
||||
|
||||
The two syntaxes are completely equivalent. Like atoms, keywords
|
||||
must be composed of Unicode characters such as letters, numbers,
|
||||
underscore, and `@`. If the keyword has a character that does not
|
||||
belong to the category above, such as spaces, you can wrap it in
|
||||
quotes:
|
||||
|
||||
iex> ["exit on close": true]
|
||||
["exit on close": true]
|
||||
|
||||
Wrapping a keyword in quotes does not make it a string. Keyword lists
|
||||
keys are always atoms. If you use quotes around the key when quoting
|
||||
is not necessary, Elixir will warn.
|
||||
Wrapping a keyword in quotes does not make it a string. Keywords are
|
||||
always atoms. If you use quotes when all characters are a valid part
|
||||
of a keyword without quotes, Elixir will warn.
|
||||
|
||||
## Duplicate keys and ordering
|
||||
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:
|
||||
|
||||
A keyword may have duplicated keys so it is not strictly a key-value
|
||||
data type. However most of the functions in this module behave exactly
|
||||
as a key-value so they work similarly to the functions you would find
|
||||
in the `Map` module. For example, `Keyword.get/3` will get the first
|
||||
entry matching the given key, regardless if duplicated entries exist.
|
||||
Similarly, `Keyword.put/3` and `Keyword.delete/2` ensure all duplicated
|
||||
entries for a given key are removed when invoked. Note, however, that
|
||||
keyword list operations need to traverse the whole list in order to find
|
||||
keys, so these operations are slower than their map counterparts.
|
||||
String.split("1-0", "-", trim: true, parts: 2)
|
||||
|
||||
A handful of functions exist to handle duplicated keys, for example,
|
||||
`get_values/2` returns all values for a given key and `delete_first/2`
|
||||
deletes just one of the existing entries.
|
||||
is equivalent to:
|
||||
|
||||
Even though lists preserve the user ordering, the functions in
|
||||
`Keyword` do not guarantee any ordering. For example, if you invoke
|
||||
`Keyword.put(opts, new_key, new_value)`, there is no guarantee to
|
||||
where `new_key` will be added (to the front, to the end, or
|
||||
anywhere else).
|
||||
String.split("1-0", "-", [trim: true, parts: 2])
|
||||
|
||||
Given ordering is not guaranteed, it is not recommended to pattern
|
||||
match on keyword lists either. For example, a function such as:
|
||||
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
|
||||
the functions you would find in the `Map` module.
|
||||
|
||||
def my_function([some_key: value, another_key: another_value])
|
||||
For example, `Keyword.get/3` will get the first entry matching
|
||||
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.
|
||||
|
||||
will match
|
||||
A handful of functions exist to handle duplicated keys, in
|
||||
particular, `Enum.into/2` allows creating new keywords without
|
||||
removing duplicated keys, `get_values/2` returns all values for
|
||||
a given key and `delete_first/2` deletes just one of the existing
|
||||
entries.
|
||||
|
||||
my_function([some_key: :foo, another_key: :bar])
|
||||
|
||||
but it won't match
|
||||
|
||||
my_function([another_key: :bar, some_key: :foo])
|
||||
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.
|
||||
|
||||
Most of the functions in this module work in linear time. This means
|
||||
that, the time it takes to perform an operation grows at the same
|
||||
rate as the length of the list.
|
||||
|
||||
## Call syntax
|
||||
|
||||
When keyword lists are passed as the last argument to a function,
|
||||
the square brackets around the keyword list can be omitted. For
|
||||
example, the keyword list syntax:
|
||||
|
||||
String.split("1-0", "-", [trim: true, parts: 2])
|
||||
|
||||
can be written without the enclosing brackets whenever it is the last
|
||||
argument of a function call:
|
||||
|
||||
String.split("1-0", "-", trim: true, parts: 2)
|
||||
|
||||
Since tuples, lists, maps, and others are treated the same as function
|
||||
calls in Elixir syntax, this property is also available to them:
|
||||
|
||||
iex> {1, 2, foo: :bar}
|
||||
{1, 2, [{:foo, :bar}]}
|
||||
|
||||
iex> [1, 2, foo: :bar]
|
||||
[1, 2, {:foo, :bar}]
|
||||
|
||||
iex> %{1 => 2, foo: :bar}
|
||||
%{1 => 2, :foo => :bar}
|
||||
"""
|
||||
|
||||
@compile :inline_list_funcs
|
||||
@@ -259,13 +236,13 @@ defmodule Keyword do
|
||||
Gets the value from `key` and updates it, all in one pass.
|
||||
|
||||
This `fun` argument receives the value of `key` (or `nil` if `key`
|
||||
is not present) and must return a two-element tuple: the current value
|
||||
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
|
||||
keyword list and returned.
|
||||
|
||||
The returned value is a tuple with the current value returned by
|
||||
The returned value is a tuple with the "get" value returned by
|
||||
`fun` and a new keyword list with the updated value under `key`.
|
||||
|
||||
## Examples
|
||||
@@ -287,9 +264,7 @@ defmodule Keyword do
|
||||
{nil, [a: 1]}
|
||||
|
||||
"""
|
||||
@spec get_and_update(t, key, (value -> {current_value, new_value :: value} | :pop)) ::
|
||||
{current_value, value}
|
||||
when current_value: value
|
||||
@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)
|
||||
@@ -326,11 +301,11 @@ defmodule Keyword do
|
||||
Gets the value from `key` and updates it. Raises if there is no `key`.
|
||||
|
||||
This `fun` argument receives the value of `key` and must return a
|
||||
two-element tuple: the current value (the retrieved value, which can be
|
||||
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 returned value is a tuple with the current value returned by `fun` and a new
|
||||
The returned value is a tuple with the "get" value returned by `fun` and a new
|
||||
keyword list with the updated value under `key`.
|
||||
|
||||
## Examples
|
||||
@@ -351,9 +326,7 @@ defmodule Keyword do
|
||||
{1, []}
|
||||
|
||||
"""
|
||||
@spec get_and_update!(t, key, (value -> {current_value, new_value :: value} | :pop)) ::
|
||||
{current_value, t}
|
||||
when current_value: value
|
||||
@spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} when get: term
|
||||
def get_and_update!(keywords, key, fun) do
|
||||
get_and_update!(keywords, key, fun, [])
|
||||
end
|
||||
@@ -436,12 +409,13 @@ defmodule Keyword do
|
||||
"""
|
||||
@spec get_values(t, key) :: [value]
|
||||
def get_values(keywords, key) when is_list(keywords) and is_atom(key) do
|
||||
get_values(keywords, key, [])
|
||||
end
|
||||
fun = fn
|
||||
{^key, val} -> {true, val}
|
||||
{_, _} -> false
|
||||
end
|
||||
|
||||
defp get_values([{key, value} | tail], key, values), do: get_values(tail, key, [value | values])
|
||||
defp get_values([{_, _} | tail], key, values), do: get_values(tail, key, values)
|
||||
defp get_values([], _key, values), do: :lists.reverse(values)
|
||||
:lists.filtermap(fun, keywords)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all keys from the keyword list.
|
||||
@@ -452,30 +426,13 @@ defmodule Keyword do
|
||||
|
||||
iex> Keyword.keys(a: 1, b: 2)
|
||||
[:a, :b]
|
||||
|
||||
iex> Keyword.keys(a: 1, b: 2, a: 3)
|
||||
[:a, :b, :a]
|
||||
|
||||
iex> Keyword.keys([{:a, 1}, {"b", 2}, {:c, 3}])
|
||||
** (ArgumentError) expected a keyword list, but an entry in the list is not a two-element tuple with an atom as its first element, got: {"b", 2}
|
||||
|
||||
"""
|
||||
@spec keys(t) :: [key]
|
||||
def keys(keywords) when is_list(keywords) do
|
||||
try do
|
||||
:lists.map(
|
||||
fn
|
||||
{key, _} when is_atom(key) -> key
|
||||
element -> throw(element)
|
||||
end,
|
||||
keywords
|
||||
)
|
||||
catch
|
||||
element ->
|
||||
raise ArgumentError,
|
||||
"expected a keyword list, but an entry in the list is not a two-element tuple with an atom as its first element, " <>
|
||||
"got: #{inspect(element)}"
|
||||
end
|
||||
:lists.map(fn {k, _} -> k end, keywords)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -496,8 +453,24 @@ defmodule Keyword do
|
||||
:lists.map(fn {_, v} -> v end, keywords)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use Keyword.fetch/2 + Keyword.delete/2 instead"
|
||||
@doc """
|
||||
Deletes the entries in the keyword list for a `key` with `value`.
|
||||
|
||||
If no `key` with `value` exists, returns the keyword list unchanged.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.delete([a: 1, b: 2], :a, 1)
|
||||
[b: 2]
|
||||
iex> Keyword.delete([a: 1, b: 2, a: 3], :a, 3)
|
||||
[a: 1, b: 2]
|
||||
iex> Keyword.delete([a: 1], :a, 5)
|
||||
[a: 1]
|
||||
iex> Keyword.delete([a: 1], :b, 5)
|
||||
[a: 1]
|
||||
|
||||
"""
|
||||
@spec delete(t, key, value) :: t
|
||||
def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do
|
||||
case :lists.keymember(key, 1, keywords) do
|
||||
true -> delete_key_value(keywords, key, value)
|
||||
@@ -543,9 +516,17 @@ defmodule Keyword do
|
||||
end
|
||||
end
|
||||
|
||||
defp delete_key([{key, _} | tail], key), do: delete_key(tail, key)
|
||||
defp delete_key([{_, _} = pair | tail], key), do: [pair | delete_key(tail, key)]
|
||||
defp delete_key([], _key), do: []
|
||||
defp delete_key([{key, _} | tail], key) do
|
||||
delete_key(tail, key)
|
||||
end
|
||||
|
||||
defp delete_key([{_, _} = pair | tail], key) do
|
||||
[pair | delete_key(tail, key)]
|
||||
end
|
||||
|
||||
defp delete_key([], _key) do
|
||||
[]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes the first entry in the keyword list for a specific `key`.
|
||||
@@ -650,50 +631,25 @@ defmodule Keyword do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Puts a value under `key` only if the `key` already exists in `keywords`.
|
||||
|
||||
In the case a value is stored multiple times in the keyword list,
|
||||
later occurrences are removed.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.replace([a: 1, b: 2, a: 4], :a, 3)
|
||||
[a: 3, b: 2]
|
||||
|
||||
iex> Keyword.replace([a: 1], :b, 2)
|
||||
[a: 1]
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec replace(t, key, value) :: t
|
||||
@doc false
|
||||
@deprecated "Use Keyword.fetch/2 + Keyword.put/3 instead"
|
||||
def replace(keywords, key, value) when is_list(keywords) and is_atom(key) do
|
||||
do_replace(keywords, key, value)
|
||||
end
|
||||
|
||||
defp do_replace([{key, _} | keywords], key, value) do
|
||||
[{key, value} | delete(keywords, key)]
|
||||
end
|
||||
|
||||
defp do_replace([{_, _} = e | keywords], key, value) do
|
||||
[e | do_replace(keywords, key, value)]
|
||||
end
|
||||
|
||||
defp do_replace([], _key, _value) do
|
||||
[]
|
||||
case :lists.keyfind(key, 1, keywords) do
|
||||
{^key, _} -> [{key, value} | delete(keywords, key)]
|
||||
false -> keywords
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Puts a value under `key` only if the `key` already exists in `keywords`.
|
||||
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: 3], :a, :new)
|
||||
[a: :new, b: 2]
|
||||
iex> Keyword.replace!([a: 1, b: 2, c: 3, b: 4], :b, :new)
|
||||
[a: 1, b: :new, c: 3]
|
||||
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]
|
||||
@@ -702,19 +658,10 @@ defmodule Keyword do
|
||||
@doc since: "1.5.0"
|
||||
@spec replace!(t, key, value) :: t
|
||||
def replace!(keywords, key, value) when is_list(keywords) and is_atom(key) do
|
||||
replace!(keywords, key, value, keywords)
|
||||
end
|
||||
|
||||
defp replace!([{key, _} | keywords], key, value, _original) do
|
||||
[{key, value} | delete(keywords, key)]
|
||||
end
|
||||
|
||||
defp replace!([{_, _} = e | keywords], key, value, original) do
|
||||
[e | replace!(keywords, key, value, original)]
|
||||
end
|
||||
|
||||
defp replace!([], key, _value, original) do
|
||||
raise(KeyError, key: key, term: original)
|
||||
case :lists.keyfind(key, 1, keywords) do
|
||||
{^key, _} -> [{key, value} | delete(keywords, key)]
|
||||
false -> raise KeyError, key: key, term: keywords
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -874,68 +821,64 @@ defmodule Keyword do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.update!([a: 1, b: 2, a: 3], :a, &(&1 * 2))
|
||||
[a: 2, b: 2]
|
||||
iex> Keyword.update!([a: 1, b: 2, c: 3], :b, &(&1 * 2))
|
||||
[a: 1, b: 4, c: 3]
|
||||
iex> Keyword.update!([a: 1], :a, &(&1 * 2))
|
||||
[a: 2]
|
||||
iex> Keyword.update!([a: 1, a: 2], :a, &(&1 * 2))
|
||||
[a: 2]
|
||||
|
||||
iex> Keyword.update!([a: 1], :b, &(&1 * 2))
|
||||
** (KeyError) key :b not found in: [a: 1]
|
||||
|
||||
"""
|
||||
@spec update!(t, key, (current_value :: value -> new_value :: value)) :: t
|
||||
@spec update!(t, key, (value -> value)) :: t
|
||||
def update!(keywords, key, fun)
|
||||
when is_list(keywords) and is_atom(key) and is_function(fun, 1) do
|
||||
update!(keywords, key, fun, keywords)
|
||||
end
|
||||
|
||||
defp update!([{key, value} | keywords], key, fun, _original) do
|
||||
defp update!([{key, value} | keywords], key, fun, _dict) do
|
||||
[{key, fun.(value)} | delete(keywords, key)]
|
||||
end
|
||||
|
||||
defp update!([{_, _} = e | keywords], key, fun, original) do
|
||||
[e | update!(keywords, key, fun, original)]
|
||||
defp update!([{_, _} = e | keywords], key, fun, dict) do
|
||||
[e | update!(keywords, key, fun, dict)]
|
||||
end
|
||||
|
||||
defp update!([], key, _fun, original) when is_atom(key) do
|
||||
raise(KeyError, key: key, term: original)
|
||||
defp update!([], key, _fun, dict) when is_atom(key) do
|
||||
raise(KeyError, key: key, term: dict)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the `key` in `keywords` with the given function.
|
||||
|
||||
If the `key` does not exist, it inserts the given `default` value.
|
||||
If the `key` does not exist, inserts the given `initial` value.
|
||||
|
||||
If there are duplicated keys, they are all removed and only the first one
|
||||
is updated.
|
||||
|
||||
The default value will not be passed through the update function.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.update([a: 1], :a, 13, fn existing_value -> existing_value * 2 end)
|
||||
iex> Keyword.update([a: 1], :a, 13, &(&1 * 2))
|
||||
[a: 2]
|
||||
|
||||
iex> Keyword.update([a: 1, a: 2], :a, 13, fn existing_value -> existing_value * 2 end)
|
||||
iex> Keyword.update([a: 1, a: 2], :a, 13, &(&1 * 2))
|
||||
[a: 2]
|
||||
|
||||
iex> Keyword.update([a: 1], :b, 11, fn existing_value -> existing_value * 2 end)
|
||||
iex> Keyword.update([a: 1], :b, 11, &(&1 * 2))
|
||||
[a: 1, b: 11]
|
||||
|
||||
"""
|
||||
@spec update(t, key, default :: value, (existing_value :: value -> updated_value :: value)) :: t
|
||||
def update(keywords, key, default, fun)
|
||||
@spec update(t, key, value, (value -> value)) :: t
|
||||
def update(keywords, key, initial, fun)
|
||||
|
||||
def update([{key, value} | keywords], key, _default, fun) do
|
||||
def update([{key, value} | keywords], key, _initial, fun) do
|
||||
[{key, fun.(value)} | delete(keywords, key)]
|
||||
end
|
||||
|
||||
def update([{_, _} = e | keywords], key, default, fun) do
|
||||
[e | update(keywords, key, default, fun)]
|
||||
def update([{_, _} = e | keywords], key, initial, fun) do
|
||||
[e | update(keywords, key, initial, fun)]
|
||||
end
|
||||
|
||||
def update([], key, default, _fun) when is_atom(key) do
|
||||
[{key, default}]
|
||||
def update([], key, initial, _fun) when is_atom(key) do
|
||||
[{key, initial}]
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1033,73 +976,14 @@ defmodule Keyword do
|
||||
@spec pop(t, key, value) :: {value, t}
|
||||
def pop(keywords, key, default \\ nil) when is_list(keywords) and is_atom(key) do
|
||||
case fetch(keywords, key) do
|
||||
{:ok, value} -> {value, delete(keywords, key)}
|
||||
:error -> {default, keywords}
|
||||
{:ok, value} ->
|
||||
{value, delete(keywords, key)}
|
||||
|
||||
:error ->
|
||||
{default, keywords}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the first value for `key` and removes all associated entries in the keyword list,
|
||||
raising if `key` is not present.
|
||||
|
||||
This function behaves like `pop/3`, but raises in cases the `key` is not present in the
|
||||
given `keywords`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.pop!([a: 1], :a)
|
||||
{1, []}
|
||||
iex> Keyword.pop!([a: 1, a: 2], :a)
|
||||
{1, []}
|
||||
iex> Keyword.pop!([a: 1], :b)
|
||||
** (KeyError) key :b not found in: [a: 1]
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec pop!(t, key) :: {value, t}
|
||||
def pop!(keywords, key) when is_list(keywords) and is_atom(key) do
|
||||
case fetch(keywords, key) do
|
||||
{:ok, value} -> {value, delete(keywords, key)}
|
||||
:error -> raise KeyError, key: key, term: keywords
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all values for `key` and removes all associated entries in the keyword list.
|
||||
|
||||
It returns a tuple where the first element is a list of values for `key` and the
|
||||
second element is a keyword list with all entries associated with `key` removed.
|
||||
If the `key` is not present in the keyword list, `{[], keyword_list}` is
|
||||
returned.
|
||||
|
||||
If you don't want to remove all the entries associated with `key` use `pop_first/3`
|
||||
instead, that function will remove only the first entry.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.pop_values([a: 1], :a)
|
||||
{[1], []}
|
||||
iex> Keyword.pop_values([a: 1], :b)
|
||||
{[], [a: 1]}
|
||||
iex> Keyword.pop_values([a: 1, a: 2], :a)
|
||||
{[1, 2], []}
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec pop_values(t, key) :: {[value], t}
|
||||
def pop_values(keywords, key) when is_list(keywords) and is_atom(key) do
|
||||
pop_values(:lists.reverse(keywords), key, [], [])
|
||||
end
|
||||
|
||||
defp pop_values([{key, value} | tail], key, values, acc),
|
||||
do: pop_values(tail, key, [value | values], acc)
|
||||
|
||||
defp pop_values([{_, _} = pair | tail], key, values, acc),
|
||||
do: pop_values(tail, key, values, [pair | acc])
|
||||
|
||||
defp pop_values([], _key, values, acc),
|
||||
do: {values, acc}
|
||||
|
||||
@doc """
|
||||
Lazily returns and removes all values associated with `key` in the keyword list.
|
||||
|
||||
|
||||
+21
-34
@@ -1,6 +1,19 @@
|
||||
defmodule List do
|
||||
@moduledoc """
|
||||
Linked lists hold zero, one, or more elements in the chosen order.
|
||||
Functions that work on (linked) lists.
|
||||
|
||||
Many of the functions provided for lists, which implement
|
||||
the `Enumerable` protocol, are found in the `Enum` module.
|
||||
|
||||
Additionally, the following functions and operators for lists are
|
||||
found in `Kernel`:
|
||||
|
||||
* `++/2`
|
||||
* `--/2`
|
||||
* `hd/1`
|
||||
* `tl/1`
|
||||
* `in/2`
|
||||
* `length/1`
|
||||
|
||||
Lists in Elixir are specified between square brackets:
|
||||
|
||||
@@ -56,17 +69,6 @@ defmodule List do
|
||||
time because they need to iterate through every element of the list, but
|
||||
`first/1` will run in constant time because it only needs the first element.
|
||||
|
||||
Lists also implement the `Enumerable` protocol, so many functions to work with
|
||||
lists are found in the `Enum` module. Additionally, the following functions and
|
||||
operators for lists are found in `Kernel`:
|
||||
|
||||
* `++/2`
|
||||
* `--/2`
|
||||
* `hd/1`
|
||||
* `tl/1`
|
||||
* `in/2`
|
||||
* `length/1`
|
||||
|
||||
## Charlists
|
||||
|
||||
If a list is made of non-negative integers, where each integer represents a
|
||||
@@ -88,23 +90,10 @@ defmodule List do
|
||||
iex> 'abc'
|
||||
'abc'
|
||||
|
||||
Even though the representation changed, the raw data does remain a list of
|
||||
numbers, which can be handled as such:
|
||||
|
||||
iex> inspect('abc', charlists: :as_list)
|
||||
"[97, 98, 99]"
|
||||
iex> Enum.map('abc', fn num -> 1000 + num end)
|
||||
[1097, 1098, 1099]
|
||||
|
||||
You can use the `IEx.Helpers.i/1` helper to get a condensed rundown on
|
||||
charlists in IEx when you encounter them, which shows you the type, description
|
||||
and also the raw representation in one single summary.
|
||||
|
||||
The rationale behind this behaviour is to better support
|
||||
Erlang libraries which may return text as charlists
|
||||
instead of Elixir strings. In Erlang, charlists are the default
|
||||
way of handling strings, while in Elixir it's binaries. One
|
||||
example of such functions is `Application.loaded_applications/0`:
|
||||
instead of Elixir strings. One example of such functions
|
||||
is `Application.loaded_applications/0`:
|
||||
|
||||
Application.loaded_applications()
|
||||
#=> [
|
||||
@@ -857,8 +846,6 @@ defmodule List do
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
The base needs to be between `2` and `36`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.to_integer('3FF', 16)
|
||||
@@ -897,8 +884,8 @@ defmodule List do
|
||||
* integers representing Unicode code points
|
||||
* a list containing one of these three elements
|
||||
|
||||
Note that this function expects a list of integers representing
|
||||
Unicode code points. If you have a list of bytes, you must instead use
|
||||
Notice that this function expects a list of integers representing
|
||||
UTF-8 code points. If you have a list of bytes, you must instead use
|
||||
the [`:binary` module](http://www.erlang.org/doc/man/binary.html).
|
||||
|
||||
## Examples
|
||||
@@ -949,11 +936,11 @@ defmodule List do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a list of integers representing Unicode code points, lists or
|
||||
Converts a list of integers representing code points, lists or
|
||||
strings into a charlist.
|
||||
|
||||
Note that this function expects a list of integers representing
|
||||
Unicode code points. If you have a list of bytes, you must instead use
|
||||
Notice that this function expects a list of integers representing
|
||||
UTF-8 code points. If you have a list of bytes, you must instead use
|
||||
the [`:binary` module](http://www.erlang.org/doc/man/binary.html).
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -3,7 +3,7 @@ defprotocol List.Chars do
|
||||
The `List.Chars` protocol is responsible for
|
||||
converting a structure to a charlist (only if applicable).
|
||||
|
||||
The only function that must be implemented is
|
||||
The only function required to be implemented is
|
||||
`to_charlist/1` which does the conversion.
|
||||
|
||||
The `to_charlist/1` function automatically imported
|
||||
@@ -24,8 +24,6 @@ defprotocol List.Chars do
|
||||
end
|
||||
|
||||
defimpl List.Chars, for: Atom do
|
||||
def to_charlist(nil), do: ''
|
||||
|
||||
def to_charlist(atom), do: Atom.to_charlist(atom)
|
||||
end
|
||||
|
||||
|
||||
+71
-251
@@ -2,62 +2,16 @@ import Kernel, except: [to_string: 1]
|
||||
|
||||
defmodule Macro do
|
||||
@moduledoc ~S"""
|
||||
Macros are compile-time constructs that are invoked with Elixir's AST
|
||||
as input and a superset of Elixir's AST as output.
|
||||
|
||||
Let's see a simple example that shows the difference between functions and macros:
|
||||
|
||||
defmodule Example do
|
||||
defmacro macro_inspect(value) do
|
||||
IO.inspect(value)
|
||||
value
|
||||
end
|
||||
|
||||
def fun_inspect(value) do
|
||||
IO.inspect(value)
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
Now let's give it a try:
|
||||
|
||||
import Example
|
||||
|
||||
macro_inspect(1)
|
||||
#=> 1
|
||||
#=> 1
|
||||
|
||||
fun_inspect(1)
|
||||
#=> 1
|
||||
#=> 1
|
||||
|
||||
So far they behave the same, as we are passing an integer as argument.
|
||||
But what happens when we pass an expression:
|
||||
|
||||
macro_inspect(1 + 2)
|
||||
#=> {:+, [line: 3], [1, 2]}
|
||||
#=> 3
|
||||
|
||||
fun_inspect(1 + 2)
|
||||
#=> 3
|
||||
#=> 3
|
||||
|
||||
The macro receives the representation of the code given as argument,
|
||||
while a function receives the result of the code given as argument.
|
||||
A macro must return a superset of the code representation. See
|
||||
`t:input/0` and `t:output/0` for more information.
|
||||
|
||||
To learn more about Elixir's AST and how to build them programmatically,
|
||||
see `quote/2`.
|
||||
Conveniences for working with macros.
|
||||
|
||||
## Custom Sigils
|
||||
|
||||
Macros are also commonly used to implement custom sigils. To create a custom
|
||||
sigil, define a function with the name `sigil_{identifier}` that takes two
|
||||
arguments. The first argument will be the string, the second will be a charlist
|
||||
containing any modifiers. If the sigil is lower case (such as `sigil_x`) then
|
||||
the string argument will allow interpolation. If the sigil is upper case
|
||||
(such as `sigil_X`) then the string will not be interpolated.
|
||||
To create a custom sigil, define a function with the name
|
||||
`sigil_{identifier}` that takes two arguments. The first argument will be
|
||||
the string, the second will be a charlist containing any modifiers. If the
|
||||
sigil is lower case (such as `sigil_x`) then the string argument will allow
|
||||
interpolation. If the sigil is upper case (such as `sigil_X`) then the string
|
||||
will not be interpolated.
|
||||
|
||||
Valid modifiers include only lower and upper case letters. Other characters
|
||||
will cause a syntax error.
|
||||
@@ -105,95 +59,13 @@ defmodule Macro do
|
||||
alias Code.Identifier
|
||||
|
||||
@typedoc "Abstract Syntax Tree (AST)"
|
||||
@type t :: input
|
||||
@type t :: expr | literal
|
||||
|
||||
@typedoc "The inputs of a macro"
|
||||
@type input ::
|
||||
input_expr
|
||||
| {input, input}
|
||||
| [input]
|
||||
| atom
|
||||
| number
|
||||
| binary
|
||||
@typedoc "Represents expressions in the AST"
|
||||
@type expr :: {expr | atom, keyword, atom | [t]}
|
||||
|
||||
@typep input_expr :: {input_expr | atom, metadata, atom | [input]}
|
||||
|
||||
@typedoc "The output of a macro"
|
||||
@type output ::
|
||||
output_expr
|
||||
| {output, output}
|
||||
| [output]
|
||||
| atom
|
||||
| number
|
||||
| binary
|
||||
| captured_remote_function
|
||||
| pid
|
||||
|
||||
@typep output_expr :: {output_expr | atom, metadata, atom | [output]}
|
||||
|
||||
@typedoc """
|
||||
A keyword list of AST metadata.
|
||||
|
||||
The metadata in Elixir AST is a keyword list of values. Any key can be used
|
||||
and different parts of the compiler may use different keys. For example,
|
||||
the AST received by a macro will always include the `:line` annotation,
|
||||
while the AST emitted by `quote/2` will only have the `:line` annotation if
|
||||
the `:line` option is provided.
|
||||
|
||||
The following metadata keys are public:
|
||||
|
||||
* `:context` - Defines the context in which the AST was generated.
|
||||
For example, `quote/2` will include the module calling `quote/2`
|
||||
as the context. This is often used to distinguish regular code from code
|
||||
generated by a macro or by `quote/2`.
|
||||
* `:counter` - The variable counter used for variable hygiene. In terms of
|
||||
the compiler, each variable is identified by the combination of either
|
||||
`name` and `metadata[:counter]`, or `name` and `context`.
|
||||
* `:generated` - Whether the code should be considered as generated by
|
||||
the compiler or not. This means the compiler and tools like Dialyzer may not
|
||||
emit certain warnings.
|
||||
* `:keep` - Used by `quote/2` with the option `location: :keep` to annotate
|
||||
the file and the line number of the quoted source.
|
||||
* `:line` - The line number of the AST node.
|
||||
|
||||
The following metadata keys are enabled by `Code.string_to_quoted/2`:
|
||||
|
||||
* `:closing` - contains metadata about the closing pair, such as a `}`
|
||||
in a tuple or in a map, or such as the closing `)` in a function call
|
||||
with parens. The `:closing` does not delimit the end of expression if
|
||||
there are `:do` and `:end` metadata (when `:token_metadata` is true)
|
||||
* `:column` - the column number of the AST node (when `:columns` is true)
|
||||
* `:delimiter` - contains the opening delimiter for sigils, strings,
|
||||
and charlists as a string (such as `"{"`, `"/"`, `"'"`, and the like)
|
||||
* `:format` - set to `:keyword` when an atom is defined as a keyword
|
||||
* `:do` - contains metadata about the `do` location in a function call with
|
||||
`do/end` blocks (when `:token_metadata` is true)
|
||||
* `:end` - contains metadata about the `end` location in a function call with
|
||||
`do/end` blocks (when `:token_metadata` is true)
|
||||
* `:end_of_expression` - denotes when the end of expression effectively
|
||||
happens. Available for all expressions except the last one inside a
|
||||
`__block__` (when `:token_metadata` is true)
|
||||
* `:indentation` - indentation of a sigil heredoc
|
||||
|
||||
The following metadata keys are private:
|
||||
|
||||
* `:alias` - Used for alias hygiene.
|
||||
* `:ambiguous_op` - Used for improved error messages in the compiler.
|
||||
* `:import` - Used for import hygiene.
|
||||
* `:var` - Used for improved error messages on undefined variables.
|
||||
|
||||
Do not rely on them as they may change or be fully removed in future versions
|
||||
of the language. They are often used by `quote/2` and the compiler to provide
|
||||
features like hygiene, better error messages, and so forth.
|
||||
|
||||
If you introduce custom keys into the AST metadata, please make sure to prefix
|
||||
them with the name of your library or application, so that they will not conflict
|
||||
with keys that could potentially be introduced by the compiler in the future.
|
||||
"""
|
||||
@type metadata :: keyword
|
||||
|
||||
@typedoc "A captured remote function in the format of &Mod.fun/arity"
|
||||
@type captured_remote_function :: fun
|
||||
@typedoc "Represents literals in the AST"
|
||||
@type literal :: atom | number | binary | fun | {t, t} | [t]
|
||||
|
||||
@doc """
|
||||
Breaks a pipeline expression into a list.
|
||||
@@ -266,7 +138,7 @@ defmodule Macro do
|
||||
end
|
||||
|
||||
# {:fn, _, _} is what we get when we pipe into an anonymous function without
|
||||
# calling it, for example, `:foo |> (fn x -> x end)`.
|
||||
# calling it, e.g., `:foo |> (fn x -> x end)`.
|
||||
def pipe(expr, {:fn, _, _}, _integer) do
|
||||
raise ArgumentError,
|
||||
"cannot pipe #{to_string(expr)} into an anonymous function without" <>
|
||||
@@ -278,26 +150,13 @@ defmodule Macro do
|
||||
{call, line, List.insert_at([], integer, expr)}
|
||||
end
|
||||
|
||||
def pipe(_expr, {op, _line, [arg]}, _integer) when op == :+ or op == :- do
|
||||
raise ArgumentError,
|
||||
"piping into a unary operator is not supported, please use the qualified name: " <>
|
||||
"Kernel.#{op}(#{to_string(arg)}), instead of #{op}#{to_string(arg)}"
|
||||
end
|
||||
|
||||
def pipe(expr, {op, line, args} = op_args, integer) when is_list(args) do
|
||||
cond do
|
||||
is_atom(op) and Identifier.unary_op(op) != :error ->
|
||||
raise ArgumentError,
|
||||
"cannot pipe #{to_string(expr)} into #{to_string(op_args)}, " <>
|
||||
"the #{to_string(op)} operator can only take one argument"
|
||||
|
||||
is_atom(op) and Identifier.binary_op(op) != :error ->
|
||||
raise ArgumentError,
|
||||
"cannot pipe #{to_string(expr)} into #{to_string(op_args)}, " <>
|
||||
"the #{to_string(op)} operator can only take two arguments"
|
||||
|
||||
true ->
|
||||
{op, line, List.insert_at(args, integer, expr)}
|
||||
def pipe(expr, {call, line, args} = call_args, integer) when is_list(args) do
|
||||
if is_atom(call) and Identifier.binary_op(call) != :error do
|
||||
raise ArgumentError,
|
||||
"cannot pipe #{to_string(expr)} into #{to_string(call_args)}, " <>
|
||||
"the #{to_string(call)} operator can only take two arguments"
|
||||
else
|
||||
{call, line, List.insert_at(args, integer, expr)}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -533,7 +392,7 @@ defmodule Macro do
|
||||
As an example, `ExUnit` stores the AST of every assertion, so when
|
||||
an assertion fails we can show code snippets to users. Without this
|
||||
option, each time the test module is compiled, we get a different
|
||||
MD5 of the module bytecode, because the AST contains metadata,
|
||||
MD5 of the module byte code, because the AST contains metadata,
|
||||
such as counters, specific to the compilation environment. By pruning
|
||||
the metadata, we ensure that the module is deterministic and reduce
|
||||
the amount of data `ExUnit` needs to keep around.
|
||||
@@ -576,7 +435,7 @@ defmodule Macro do
|
||||
|
||||
This is useful when a struct needs to be expanded at
|
||||
compilation time and the struct being expanded may or may
|
||||
not have been compiled. This function is also capable of
|
||||
not have been compiled. This function is even capable of
|
||||
expanding structs defined under the module being compiled.
|
||||
|
||||
It will raise `CompileError` if the struct is not available.
|
||||
@@ -896,16 +755,6 @@ defmodule Macro do
|
||||
end
|
||||
|
||||
# All other calls
|
||||
def to_string({{:., _, [left, _]} = target, meta, []} = ast, fun) do
|
||||
to_string = call_to_string(target, fun)
|
||||
|
||||
if is_tuple(left) && meta[:no_parens] do
|
||||
fun.(ast, to_string)
|
||||
else
|
||||
fun.(ast, to_string <> "()")
|
||||
end
|
||||
end
|
||||
|
||||
def to_string({target, _, args} = ast, fun) when is_list(args) do
|
||||
with :error <- unary_call(ast, fun),
|
||||
:error <- binary_call(ast, fun),
|
||||
@@ -963,14 +812,10 @@ defmodule Macro do
|
||||
Kernel.inspect(value, limit: :infinity, printable_limit: :infinity)
|
||||
end
|
||||
|
||||
defp bitpart_to_string({:"::", meta, [left, right]} = ast, fun) do
|
||||
defp bitpart_to_string({:"::", _, [left, right]} = ast, fun) do
|
||||
result =
|
||||
if meta[:inferred_bitstring_spec] do
|
||||
to_string(left, fun)
|
||||
else
|
||||
op_to_string(left, fun, :"::", :left) <>
|
||||
"::" <> bitmods_to_string(right, fun, :"::", :right)
|
||||
end
|
||||
op_to_string(left, fun, :"::", :left) <>
|
||||
"::" <> bitmods_to_string(right, fun, :"::", :right)
|
||||
|
||||
fun.(ast, result)
|
||||
end
|
||||
@@ -1013,13 +858,7 @@ defmodule Macro do
|
||||
false
|
||||
end
|
||||
|
||||
defp interpolate(ast, fun), do: interpolate(ast, "\"", "\"", fun)
|
||||
|
||||
defp interpolate({:<<>>, _, [parts]}, left, right, _) when left in [~s["""\n], ~s['''\n]] do
|
||||
<<left::binary, parts::binary, right::binary>>
|
||||
end
|
||||
|
||||
defp interpolate({:<<>>, _, parts}, left, right, fun) do
|
||||
defp interpolate({:<<>>, _, parts}, fun) do
|
||||
parts =
|
||||
Enum.map_join(parts, "", fn
|
||||
{:"::", _, [{{:., _, [Kernel, :to_string]}, _, [arg]}, {:binary, _, _}]} ->
|
||||
@@ -1027,19 +866,12 @@ defmodule Macro do
|
||||
|
||||
binary when is_binary(binary) ->
|
||||
binary = inspect_no_limit(binary)
|
||||
binary = binary_part(binary, 1, byte_size(binary) - 2)
|
||||
escape_sigil(binary, left)
|
||||
binary_part(binary, 1, byte_size(binary) - 2)
|
||||
end)
|
||||
|
||||
<<left::binary, parts::binary, right::binary>>
|
||||
<<?", parts::binary, ?">>
|
||||
end
|
||||
|
||||
defp escape_sigil(parts, "("), do: String.replace(parts, ")", ~S"\)")
|
||||
defp escape_sigil(parts, "{"), do: String.replace(parts, "}", ~S"\}")
|
||||
defp escape_sigil(parts, "["), do: String.replace(parts, "]", ~S"\]")
|
||||
defp escape_sigil(parts, "<"), do: String.replace(parts, ">", ~S"\>")
|
||||
defp escape_sigil(parts, delimiter), do: String.replace(parts, delimiter, "\\#{delimiter}")
|
||||
|
||||
defp module_to_string(atom, _fun) when is_atom(atom) do
|
||||
inspect_no_limit(atom)
|
||||
end
|
||||
@@ -1099,22 +931,25 @@ defmodule Macro do
|
||||
:error
|
||||
end
|
||||
|
||||
defp sigil_call({sigil, meta, [{:<<>>, _, _} = parts, args]} = ast, fun)
|
||||
defp sigil_call({sigil, _, [{:<<>>, _, _} = parts, args]} = ast, fun)
|
||||
when is_atom(sigil) and is_list(args) do
|
||||
delimiter = Keyword.get(meta, :delimiter, "\"")
|
||||
{left, right} = delimiter_pair(delimiter)
|
||||
|
||||
case Atom.to_string(sigil) do
|
||||
<<"sigil_", name>> when name >= ?A and name <= ?Z ->
|
||||
args = sigil_args(args, fun)
|
||||
{:<<>>, _, [binary]} = parts
|
||||
formatted = <<?~, name, left::binary, binary::binary, right::binary, args::binary>>
|
||||
|
||||
formatted =
|
||||
if :binary.last(binary) == ?\n do
|
||||
binary = String.replace(binary, ~s["""], ~s["\\""])
|
||||
<<?~, name, ~s["""\n], binary::binary, ~s["""], sigil_args(args, fun)::binary>>
|
||||
else
|
||||
{left, right} = select_sigil_container(binary)
|
||||
<<?~, name, left, binary::binary, right, sigil_args(args, fun)::binary>>
|
||||
end
|
||||
|
||||
{:ok, fun.(ast, formatted)}
|
||||
|
||||
<<"sigil_", name>> when name >= ?a and name <= ?z ->
|
||||
args = sigil_args(args, fun)
|
||||
formatted = "~" <> <<name>> <> interpolate(parts, left, right, fun) <> args
|
||||
{:ok, fun.(ast, formatted)}
|
||||
{:ok, fun.(ast, "~" <> <<name>> <> interpolate(parts, fun) <> sigil_args(args, fun))}
|
||||
|
||||
_ ->
|
||||
:error
|
||||
@@ -1125,13 +960,17 @@ defmodule Macro do
|
||||
:error
|
||||
end
|
||||
|
||||
defp delimiter_pair("["), do: {"[", "]"}
|
||||
defp delimiter_pair("{"), do: {"{", "}"}
|
||||
defp delimiter_pair("("), do: {"(", ")"}
|
||||
defp delimiter_pair("<"), do: {"<", ">"}
|
||||
defp delimiter_pair("\"\"\""), do: {"\"\"\"\n", "\"\"\""}
|
||||
defp delimiter_pair("'''"), do: {"'''\n", "'''"}
|
||||
defp delimiter_pair(str), do: {str, str}
|
||||
defp select_sigil_container(binary) do
|
||||
cond do
|
||||
:binary.match(binary, ["\""]) == :nomatch -> {?", ?"}
|
||||
:binary.match(binary, ["\'"]) == :nomatch -> {?', ?'}
|
||||
:binary.match(binary, ["(", ")"]) == :nomatch -> {?(, ?)}
|
||||
:binary.match(binary, ["[", "]"]) == :nomatch -> {?[, ?]}
|
||||
:binary.match(binary, ["{", "}"]) == :nomatch -> {?{, ?}}
|
||||
:binary.match(binary, ["<", ">"]) == :nomatch -> {?<, ?>}
|
||||
true -> {?/, ?/}
|
||||
end
|
||||
end
|
||||
|
||||
defp sigil_args([], _fun), do: ""
|
||||
defp sigil_args(args, fun), do: fun.(args, List.to_string(args))
|
||||
@@ -1374,10 +1213,10 @@ defmodule Macro do
|
||||
elem(do_expand_once(ast, env), 0)
|
||||
end
|
||||
|
||||
defp do_expand_once({:__aliases__, meta, _} = original, env) do
|
||||
case :elixir_aliases.expand(original, env) do
|
||||
defp do_expand_once({:__aliases__, _, _} = original, env) do
|
||||
case :elixir_aliases.expand(original, env.aliases, env.macro_aliases, env.lexical_tracker) do
|
||||
receiver when is_atom(receiver) ->
|
||||
:elixir_env.trace({:alias_reference, meta, receiver}, env)
|
||||
:elixir_lexical.record_remote(receiver, env.function, env.lexical_tracker)
|
||||
{receiver, true}
|
||||
|
||||
aliases ->
|
||||
@@ -1386,7 +1225,7 @@ defmodule Macro do
|
||||
case :lists.all(&is_atom/1, aliases) do
|
||||
true ->
|
||||
receiver = :elixir_aliases.concat(aliases)
|
||||
:elixir_env.trace({:alias_reference, meta, receiver}, env)
|
||||
:elixir_lexical.record_remote(receiver, env.function, env.lexical_tracker)
|
||||
{receiver, true}
|
||||
|
||||
false ->
|
||||
@@ -1413,9 +1252,17 @@ defmodule Macro do
|
||||
end
|
||||
end
|
||||
|
||||
defp do_expand_once({atom, meta, context} = original, _env)
|
||||
# Expand possible macro import invocation
|
||||
defp do_expand_once({atom, meta, context} = original, env)
|
||||
when is_atom(atom) and is_list(meta) and is_atom(context) do
|
||||
{original, false}
|
||||
if Macro.Env.has_var?(env, {atom, Keyword.get(meta, :counter, context)}) do
|
||||
{original, false}
|
||||
else
|
||||
case do_expand_once({atom, meta, []}, env) do
|
||||
{_, true} = exp -> exp
|
||||
{_, false} -> {original, false}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp do_expand_once({atom, meta, args} = original, env)
|
||||
@@ -1500,46 +1347,19 @@ defmodule Macro do
|
||||
def operator?(name, arity) when is_atom(name) and is_integer(arity), do: false
|
||||
|
||||
@doc """
|
||||
Returns `true` if the given quoted expression represents a quoted literal.
|
||||
|
||||
Atoms, numbers, and functions are always literals. Binaries, lists, tuples,
|
||||
maps, and structs are only literals if all of their terms are also literals.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Macro.quoted_literal?(quote(do: "foo"))
|
||||
true
|
||||
iex> Macro.quoted_literal?(quote(do: {"foo", 1}))
|
||||
true
|
||||
iex> Macro.quoted_literal?(quote(do: {"foo", 1, :baz}))
|
||||
true
|
||||
iex> Macro.quoted_literal?(quote(do: %{foo: "bar"}))
|
||||
true
|
||||
iex> Macro.quoted_literal?(quote(do: %URI{path: "/"}))
|
||||
true
|
||||
iex> Macro.quoted_literal?(quote(do: URI.parse("/")))
|
||||
false
|
||||
iex> Macro.quoted_literal?(quote(do: {foo, var}))
|
||||
false
|
||||
|
||||
Returns `true` if the given quoted expression is an AST literal.
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec quoted_literal?(t) :: boolean
|
||||
@spec quoted_literal?(literal) :: true
|
||||
@spec quoted_literal?(expr) :: false
|
||||
def quoted_literal?(term)
|
||||
|
||||
def quoted_literal?({:__aliases__, _, args}),
|
||||
do: quoted_literal?(args)
|
||||
|
||||
def quoted_literal?({:%, _, [left, right]}),
|
||||
do: quoted_literal?(left) and quoted_literal?(right)
|
||||
|
||||
def quoted_literal?({:%{}, _, args}), do: quoted_literal?(args)
|
||||
def quoted_literal?({:{}, _, args}), do: quoted_literal?(args)
|
||||
def quoted_literal?({left, right}), do: quoted_literal?(left) and quoted_literal?(right)
|
||||
def quoted_literal?(list) when is_list(list), do: Enum.all?(list, "ed_literal?/1)
|
||||
|
||||
def quoted_literal?(term),
|
||||
do: is_atom(term) or is_number(term) or is_binary(term) or is_function(term)
|
||||
def quoted_literal?(term) do
|
||||
is_atom(term) or is_number(term) or is_binary(term) or is_function(term)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives an AST node and expands it until it can no longer
|
||||
|
||||
+66
-77
@@ -21,31 +21,31 @@ defmodule Macro.Env do
|
||||
|
||||
It contains the following fields:
|
||||
|
||||
* `aliases` - a list of two-element tuples, where the first
|
||||
element is the aliased name and the second one the actual name
|
||||
* `context` - the context of the environment; it can be `nil`
|
||||
(default context), `:guard` (inside a guard) or `:match` (inside a match)
|
||||
* `context_modules` - a list of modules defined in the current context
|
||||
* `module` - the current module name
|
||||
* `file` - the current file name as a binary
|
||||
* `line` - the current line as an integer
|
||||
* `function` - a tuple as `{atom, integer}`, where the first
|
||||
element is the function name and the second its arity; returns
|
||||
`nil` if not inside a function
|
||||
* `functions` - a list of functions imported from each module
|
||||
* `line` - the current line as an integer
|
||||
* `macro_aliases` - a list of aliases defined inside the current macro
|
||||
* `macros` - a list of macros imported from each module
|
||||
* `module` - the current module name
|
||||
* `context` - the context of the environment; it can be `nil`
|
||||
(default context), `:guard` (inside a guard) or `:match` (inside a match)
|
||||
* `aliases` - a list of two-element tuples, where the first
|
||||
element is the aliased name and the second one the actual name
|
||||
* `requires` - the list of required modules
|
||||
* `functions` - a list of functions imported from each module
|
||||
* `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
|
||||
|
||||
The following fields are private to Elixir's macro expansion mechanism and
|
||||
must not be accessed directly:
|
||||
The following fields pertain to variable handling and must not be accessed or
|
||||
relied on. To get a list of all variables, see `vars/1`:
|
||||
|
||||
* `contextual_vars`
|
||||
* `current_vars`
|
||||
* `lexical_tracker`
|
||||
* `prematch_vars`
|
||||
* `tracers`
|
||||
* `unused_vars`
|
||||
* `prematch_vars`
|
||||
* `contextual_vars`
|
||||
|
||||
The following fields are deprecated and must not be accessed or relied on:
|
||||
|
||||
@@ -53,80 +53,69 @@ defmodule Macro.Env do
|
||||
|
||||
"""
|
||||
|
||||
@type aliases :: [{module, module}]
|
||||
@type context :: :match | :guard | nil
|
||||
@type context_modules :: [module]
|
||||
@type file :: binary
|
||||
@type functions :: [{module, [name_arity]}]
|
||||
@type lexical_tracker :: pid | nil
|
||||
@type line :: non_neg_integer
|
||||
@type macro_aliases :: [{module, {term, module}}]
|
||||
@type macros :: [{module, [name_arity]}]
|
||||
@type name_arity :: {atom, arity}
|
||||
@type file :: binary
|
||||
@type line :: non_neg_integer
|
||||
@type aliases :: [{module, module}]
|
||||
@type macro_aliases :: [{module, {term, module}}]
|
||||
@type context :: :match | :guard | nil
|
||||
@type requires :: [module]
|
||||
@type functions :: [{module, [name_arity]}]
|
||||
@type macros :: [{module, [name_arity]}]
|
||||
@type context_modules :: [module]
|
||||
@type lexical_tracker :: pid | nil
|
||||
@type variable :: {atom, atom | term}
|
||||
|
||||
@typep contextual_vars :: [atom]
|
||||
@typep current_vars ::
|
||||
{%{optional(variable) => {var_version, var_type}},
|
||||
%{optional(variable) => {var_version, var_type}} | false}
|
||||
@typep unused_vars ::
|
||||
{%{optional({atom, var_version}) => non_neg_integer | false}, non_neg_integer}
|
||||
@typep prematch_vars ::
|
||||
{%{optional(variable) => {var_version, var_type}}, non_neg_integer}
|
||||
| :warn
|
||||
| :raise
|
||||
| :pin
|
||||
| :apply
|
||||
@typep tracers :: [module]
|
||||
@typep vars :: [variable]
|
||||
@typep var_type :: :term
|
||||
@typep var_version :: non_neg_integer
|
||||
@typep vars :: [variable]
|
||||
@typep unused_vars :: %{optional({variable, var_version}) => non_neg_integer | false}
|
||||
@typep current_vars :: %{optional(variable) => {var_version, var_type}}
|
||||
@typep prematch_vars :: current_vars | :warn | :raise | :pin | :apply
|
||||
@typep contextual_vars :: [atom]
|
||||
|
||||
@type t :: %{
|
||||
__struct__: __MODULE__,
|
||||
aliases: aliases,
|
||||
context: context,
|
||||
context_modules: context_modules,
|
||||
contextual_vars: contextual_vars,
|
||||
current_vars: current_vars,
|
||||
file: file,
|
||||
function: name_arity | nil,
|
||||
functions: functions,
|
||||
lexical_tracker: lexical_tracker,
|
||||
line: line,
|
||||
macro_aliases: macro_aliases,
|
||||
macros: macros,
|
||||
module: atom,
|
||||
prematch_vars: prematch_vars,
|
||||
unused_vars: unused_vars,
|
||||
file: file,
|
||||
line: line,
|
||||
function: name_arity | nil,
|
||||
context: context,
|
||||
requires: requires,
|
||||
tracers: tracers,
|
||||
vars: vars
|
||||
aliases: aliases,
|
||||
functions: functions,
|
||||
macros: macros,
|
||||
macro_aliases: macro_aliases,
|
||||
context_modules: context_modules,
|
||||
vars: vars,
|
||||
unused_vars: unused_vars,
|
||||
current_vars: current_vars,
|
||||
prematch_vars: prematch_vars,
|
||||
lexical_tracker: lexical_tracker,
|
||||
contextual_vars: contextual_vars
|
||||
}
|
||||
|
||||
# TODO: Remove :vars field on v2.0
|
||||
def __struct__ do
|
||||
%{
|
||||
__struct__: __MODULE__,
|
||||
aliases: [],
|
||||
context: nil,
|
||||
context_modules: [],
|
||||
contextual_vars: [],
|
||||
current_vars: {%{}, %{}},
|
||||
file: "nofile",
|
||||
function: nil,
|
||||
functions: [],
|
||||
lexical_tracker: nil,
|
||||
line: 0,
|
||||
macro_aliases: [],
|
||||
macros: [],
|
||||
module: nil,
|
||||
prematch_vars: :warn,
|
||||
file: "nofile",
|
||||
line: 0,
|
||||
function: nil,
|
||||
context: nil,
|
||||
requires: [],
|
||||
tracers: [],
|
||||
unused_vars: {%{}, 0},
|
||||
vars: []
|
||||
aliases: [],
|
||||
functions: [],
|
||||
macros: [],
|
||||
macro_aliases: [],
|
||||
context_modules: [],
|
||||
vars: [],
|
||||
unused_vars: %{},
|
||||
current_vars: %{},
|
||||
prematch_vars: :warn,
|
||||
lexical_tracker: nil,
|
||||
contextual_vars: []
|
||||
}
|
||||
end
|
||||
|
||||
@@ -146,8 +135,8 @@ defmodule Macro.Env do
|
||||
@spec vars(t) :: [variable]
|
||||
def vars(env)
|
||||
|
||||
def vars(%{__struct__: Macro.Env, current_vars: {read, _}}) do
|
||||
Map.keys(read)
|
||||
def vars(%{__struct__: Macro.Env, current_vars: current_vars}) do
|
||||
Map.keys(current_vars)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -157,8 +146,8 @@ defmodule Macro.Env do
|
||||
@spec has_var?(t, variable) :: boolean()
|
||||
def has_var?(env, var)
|
||||
|
||||
def has_var?(%{__struct__: Macro.Env, current_vars: {read, _}}, var) do
|
||||
Map.has_key?(read, var)
|
||||
def has_var?(%{__struct__: Macro.Env, current_vars: current_vars}, var) do
|
||||
Map.has_key?(current_vars, var)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -180,8 +169,8 @@ defmodule Macro.Env do
|
||||
env
|
||||
end
|
||||
|
||||
def to_match(%{__struct__: Macro.Env, current_vars: {read, _}, unused_vars: {_, counter}} = env) do
|
||||
%{env | context: :match, prematch_vars: {read, counter}}
|
||||
def to_match(%{__struct__: Macro.Env, current_vars: vars} = env) do
|
||||
%{env | context: :match, prematch_vars: vars}
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
+67
-108
@@ -1,9 +1,15 @@
|
||||
defmodule Map do
|
||||
@moduledoc """
|
||||
Maps are the "go to" key-value data structure in Elixir.
|
||||
A set of functions for working with maps.
|
||||
|
||||
Maps can be created with the `%{}` syntax, and key-value pairs can be
|
||||
expressed as `key => value`:
|
||||
Many functions for maps, which implement the `Enumerable` protocol,
|
||||
are found in the `Enum` module. Additionally, the following functions
|
||||
for maps are found in `Kernel`:
|
||||
|
||||
* `map_size/1`
|
||||
|
||||
Maps are the "go to" key-value data structure in Elixir. Maps can be created
|
||||
with the `%{}` syntax, and key-value pairs can be expressed as `key => value`:
|
||||
|
||||
iex> %{}
|
||||
%{}
|
||||
@@ -37,19 +43,15 @@ defmodule Map do
|
||||
iex> map["non_existing_key"]
|
||||
nil
|
||||
|
||||
To access atom keys, one may also use the `map.key` notation. Note that `map.key`
|
||||
will raise a `KeyError` if the `map` doesn't contain the key `:key`, compared to
|
||||
`map[:key]`, that would return `nil`.
|
||||
For accessing atom keys, one may also `map.key`. Note that while `map[key]` will
|
||||
return `nil` if `map` doesn't contain `key`, `map.key` will raise if `map` doesn't
|
||||
contain the key `:key`.
|
||||
|
||||
map = %{foo: "bar", baz: "bong"}
|
||||
map.foo
|
||||
#=> "bar"
|
||||
map.non_existing_key
|
||||
#=> ** (KeyError) key :non_existing_key not found in: %{baz: "bong", foo: "bar"}
|
||||
|
||||
> Note: do not add parens when accessing fields, such as in `data.key()`.
|
||||
> If parenthesis are used, Elixir will consider it to be a function call
|
||||
> on `data`, which would be expected to be an atom.
|
||||
iex> map = %{foo: "bar", baz: "bong"}
|
||||
iex> map.foo
|
||||
"bar"
|
||||
iex> map.non_existing_key
|
||||
** (KeyError) key :non_existing_key not found in: %{baz: "bong", foo: "bar"}
|
||||
|
||||
The two syntaxes for accessing keys reveal the dual nature of maps. The `map[key]`
|
||||
syntax is used for dynamically created maps that may have any key, of any type.
|
||||
@@ -67,10 +69,8 @@ defmodule Map do
|
||||
iex> %{a: a} = %{:a => 1, "b" => 2, [:c, :e, :e] => 3}
|
||||
iex> a
|
||||
1
|
||||
|
||||
But this will raise a `MatchError` exception:
|
||||
|
||||
%{:c => 3} = %{:a => 1, 2 => :b}
|
||||
iex> %{:c => 3} = %{:a => 1, 2 => :b}
|
||||
** (MatchError) no match of right hand side value: %{2 => :b, :a => 1}
|
||||
|
||||
Variables can be used as map keys both when writing map literals as well as
|
||||
when matching:
|
||||
@@ -88,10 +88,8 @@ defmodule Map do
|
||||
iex> map = %{one: 1, two: 2}
|
||||
iex> %{map | one: "one"}
|
||||
%{one: "one", two: 2}
|
||||
|
||||
When a key that does not exist in the map is updated a `KeyError` exception will be raised:
|
||||
|
||||
%{map | three: 3}
|
||||
iex> %{map | three: 3}
|
||||
** (KeyError) key :three not found
|
||||
|
||||
The functions in this module that need to find a specific key work in logarithmic time.
|
||||
This means that the time it takes to find keys grows as the map grows, but it's not
|
||||
@@ -99,13 +97,6 @@ defmodule Map do
|
||||
it performs better because lists have a linear time complexity. Some functions,
|
||||
such as `keys/1` and `values/1`, run in linear time because they need to get to every
|
||||
element in the map.
|
||||
|
||||
Maps also implement the `Enumerable` protocol, so many functions to work with maps
|
||||
are found in the `Enum` module. Additionally, the following functions for maps are
|
||||
found in `Kernel`:
|
||||
|
||||
* `map_size/1`
|
||||
|
||||
"""
|
||||
|
||||
@type key :: any
|
||||
@@ -244,8 +235,8 @@ defmodule Map do
|
||||
@doc """
|
||||
Fetches the value for a specific `key` in the given `map`.
|
||||
|
||||
If `map` contains the given `key` then its value is returned in the shape of `{:ok, value}`.
|
||||
If `map` doesn't contain `key`, `:error` is returned.
|
||||
If `map` contains the given `key` with value `value`, then `{:ok, value}` is
|
||||
returned. If `map` doesn't contain `key`, `:error` is returned.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
@@ -264,7 +255,7 @@ defmodule Map do
|
||||
Fetches the value for a specific `key` in the given `map`, erroring out if
|
||||
`map` doesn't contain `key`.
|
||||
|
||||
If `map` contains `key`, the corresponding value is returned. If
|
||||
If `map` contains the given `key`, the corresponding value is returned. If
|
||||
`map` doesn't contain `key`, a `KeyError` exception is raised.
|
||||
|
||||
Inlined by the compiler.
|
||||
@@ -273,6 +264,8 @@ defmodule Map do
|
||||
|
||||
iex> Map.fetch!(%{a: 1}, :a)
|
||||
1
|
||||
iex> Map.fetch!(%{a: 1}, :b)
|
||||
** (KeyError) key :b not found in: %{a: 1}
|
||||
|
||||
"""
|
||||
@spec fetch!(map, key) :: value
|
||||
@@ -306,20 +299,8 @@ defmodule Map do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Puts a value under `key` only if the `key` already exists in `map`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Map.replace(%{a: 1, b: 2}, :a, 3)
|
||||
%{a: 3, b: 2}
|
||||
|
||||
iex> Map.replace(%{a: 1}, :b, 2)
|
||||
%{a: 1}
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec replace(map, key, value) :: map
|
||||
@doc false
|
||||
@deprecated "Use Map.fetch/2 + Map.put/3 instead"
|
||||
def replace(map, key, value) do
|
||||
case map do
|
||||
%{^key => _value} ->
|
||||
@@ -334,7 +315,8 @@ defmodule Map do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Puts a value under `key` only if the `key` already exists in `map`.
|
||||
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.
|
||||
|
||||
@@ -360,8 +342,8 @@ defmodule Map do
|
||||
in `map` unless `key` is already present.
|
||||
|
||||
This function is useful in case you want to compute the value to put under
|
||||
`key` only if `key` is not already present, as for example, when the value is expensive to
|
||||
calculate or generally difficult to setup and teardown again.
|
||||
`key` only if `key` is not already present (e.g., the value is expensive to
|
||||
calculate or generally difficult to setup and teardown again).
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -439,7 +421,7 @@ defmodule Map do
|
||||
@doc """
|
||||
Gets the value for a specific `key` in `map`.
|
||||
|
||||
If `key` is present in `map` then its value `value` is
|
||||
If `key` is present in `map` with value `value`, then `value` is
|
||||
returned. Otherwise, `default` is returned.
|
||||
|
||||
If `default` is not provided, `nil` is used.
|
||||
@@ -473,7 +455,7 @@ defmodule Map do
|
||||
@doc """
|
||||
Gets the value for a specific `key` in `map`.
|
||||
|
||||
If `key` is present in `map` then its value `value` is
|
||||
If `key` is present in `map` with value `value`, then `value` is
|
||||
returned. Otherwise, `fun` is evaluated and its result is returned.
|
||||
|
||||
This is useful if the default value is very expensive to calculate or
|
||||
@@ -601,39 +583,38 @@ defmodule Map do
|
||||
@doc """
|
||||
Updates the `key` in `map` with the given function.
|
||||
|
||||
If `key` is present in `map` then the existing value is passed to `fun` and its result is
|
||||
used as the updated value of `key`. If `key` is
|
||||
not present in `map`, `default` is inserted as the value of `key`. The default
|
||||
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.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Map.update(%{a: 1}, :a, 13, fn existing_value -> existing_value * 2 end)
|
||||
iex> Map.update(%{a: 1}, :a, 13, &(&1 * 2))
|
||||
%{a: 2}
|
||||
iex> Map.update(%{a: 1}, :b, 11, fn existing_value -> existing_value * 2 end)
|
||||
iex> Map.update(%{a: 1}, :b, 11, &(&1 * 2))
|
||||
%{a: 1, b: 11}
|
||||
|
||||
"""
|
||||
@spec update(map, key, default :: value, (existing_value :: value -> updated_value :: value)) ::
|
||||
map
|
||||
def update(map, key, default, fun) when is_function(fun, 1) 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} ->
|
||||
put(map, key, fun.(value))
|
||||
|
||||
%{} ->
|
||||
put(map, key, default)
|
||||
put(map, key, initial)
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other}, [map, key, default, fun])
|
||||
:erlang.error({:badmap, other}, [map, key, initial, fun])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Removes the value associated with `key` in `map` and returns the value and the updated map.
|
||||
Returns and removes the value associated with `key` in `map`.
|
||||
|
||||
If `key` is present in `map`, it returns `{value, new_map}` where `value` is the value of
|
||||
the key and `new_map` is the result of removing `key` from `map`. If `key`
|
||||
If `key` is present in `map` with value `value`, `{value, new_map}` is
|
||||
returned where `new_map` is the result of removing `key` from `map`. If `key`
|
||||
is not present in `map`, `{default, map}` is returned.
|
||||
|
||||
## Examples
|
||||
@@ -646,7 +627,7 @@ defmodule Map do
|
||||
{3, %{a: 1}}
|
||||
|
||||
"""
|
||||
@spec pop(map, key, value) :: {value, new_map :: map}
|
||||
@spec pop(map, key, value) :: {value, map}
|
||||
def pop(map, key, default \\ nil) do
|
||||
case :maps.take(key, map) do
|
||||
{_, _} = tuple -> tuple
|
||||
@@ -654,36 +635,11 @@ defmodule Map do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns and removes the value associated with `key` in `map` or raises
|
||||
if `key` is not present.
|
||||
|
||||
Behaves the same as `pop/3` but raises if `key` is not present in `map`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Map.pop!(%{a: 1}, :a)
|
||||
{1, %{}}
|
||||
iex> Map.pop!(%{a: 1, b: 2}, :a)
|
||||
{1, %{b: 2}}
|
||||
iex> Map.pop!(%{a: 1}, :b)
|
||||
** (KeyError) key :b not found in: %{a: 1}
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec pop!(map, key) :: {value, map}
|
||||
def pop!(map, key) do
|
||||
case :maps.take(key, map) do
|
||||
{_, _} = tuple -> tuple
|
||||
:error -> raise KeyError, key: key, term: map
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Lazily returns and removes the value associated with `key` in `map`.
|
||||
|
||||
If `key` is present in `map`, it returns `{value, new_map}` where `value` is the value of
|
||||
the key and `new_map` is the result of removing `key` from `map`. If `key`
|
||||
If `key` is present in `map` with value `value`, `{value, new_map}` is
|
||||
returned where `new_map` is the result of removing `key` from `map`. If `key`
|
||||
is not present in `map`, `{fun_result, map}` is returned, where `fun_result`
|
||||
is the result of applying `fun`.
|
||||
|
||||
@@ -705,9 +661,15 @@ defmodule Map do
|
||||
"""
|
||||
@spec pop_lazy(map, key, (() -> value)) :: {value, map}
|
||||
def pop_lazy(map, key, fun) when is_function(fun, 0) do
|
||||
case :maps.take(key, map) do
|
||||
{_, _} = tuple -> tuple
|
||||
:error -> {fun.(), map}
|
||||
case map do
|
||||
%{^key => value} ->
|
||||
{value, delete(map, key)}
|
||||
|
||||
%{} ->
|
||||
{fun.(), map}
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other}, [map, key, fun])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -799,8 +761,8 @@ defmodule Map do
|
||||
@doc """
|
||||
Updates `key` with the given function.
|
||||
|
||||
If `key` is present in `map` then the existing value is passed to `fun` and its result is
|
||||
used as the updated value of `key`. If `key` is
|
||||
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`, a `KeyError` exception is raised.
|
||||
|
||||
## Examples
|
||||
@@ -812,7 +774,7 @@ defmodule Map do
|
||||
** (KeyError) key :b not found in: %{a: 1}
|
||||
|
||||
"""
|
||||
@spec update!(map, key, (existing_value :: value -> updated_value :: value)) :: map
|
||||
@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))
|
||||
@@ -822,13 +784,13 @@ defmodule Map do
|
||||
Gets the value from `key` and updates it, all in one pass.
|
||||
|
||||
`fun` is called with the current value under `key` in `map` (or `nil` if `key`
|
||||
is not present in `map`) and must return a two-element tuple: the current value
|
||||
is not present in `map`) 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` in the resulting new map. `fun` may also
|
||||
return `:pop`, which means the current value shall be removed from `map` and
|
||||
returned (making this function behave like `Map.pop(map, key)`).
|
||||
|
||||
The returned value is a two-element tuple with the current value returned by
|
||||
The returned value is a tuple with the "get" value returned by
|
||||
`fun` and a new map with the updated value under `key`.
|
||||
|
||||
## Examples
|
||||
@@ -850,9 +812,7 @@ defmodule Map do
|
||||
{nil, %{a: 1}}
|
||||
|
||||
"""
|
||||
@spec get_and_update(map, key, (value -> {current_value, new_value :: value} | :pop)) ::
|
||||
{current_value, map}
|
||||
when current_value: value
|
||||
@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)
|
||||
|
||||
@@ -869,7 +829,7 @@ defmodule Map do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets the value from `key` and updates it, all in one pass. Raises if there is no `key`.
|
||||
Gets the value from `key` and updates it. Raises if there is no `key`.
|
||||
|
||||
Behaves exactly like `get_and_update/3`, but raises a `KeyError` exception if
|
||||
`key` is not present in `map`.
|
||||
@@ -892,9 +852,8 @@ defmodule Map do
|
||||
{1, %{}}
|
||||
|
||||
"""
|
||||
@spec get_and_update!(map, key, (value -> {current_value, new_value :: value} | :pop)) ::
|
||||
{current_value, map}
|
||||
when current_value: value
|
||||
@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
|
||||
value = fetch!(map, key)
|
||||
|
||||
|
||||
+38
-49
@@ -2,26 +2,14 @@ defmodule MapSet do
|
||||
@moduledoc """
|
||||
Functions that work on sets.
|
||||
|
||||
A set is a data structure that can contain unique elements of any kind,
|
||||
without any particular order. `MapSet` is the "go to" set data structure in Elixir.
|
||||
|
||||
A set can be constructed using `MapSet.new/0`:
|
||||
`MapSet` is the "go to" set data structure in Elixir. A set can be constructed
|
||||
using `MapSet.new/0`:
|
||||
|
||||
iex> MapSet.new()
|
||||
#MapSet<[]>
|
||||
|
||||
Elements in a set don't have to be of the same type and they can be
|
||||
populated from an [enumerable](`t:Enumerable.t/0`) using `MapSet.new/1`:
|
||||
|
||||
iex> MapSet.new([1, :two, {"three"}])
|
||||
#MapSet<[1, :two, {"three"}]>
|
||||
|
||||
Elements can be inserted using `MapSet.put/2`:
|
||||
|
||||
iex> MapSet.new([2]) |> MapSet.put(4) |> MapSet.put(0)
|
||||
#MapSet<[0, 2, 4]>
|
||||
|
||||
By definition, sets can't contain duplicate elements: when
|
||||
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.
|
||||
|
||||
@@ -117,7 +105,7 @@ defmodule MapSet do
|
||||
end
|
||||
|
||||
defp new_from_list([], acc) do
|
||||
Map.new(acc)
|
||||
:maps.from_list(acc)
|
||||
end
|
||||
|
||||
defp new_from_list([element | rest], acc) do
|
||||
@@ -125,7 +113,7 @@ defmodule MapSet do
|
||||
end
|
||||
|
||||
defp new_from_list_transform([], _fun, acc) do
|
||||
Map.new(acc)
|
||||
:maps.from_list(acc)
|
||||
end
|
||||
|
||||
defp new_from_list_transform([element | rest], fun, acc) do
|
||||
@@ -163,14 +151,14 @@ defmodule MapSet do
|
||||
@spec difference(t(val1), t(val2)) :: t(val1) when val1: value, val2: value
|
||||
def difference(map_set1, map_set2)
|
||||
|
||||
# If the first set is less than twice the size of the second map, it is fastest
|
||||
# to re-accumulate elements in the first set that are not present in the second set.
|
||||
# If the first set is less than twice the size of the second map,
|
||||
# it is fastest to re-accumulate elements 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
|
||||
|> :maps.iterator()
|
||||
|> :maps.next()
|
||||
|> Map.keys()
|
||||
|> filter_not_in(map2, [])
|
||||
|
||||
%MapSet{map: map}
|
||||
@@ -183,13 +171,12 @@ defmodule MapSet do
|
||||
%{map_set | map: Map.drop(map1, Map.keys(map2))}
|
||||
end
|
||||
|
||||
defp filter_not_in(:none, _map2, acc), do: Map.new(acc)
|
||||
defp filter_not_in([], _map2, acc), do: :maps.from_list(acc)
|
||||
|
||||
defp filter_not_in({key, _val, iter}, map2, acc) do
|
||||
if :erlang.is_map_key(key, map2) do
|
||||
filter_not_in(:maps.next(iter), map2, acc)
|
||||
else
|
||||
filter_not_in(:maps.next(iter), map2, [{key, @dummy_value} | 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])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -209,15 +196,19 @@ defmodule MapSet do
|
||||
{map1, map2} = order_by_size(map1, map2)
|
||||
|
||||
map1
|
||||
|> :maps.iterator()
|
||||
|> :maps.next()
|
||||
|> Map.keys()
|
||||
|> none_in?(map2)
|
||||
end
|
||||
|
||||
defp none_in?(:none, _), do: true
|
||||
defp none_in?([], _) do
|
||||
true
|
||||
end
|
||||
|
||||
defp none_in?({key, _val, iter}, map2) do
|
||||
not :erlang.is_map_key(key, map2) and none_in?(:maps.next(iter), map2)
|
||||
defp none_in?([key | rest], map2) do
|
||||
case map2 do
|
||||
%{^key => _} -> false
|
||||
_ -> none_in?(rest, map2)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -238,10 +229,10 @@ defmodule MapSet do
|
||||
Map.equal?(map1, map2)
|
||||
end
|
||||
|
||||
# Elixir v1.5 changed the map representation, so on
|
||||
# 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 all_in?(map1, map2)
|
||||
map_size(map1) == map_size(map2) and map_subset?(Map.keys(map1), map2)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -275,7 +266,7 @@ defmodule MapSet do
|
||||
"""
|
||||
@spec member?(t, value) :: boolean
|
||||
def member?(%MapSet{map: map}, value) do
|
||||
:erlang.is_map_key(value, map)
|
||||
match?(%{^value => _}, map)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -323,20 +314,19 @@ defmodule MapSet do
|
||||
"""
|
||||
@spec subset?(t, t) :: boolean
|
||||
def subset?(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
map_size(map1) <= map_size(map2) and all_in?(map1, map2)
|
||||
if map_size(map1) <= map_size(map2) do
|
||||
map1
|
||||
|> Map.keys()
|
||||
|> map_subset?(map2)
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
defp all_in?(:none, _), do: true
|
||||
defp map_subset?([], _), do: true
|
||||
|
||||
defp all_in?({key, _val, iter}, map2) do
|
||||
:erlang.is_map_key(key, map2) and all_in?(:maps.next(iter), map2)
|
||||
end
|
||||
|
||||
defp all_in?(map1, map2) when is_map(map1) and is_map(map2) do
|
||||
map1
|
||||
|> :maps.iterator()
|
||||
|> :maps.next()
|
||||
|> all_in?(map2)
|
||||
defp map_subset?([key | rest], map2) do
|
||||
match?(%{^key => _}, map2) and map_subset?(rest, map2)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -388,8 +378,7 @@ defmodule MapSet do
|
||||
end
|
||||
|
||||
def slice(map_set) do
|
||||
size = MapSet.size(map_set)
|
||||
{:ok, size, &Enumerable.List.slice(MapSet.to_list(map_set), &1, &2, size)}
|
||||
{:ok, MapSet.size(map_set), &Enumerable.List.slice(MapSet.to_list(map_set), &1, &2)}
|
||||
end
|
||||
|
||||
def reduce(map_set, acc, fun) do
|
||||
|
||||
+46
-125
@@ -56,9 +56,6 @@ defmodule Module do
|
||||
If the behaviour changes or `URI.HTTP` does not implement
|
||||
one of the callbacks, a warning will be raised.
|
||||
|
||||
For detailed documentation, see the
|
||||
[behaviour typespec documentation](typespecs.md#behaviours).
|
||||
|
||||
### `@impl`
|
||||
|
||||
To aid in the correct implementation of behaviours, you may optionally declare
|
||||
@@ -140,7 +137,7 @@ defmodule Module do
|
||||
end
|
||||
|
||||
The Mix compiler automatically looks for calls to deprecated modules
|
||||
and emit warnings during compilation.
|
||||
and emit warnings during compilation, computed via `mix xref warnings`.
|
||||
|
||||
Using the `@deprecated` attribute will also be reflected in the
|
||||
documentation of the given function and macro. You can choose between
|
||||
@@ -248,13 +245,8 @@ defmodule Module do
|
||||
attribute allows the module to annotate which external resources
|
||||
have been used.
|
||||
|
||||
Tools may use this information to ensure the module is recompiled
|
||||
in case any of the external resources change, see for example:
|
||||
[`mix compile.elixir`](https://hexdocs.pm/mix/Mix.Tasks.Compile.Elixir.html).
|
||||
|
||||
If the external resource does not exist, the module still has
|
||||
a dependency on it, causing the module be recompiled as soon
|
||||
as the file is added.
|
||||
Tools like Mix may use this information to ensure the module is
|
||||
recompiled in case any of the external resources change.
|
||||
|
||||
### `@file`
|
||||
|
||||
@@ -350,13 +342,11 @@ defmodule Module do
|
||||
behaviour callbacks are optional
|
||||
* `@impl` - declares an implementation of a callback function or macro
|
||||
|
||||
For detailed documentation, see the [typespec documentation](typespecs.md).
|
||||
|
||||
### Custom attributes
|
||||
|
||||
In addition to the built-in attributes outlined above, custom attributes may
|
||||
also be added. Custom attributes are expressed using the `@/1` operator followed
|
||||
by a valid variable name. The value given to the custom attribute must be a valid
|
||||
by a valid variable name. The value given to the custom attribute must be a valid
|
||||
Elixir value:
|
||||
|
||||
defmodule MyModule do
|
||||
@@ -380,7 +370,7 @@ defmodule Module do
|
||||
When just a module is provided, the function is assumed to be
|
||||
`__after_compile__/2`.
|
||||
|
||||
Callbacks will run in the order they are registered.
|
||||
Callbacks registered first will run last.
|
||||
|
||||
#### Example
|
||||
|
||||
@@ -404,11 +394,10 @@ defmodule Module do
|
||||
When just a module is provided, the function/macro is assumed to be
|
||||
`__before_compile__/1`.
|
||||
|
||||
Callbacks will run in the order they are registered. Any overridable
|
||||
definition will be made concrete before the first callback runs.
|
||||
A definition may be made overridable again in another before compile
|
||||
callback and it will be made concrete one last time after all callbacks
|
||||
run.
|
||||
Callbacks registered first will run last. Any overridable definition
|
||||
will be made concrete before the first callback runs. A definition may
|
||||
be made overridable again in another before compile callback and it
|
||||
will be made concrete one last time after after all callbacks run.
|
||||
|
||||
*Note*: unlike `@after_compile`, the callback function/macro must
|
||||
be placed in a separate module (because when the callback is invoked,
|
||||
@@ -446,6 +435,10 @@ defmodule Module do
|
||||
* the list of quoted guards
|
||||
* the quoted function body
|
||||
|
||||
Note the hook receives the quoted arguments and it is invoked before
|
||||
the function is stored in the module. So `Module.defines?/2` will return
|
||||
`false` for the first clause of every function.
|
||||
|
||||
If the function/macro being defined has multiple clauses, the hook will
|
||||
be called for each clause.
|
||||
|
||||
@@ -489,10 +482,10 @@ defmodule Module do
|
||||
below:
|
||||
|
||||
* `@compile :debug_info` - includes `:debug_info` regardless of the
|
||||
corresponding setting in `Code.get_compiler_option/1`
|
||||
corresponding setting in `Code.compiler_options/1`
|
||||
|
||||
* `@compile {:debug_info, false}` - disables `:debug_info` regardless
|
||||
of the corresponding setting in `Code.get_compiler_option/1`
|
||||
of the corresponding setting in `Code.compiler_options/1`
|
||||
|
||||
* `@compile {:inline, some_fun: 2, other_fun: 3}` - inlines the given
|
||||
name/arity pairs. Inlining is applied locally, calls from another
|
||||
@@ -502,10 +495,8 @@ defmodule Module do
|
||||
modules after compilation. Instead, the module will be loaded after
|
||||
it is dispatched to
|
||||
|
||||
* `@compile {:no_warn_undefined, Mod}` or
|
||||
`@compile {:no_warn_undefined, {Mod, fun, arity}}` - does not warn if
|
||||
the given module or the given `Mod.fun/arity` are not defined
|
||||
|
||||
You can see a handful more options used by the Erlang compiler in
|
||||
the documentation for the [`:compile` module](http://www.erlang.org/doc/man/compile.html).
|
||||
'''
|
||||
|
||||
@typep definition :: {atom, arity}
|
||||
@@ -615,7 +606,7 @@ defmodule Module do
|
||||
assert_not_compiled!(__ENV__.function, module)
|
||||
:elixir_def.reset_last(module)
|
||||
|
||||
{value, binding, _env} =
|
||||
{value, binding, _env, _scope} =
|
||||
:elixir.eval_quoted(quoted, binding, Keyword.put(opts, :module, module))
|
||||
|
||||
{value, binding}
|
||||
@@ -630,7 +621,7 @@ defmodule Module do
|
||||
|
||||
It returns a tuple of shape `{:module, module, binary, term}`
|
||||
where `module` is the module name, `binary` is the module
|
||||
bytecode and `term` is the result of the last expression in
|
||||
byte code and `term` is the result of the last expression in
|
||||
`quoted`.
|
||||
|
||||
Similar to `Kernel.defmodule/2`, the binary will only be
|
||||
@@ -1054,11 +1045,11 @@ defmodule Module do
|
||||
|
||||
"""
|
||||
@spec definitions_in(module, def_kind) :: [definition]
|
||||
def definitions_in(module, kind)
|
||||
when is_atom(module) and kind in [:def, :defp, :defmacro, :defmacrop] do
|
||||
def definitions_in(module, def_kind)
|
||||
when is_atom(module) and def_kind in [:def, :defp, :defmacro, :defmacrop] do
|
||||
assert_not_compiled!(__ENV__.function, module, @extra_error_msg_definitions_in)
|
||||
{set, _} = data_tables_for(module)
|
||||
:ets.select(set, [{{{:def, :"$1"}, kind, :_, :_, :_, :_}, [], [:"$1"]}])
|
||||
:lists.concat(:ets.match(set, {{:def, :"$1"}, def_kind, :_, :_, :_, :_}))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -1075,7 +1066,7 @@ defmodule Module do
|
||||
"""
|
||||
@spec make_overridable(module, [definition]) :: :ok
|
||||
def make_overridable(module, tuples) when is_atom(module) and is_list(tuples) do
|
||||
assert_not_readonly!(__ENV__.function, module)
|
||||
assert_not_compiled!(__ENV__.function, module)
|
||||
|
||||
func = fn
|
||||
{function_name, arity} = tuple
|
||||
@@ -1131,7 +1122,7 @@ defmodule Module do
|
||||
behaviour_definitions = bag_lookup_element(bag, {:accumulate, :behaviour}, 2)
|
||||
|
||||
cond do
|
||||
Code.ensure_compiled(behaviour) != {:module, behaviour} ->
|
||||
not Code.ensure_compiled?(behaviour) ->
|
||||
{:error, "it was not defined"}
|
||||
|
||||
not function_exported?(behaviour, :behaviour_info, 1) ->
|
||||
@@ -1236,42 +1227,6 @@ defmodule Module do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the given attribute has been defined.
|
||||
|
||||
An attribute is defined if it has been registered with `register_attribute/3`
|
||||
or assigned a value. If an attribute has been deleted with `delete_attribute/2`
|
||||
it is no longer considered defined.
|
||||
|
||||
This function can only be used on modules that have not yet been compiled.
|
||||
|
||||
## Examples
|
||||
|
||||
defmodule MyModule do
|
||||
@value 1
|
||||
Module.register_attribute(__MODULE__, :other_value)
|
||||
Module.put_attribute(__MODULE__, :another_value, 1)
|
||||
|
||||
Module.has_attribute?(__MODULE__, :value) #=> true
|
||||
Module.has_attribute?(__MODULE__, :other_value) #=> true
|
||||
Module.has_attribute?(__MODULE__, :another_value) #=> true
|
||||
|
||||
Module.has_attribute?(__MODULE__, :undefined) #=> false
|
||||
|
||||
Module.delete_attribute(__MODULE__, :value)
|
||||
Module.has_attribute?(__MODULE__, :value) #=> false
|
||||
end
|
||||
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec has_attribute?(module, atom) :: boolean
|
||||
def has_attribute?(module, key) when is_atom(module) and is_atom(key) do
|
||||
assert_not_compiled!(__ENV__.function, module)
|
||||
{set, _bag} = data_tables_for(module)
|
||||
|
||||
:ets.member(set, key)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes the module attribute that matches the given key.
|
||||
|
||||
@@ -1287,7 +1242,7 @@ defmodule Module do
|
||||
"""
|
||||
@spec delete_attribute(module, atom) :: term
|
||||
def delete_attribute(module, key) when is_atom(module) and is_atom(key) do
|
||||
assert_not_readonly!(__ENV__.function, module)
|
||||
assert_not_compiled!(__ENV__.function, module)
|
||||
{set, bag} = data_tables_for(module)
|
||||
|
||||
case :ets.lookup(set, key) do
|
||||
@@ -1339,7 +1294,7 @@ defmodule Module do
|
||||
@spec register_attribute(module, atom, [{:accumulate, boolean}, {:persist, boolean}]) :: :ok
|
||||
def register_attribute(module, attribute, options)
|
||||
when is_atom(module) and is_atom(attribute) and is_list(options) do
|
||||
assert_not_readonly!(__ENV__.function, module)
|
||||
assert_not_compiled!(__ENV__.function, module)
|
||||
{set, bag} = data_tables_for(module)
|
||||
|
||||
if Keyword.get(options, :persist) do
|
||||
@@ -1349,9 +1304,6 @@ defmodule Module do
|
||||
if Keyword.get(options, :accumulate) do
|
||||
:ets.insert_new(set, {attribute, [], :accumulate}) ||
|
||||
:ets.update_element(set, attribute, {3, :accumulate})
|
||||
else
|
||||
:ets.insert_new(bag, {:warn_attributes, attribute})
|
||||
:ets.insert_new(set, {attribute, nil, :unset})
|
||||
end
|
||||
|
||||
:ok
|
||||
@@ -1402,7 +1354,7 @@ defmodule Module do
|
||||
if doc, do: {:error, :private_doc}, else: :ok
|
||||
else
|
||||
{set, _bag} = data_tables_for(module)
|
||||
compile_doc(set, nil, line, kind, name, arity, signature, nil, doc, %{}, __ENV__, false)
|
||||
compile_doc(set, line, kind, name, arity, signature, nil, doc, %{}, __ENV__, false)
|
||||
:ok
|
||||
end
|
||||
end
|
||||
@@ -1415,17 +1367,16 @@ defmodule Module do
|
||||
{set, bag} = data_tables_for(module)
|
||||
{arity, defaults} = args_count(args, 0, 0)
|
||||
|
||||
context = Keyword.get(:ets.lookup_element(set, {:def, {name, arity}}, 3), :context)
|
||||
impl = compile_impl(set, bag, context, name, env, kind, arity, defaults)
|
||||
impl = compile_impl(set, bag, name, env, kind, arity, defaults)
|
||||
doc_meta = compile_doc_meta(set, bag, name, arity, defaults)
|
||||
|
||||
{line, doc} = get_doc_info(set, env)
|
||||
compile_doc(set, context, line, kind, name, arity, args, body, doc, doc_meta, env, impl)
|
||||
compile_doc(set, line, kind, name, arity, args, body, doc, doc_meta, env, impl)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp compile_doc(_table, _ctx, line, kind, name, arity, _args, _body, doc, _meta, env, _impl)
|
||||
defp compile_doc(_table, line, kind, name, arity, _args, _body, doc, _doc_meta, env, _impl)
|
||||
when kind in [:defp, :defmacrop] do
|
||||
if doc do
|
||||
message =
|
||||
@@ -1436,37 +1387,21 @@ defmodule Module do
|
||||
end
|
||||
end
|
||||
|
||||
defp compile_doc(table, ctx, line, kind, name, arity, args, body, doc, doc_meta, env, impl) do
|
||||
defp compile_doc(table, line, kind, name, arity, args, _body, doc, doc_meta, env, impl) do
|
||||
key = {doc_key(kind), name, arity}
|
||||
signature = build_signature(args, env)
|
||||
|
||||
case :ets.lookup(table, key) do
|
||||
[] ->
|
||||
doc = if is_nil(doc) && impl, do: false, else: doc
|
||||
:ets.insert(table, {key, ctx, line, signature, doc, doc_meta})
|
||||
|
||||
[{_, current_ctx, current_line, current_sign, current_doc, current_doc_meta}] ->
|
||||
if is_binary(current_doc) and is_binary(doc) and body != nil and is_nil(current_ctx) do
|
||||
message = ~s'''
|
||||
redefining @doc attribute previously set at line #{current_line}.
|
||||
|
||||
Please remove the duplicate docs. If instead you want to override a \
|
||||
previously defined @doc, attach the @doc attribute to a function head:
|
||||
|
||||
@doc """
|
||||
new docs
|
||||
"""
|
||||
def #{name}(...)
|
||||
'''
|
||||
|
||||
IO.warn(message, Macro.Env.stacktrace(%{env | line: line}))
|
||||
end
|
||||
:ets.insert(table, {key, line, signature, doc, doc_meta})
|
||||
|
||||
[{_, current_line, current_sign, current_doc, current_doc_meta}] ->
|
||||
signature = merge_signatures(current_sign, signature, 1)
|
||||
doc = if is_nil(doc), do: current_doc, else: doc
|
||||
doc = if is_nil(doc) && impl, do: false, else: doc
|
||||
doc_meta = Map.merge(current_doc_meta, doc_meta)
|
||||
:ets.insert(table, {key, ctx, current_line, signature, doc, doc_meta})
|
||||
:ets.insert(table, {key, current_line, signature, doc, doc_meta})
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1514,12 +1449,14 @@ defmodule Module do
|
||||
defp deprecated_reason(name, arity, reason),
|
||||
do: {:deprecated, {{name, arity}, reason}}
|
||||
|
||||
defp compile_impl(set, bag, context, name, env, kind, arity, defaults) do
|
||||
defp compile_impl(set, bag, name, env, kind, arity, defaults) do
|
||||
%{line: line, file: file} = env
|
||||
|
||||
case :ets.take(set, :impl) do
|
||||
[{:impl, value, _}] ->
|
||||
impl = {{name, arity}, context, defaults, kind, line, file, value}
|
||||
pair = {name, arity}
|
||||
meta = :ets.lookup_element(set, {:def, pair}, 3)
|
||||
impl = {pair, Keyword.get(meta, :context), defaults, kind, line, file, value}
|
||||
:ets.insert(bag, {:impls, impl})
|
||||
value
|
||||
|
||||
@@ -1557,7 +1494,7 @@ defmodule Module do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp check_behaviours(env, behaviours) do
|
||||
defp check_behaviours(%{lexical_tracker: pid} = env, behaviours) do
|
||||
Enum.reduce(behaviours, %{}, fn behaviour, acc ->
|
||||
cond do
|
||||
not is_atom(behaviour) ->
|
||||
@@ -1567,7 +1504,7 @@ defmodule Module do
|
||||
IO.warn(message, Macro.Env.stacktrace(env))
|
||||
acc
|
||||
|
||||
Code.ensure_compiled(behaviour) != {:module, behaviour} ->
|
||||
not Code.ensure_compiled?(behaviour) ->
|
||||
message =
|
||||
"@behaviour #{inspect(behaviour)} does not exist (in module #{inspect(env.module)})"
|
||||
|
||||
@@ -1582,7 +1519,7 @@ defmodule Module do
|
||||
acc
|
||||
|
||||
true ->
|
||||
:elixir_env.trace({:require, [], behaviour, []}, env)
|
||||
:elixir_lexical.record_remote(behaviour, nil, pid)
|
||||
optional_callbacks = behaviour_info(behaviour, :optional_callbacks)
|
||||
callbacks = behaviour_info(behaviour, :callbacks)
|
||||
Enum.reduce(callbacks, acc, &add_callback(&1, behaviour, env, optional_callbacks, &2))
|
||||
@@ -1834,11 +1771,11 @@ defmodule Module do
|
||||
[{_, _, :accumulate}] ->
|
||||
:lists.reverse(bag_lookup_element(bag, {:accumulate, key}, 2))
|
||||
|
||||
[{_, val, line}] when is_integer(line) ->
|
||||
:ets.update_element(set, key, {3, :used})
|
||||
[{_, val, nil}] ->
|
||||
val
|
||||
|
||||
[{_, val, _}] ->
|
||||
:ets.update_element(set, key, {3, nil})
|
||||
val
|
||||
|
||||
[] when is_integer(line) ->
|
||||
@@ -1859,7 +1796,7 @@ defmodule Module do
|
||||
# Used internally by Kernel's @.
|
||||
# This function is private and must be used only internally.
|
||||
def __put_attribute__(module, key, value, line) when is_atom(key) do
|
||||
assert_not_readonly!(__ENV__.function, module)
|
||||
assert_not_compiled!(__ENV__.function, module)
|
||||
{set, bag} = data_tables_for(module)
|
||||
value = preprocess_attribute(key, value)
|
||||
put_attribute(module, key, value, line, set, bag)
|
||||
@@ -1909,7 +1846,7 @@ defmodule Module do
|
||||
catch
|
||||
:error, :badarg ->
|
||||
:ets.insert(set, {:on_load, value, line})
|
||||
:ets.insert(bag, {:warn_attributes, :on_load})
|
||||
:ets.insert(bag, {:attributes, :on_load})
|
||||
else
|
||||
_ -> raise ArgumentError, "the @on_load attribute can only be set once per module"
|
||||
end
|
||||
@@ -1921,7 +1858,7 @@ defmodule Module do
|
||||
catch
|
||||
:error, :badarg ->
|
||||
:ets.insert(set, {key, value, line})
|
||||
:ets.insert(bag, {:warn_attributes, key})
|
||||
:ets.insert(bag, {:attributes, key})
|
||||
else
|
||||
:accumulate -> :ets.insert(bag, {{:accumulate, key}, value})
|
||||
_ -> :ets.insert(set, {key, value, line})
|
||||
@@ -2104,22 +2041,6 @@ defmodule Module do
|
||||
assert_not_compiled_message(function_name_arity, module, extra_msg)
|
||||
end
|
||||
|
||||
defp assert_not_readonly!({function_name, arity}, module) do
|
||||
case :elixir_module.mode(module) do
|
||||
:all ->
|
||||
:ok
|
||||
|
||||
:readonly ->
|
||||
raise ArgumentError,
|
||||
"could not call Module.#{function_name}/#{arity} because the module " <>
|
||||
"#{inspect(module)} is in read-only mode (@after_compile)"
|
||||
|
||||
:closed ->
|
||||
raise ArgumentError,
|
||||
assert_not_compiled_message({function_name, arity}, module, "")
|
||||
end
|
||||
end
|
||||
|
||||
defp assert_not_compiled_message({function_name, arity}, module, extra_msg) do
|
||||
mfa = "Module.#{function_name}/#{arity}"
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ defmodule Module.LocalsTracker do
|
||||
end
|
||||
|
||||
defp reachable?(tuple, :defmacrop, reachable, reattached) do
|
||||
# All private macros are unreachable unless they have been
|
||||
# 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
|
||||
|
||||
@@ -1,417 +0,0 @@
|
||||
defmodule Module.ParallelChecker do
|
||||
@moduledoc false
|
||||
|
||||
@type cache() :: {pid(), :ets.tid()}
|
||||
@type warning() :: term()
|
||||
@type kind() :: :def | :defmacro
|
||||
|
||||
@doc """
|
||||
Receives pairs of module maps and BEAM binaries. In parallel it verifies
|
||||
the modules and adds the ExCk chunk to the binaries. Returns the updated
|
||||
binaries and a list of warnings from the verification.
|
||||
"""
|
||||
@spec verify([{map(), binary()}], [{module(), binary()}], pos_integer() | nil) :: [warning()]
|
||||
def verify(compiled_modules, runtime_binaries, schedulers \\ nil) do
|
||||
compiled_maps = Enum.map(compiled_modules, fn {map, _binary} -> {map.module, map} end)
|
||||
|
||||
case compiled_maps ++ runtime_binaries do
|
||||
[] ->
|
||||
[]
|
||||
|
||||
check_modules ->
|
||||
schedulers = schedulers || max(:erlang.system_info(:schedulers_online), 2)
|
||||
|
||||
{:ok, server} =
|
||||
:gen_server.start_link(__MODULE__, [check_modules, self(), schedulers], [])
|
||||
|
||||
preload_cache(get_ets(server), check_modules)
|
||||
start(server)
|
||||
collect_results(length(check_modules), [])
|
||||
end
|
||||
end
|
||||
|
||||
defp collect_results(0, warnings) do
|
||||
warnings
|
||||
end
|
||||
|
||||
defp collect_results(count, warnings) do
|
||||
receive do
|
||||
{__MODULE__, _module, new_warnings} ->
|
||||
collect_results(count - 1, new_warnings ++ warnings)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Test cache.
|
||||
"""
|
||||
def test_cache do
|
||||
{:ok, pid} = :gen_server.start_link(__MODULE__, [[], self(), 1], [])
|
||||
{pid, get_ets(pid)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Preloads a module into the cache. Call this function before any other
|
||||
cache lookups for the module.
|
||||
"""
|
||||
@spec preload_module(cache(), module()) :: :ok
|
||||
def preload_module({server, ets}, module) do
|
||||
case :ets.lookup(ets, {:cached, module}) do
|
||||
[{_key, _}] -> :ok
|
||||
[] -> cache_module({server, ets}, module)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the export kind and deprecation reason for the given MFA from
|
||||
the cache. If the module does not exist return `{:error, :module}`,
|
||||
or if the function does not exist return `{:error, :function}`.
|
||||
"""
|
||||
@spec fetch_export(cache(), module(), atom(), arity()) ::
|
||||
{:ok, kind(), binary() | nil} | {:error, :function | :module}
|
||||
def fetch_export({_server, ets}, module, fun, arity) do
|
||||
case :ets.lookup(ets, {:cached, module}) do
|
||||
[{_key, true}] ->
|
||||
case :ets.lookup(ets, {:export, {module, fun, arity}}) do
|
||||
[{_key, kind, reason}] -> {:ok, kind, reason}
|
||||
[] -> {:error, :function}
|
||||
end
|
||||
|
||||
[{_key, false}] ->
|
||||
{:error, :module}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all exported functions and macros for the given module from
|
||||
the cache.
|
||||
"""
|
||||
@spec all_exports(cache(), module()) :: [{atom(), arity()}]
|
||||
def all_exports({_server, ets}, module) do
|
||||
# This is only called after we get a deprecation notice
|
||||
# so we can assume it's a cached module
|
||||
[{_key, exports}] = :ets.lookup(ets, {:all_exports, module})
|
||||
|
||||
exports
|
||||
|> Enum.map(fn {function, _kind} -> function end)
|
||||
|> Enum.sort()
|
||||
end
|
||||
|
||||
## Module checking
|
||||
|
||||
defp check_module(module, cache) do
|
||||
case extract_definitions(module) do
|
||||
{:ok, module, file, definitions, no_warn_undefined} ->
|
||||
Module.Types.warnings(module, file, definitions, no_warn_undefined, cache)
|
||||
|> group_warnings()
|
||||
|> emit_warnings()
|
||||
|
||||
:error ->
|
||||
[]
|
||||
end
|
||||
end
|
||||
|
||||
defp extract_definitions({module, module_map}) when is_map(module_map) do
|
||||
no_warn_undefined =
|
||||
module_map.compile_opts
|
||||
|> extract_no_warn_undefined()
|
||||
|> merge_compiler_no_warn_undefined()
|
||||
|
||||
{:ok, module, module_map.file, module_map.definitions, no_warn_undefined}
|
||||
end
|
||||
|
||||
defp extract_definitions({module, binary}) when is_binary(binary) do
|
||||
with {:ok, {_, [debug_info: chunk]}} <- :beam_lib.chunks(binary, [:debug_info]),
|
||||
{:debug_info_v1, backend, data} <- chunk,
|
||||
{:ok, module_map} <- backend.debug_info(:elixir_v1, module, data, []) do
|
||||
extract_definitions({module, module_map})
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp extract_no_warn_undefined(compile_opts) do
|
||||
for(
|
||||
{:no_warn_undefined, values} <- compile_opts,
|
||||
value <- List.wrap(values),
|
||||
do: value
|
||||
)
|
||||
end
|
||||
|
||||
defp merge_compiler_no_warn_undefined(no_warn_undefined) do
|
||||
case Code.get_compiler_option(:no_warn_undefined) do
|
||||
:all ->
|
||||
:all
|
||||
|
||||
list when is_list(list) ->
|
||||
no_warn_undefined ++ list
|
||||
end
|
||||
end
|
||||
|
||||
## Warning helpers
|
||||
|
||||
def group_warnings(warnings) do
|
||||
warnings
|
||||
|> Enum.reduce(%{}, fn {module, warning, location}, acc ->
|
||||
locations = MapSet.new([location])
|
||||
Map.update(acc, {module, warning}, locations, &MapSet.put(&1, location))
|
||||
end)
|
||||
|> Enum.map(fn {{module, warning}, locations} -> {module, warning, Enum.sort(locations)} end)
|
||||
|> Enum.sort()
|
||||
end
|
||||
|
||||
def emit_warnings(warnings) do
|
||||
Enum.flat_map(warnings, fn {module, warning, locations} ->
|
||||
message = module.format_warning(warning)
|
||||
print_warning([message, ?\n, format_locations(locations)])
|
||||
|
||||
Enum.map(locations, fn {file, line, _mfa} ->
|
||||
{file, line, message}
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
defp format_locations([location]) do
|
||||
format_location(location)
|
||||
end
|
||||
|
||||
defp format_locations(locations) do
|
||||
[
|
||||
"Found at #{length(locations)} locations:\n",
|
||||
Enum.map(locations, &format_location/1)
|
||||
]
|
||||
end
|
||||
|
||||
defp format_location({file, line, {module, fun, arity}}) do
|
||||
mfa = Exception.format_mfa(module, fun, arity)
|
||||
[format_file_line(file, line), ": ", mfa, ?\n]
|
||||
end
|
||||
|
||||
defp format_location({file, line, nil}) do
|
||||
[format_file_line(file, line), ?\n]
|
||||
end
|
||||
|
||||
defp format_location({file, line, module}) do
|
||||
[format_file_line(file, line), ": ", inspect(module), ?\n]
|
||||
end
|
||||
|
||||
defp format_file_line(file, line) do
|
||||
file = Path.relative_to_cwd(file)
|
||||
line = if line > 0, do: [?: | Integer.to_string(line)], else: []
|
||||
[" ", file, line]
|
||||
end
|
||||
|
||||
defp print_warning(message) do
|
||||
IO.puts(:stderr, [:elixir_errors.warning_prefix(), message])
|
||||
end
|
||||
|
||||
## Server callbacks
|
||||
|
||||
def init([modules, send_results, schedulers]) do
|
||||
ets = :ets.new(:checker_cache, [:set, :public, {:read_concurrency, true}])
|
||||
|
||||
state = %{
|
||||
ets: ets,
|
||||
waiting: %{},
|
||||
send_results: send_results,
|
||||
modules: modules,
|
||||
spawned: 0,
|
||||
schedulers: schedulers
|
||||
}
|
||||
|
||||
{:ok, state}
|
||||
end
|
||||
|
||||
def handle_call({:lock, module}, from, %{waiting: waiting} = state) do
|
||||
case waiting do
|
||||
%{^module => froms} ->
|
||||
waiting = Map.put(state.waiting, module, [from | froms])
|
||||
{:noreply, %{state | waiting: waiting}}
|
||||
|
||||
%{} ->
|
||||
waiting = Map.put(state.waiting, module, [])
|
||||
{:reply, true, %{state | waiting: waiting}}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call({:unlock, module}, _from, %{waiting: waiting} = state) do
|
||||
froms = Map.fetch!(waiting, module)
|
||||
Enum.each(froms, &:gen_server.reply(&1, false))
|
||||
waiting = Map.delete(waiting, module)
|
||||
{:reply, :ok, %{state | waiting: waiting}}
|
||||
end
|
||||
|
||||
def handle_call(:get_ets, _from, %{ets: ets} = state) do
|
||||
{:reply, ets, state}
|
||||
end
|
||||
|
||||
def handle_cast(:start, state) do
|
||||
{:noreply, spawn_checkers(state)}
|
||||
end
|
||||
|
||||
def handle_info({__MODULE__, :done}, state) do
|
||||
state = %{state | spawned: state.spawned - 1}
|
||||
|
||||
if state.spawned == 0 and state.modules == [] do
|
||||
{:stop, :normal, state}
|
||||
else
|
||||
state = spawn_checkers(state)
|
||||
{:noreply, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp lock(server, module) do
|
||||
:gen_server.call(server, {:lock, module}, :infinity)
|
||||
end
|
||||
|
||||
defp unlock(server, module) do
|
||||
:gen_server.call(server, {:unlock, module})
|
||||
end
|
||||
|
||||
defp get_ets(server) do
|
||||
:gen_server.call(server, :get_ets)
|
||||
end
|
||||
|
||||
defp start(server) do
|
||||
:gen_server.cast(server, :start)
|
||||
end
|
||||
|
||||
defp preload_cache(ets, modules) do
|
||||
Enum.each(modules, fn
|
||||
{_module, map} when is_map(map) -> cache_from_module_map(ets, map)
|
||||
{module, binary} when is_binary(binary) -> cache_from_chunk(ets, module, binary)
|
||||
end)
|
||||
end
|
||||
|
||||
defp spawn_checkers(%{modules: []} = state) do
|
||||
state
|
||||
end
|
||||
|
||||
defp spawn_checkers(%{spawned: spawned, schedulers: schedulers} = state)
|
||||
when spawned >= schedulers do
|
||||
state
|
||||
end
|
||||
|
||||
defp spawn_checkers(%{modules: [{module, _} = verify | modules]} = state) do
|
||||
parent = self()
|
||||
ets = state.ets
|
||||
send_results_pid = state.send_results
|
||||
|
||||
spawn_link(fn ->
|
||||
warnings = check_module(verify, {parent, ets})
|
||||
send(send_results_pid, {__MODULE__, module, warnings})
|
||||
send(parent, {__MODULE__, :done})
|
||||
end)
|
||||
|
||||
spawn_checkers(%{state | modules: modules, spawned: state.spawned + 1})
|
||||
end
|
||||
|
||||
defp cache_module({server, ets}, module) do
|
||||
if lock(server, module) do
|
||||
cache_from_chunk(ets, module) || cache_from_info(ets, module)
|
||||
unlock(server, module)
|
||||
end
|
||||
end
|
||||
|
||||
defp cache_from_chunk(ets, module) do
|
||||
case :code.get_object_code(module) do
|
||||
{^module, binary, _filename} -> cache_from_chunk(ets, module, binary)
|
||||
_other -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp cache_from_chunk(ets, module, binary) do
|
||||
with {:ok, {_, [{'ExCk', chunk}]}} <- :beam_lib.chunks(binary, ['ExCk']),
|
||||
{:elixir_checker_v1, contents} <- :erlang.binary_to_term(chunk) do
|
||||
cache_chunk(ets, module, contents.exports)
|
||||
true
|
||||
else
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp cache_from_module_map(ets, map) do
|
||||
exports =
|
||||
[{{:__info__, 1}, :def}] ++
|
||||
behaviour_exports(map) ++
|
||||
definitions_to_exports(map.definitions)
|
||||
|
||||
deprecated = Map.new(map.deprecated)
|
||||
cache_info(ets, map.module, exports, deprecated)
|
||||
end
|
||||
|
||||
defp cache_from_info(ets, module) do
|
||||
if Code.ensure_loaded?(module) do
|
||||
exports = info_exports(module)
|
||||
deprecated = info_deprecated(module)
|
||||
cache_info(ets, module, exports, deprecated)
|
||||
else
|
||||
:ets.insert(ets, {{:cached, module}, false})
|
||||
end
|
||||
end
|
||||
|
||||
defp info_exports(module) do
|
||||
Map.new(
|
||||
[{{:__info__, 1}, :def}] ++
|
||||
behaviour_exports(module) ++
|
||||
Enum.map(module.__info__(:macros), &{&1, :defmacro}) ++
|
||||
Enum.map(module.__info__(:functions), &{&1, :def})
|
||||
)
|
||||
rescue
|
||||
_ -> Map.new(Enum.map(module.module_info(:exports), &{&1, :def}))
|
||||
end
|
||||
|
||||
defp info_deprecated(module) do
|
||||
Map.new(module.__info__(:deprecated))
|
||||
rescue
|
||||
_ -> %{}
|
||||
end
|
||||
|
||||
defp cache_info(ets, module, exports, deprecated) do
|
||||
exports =
|
||||
Enum.map(exports, fn {{fun, arity}, kind} ->
|
||||
reason = Map.get(deprecated, {fun, arity})
|
||||
:ets.insert(ets, {{:export, {module, fun, arity}}, kind, reason})
|
||||
|
||||
{{fun, arity}, kind}
|
||||
end)
|
||||
|
||||
:ets.insert(ets, {{:all_exports, module}, exports})
|
||||
:ets.insert(ets, {{:cached, module}, true})
|
||||
end
|
||||
|
||||
defp cache_chunk(ets, module, exports) do
|
||||
exports =
|
||||
Enum.map(exports, fn {{fun, arity}, %{kind: kind, deprecated_reason: reason}} ->
|
||||
:ets.insert(ets, {{:export, {module, fun, arity}}, kind, reason})
|
||||
|
||||
{{fun, arity}, kind}
|
||||
end)
|
||||
|
||||
:ets.insert(ets, {{:export, {module, :__info__, 1}}, :def, nil})
|
||||
exports = [{{:__info__, 1}, :def} | exports]
|
||||
|
||||
:ets.insert(ets, {{:all_exports, module}, exports})
|
||||
:ets.insert(ets, {{:cached, module}, true})
|
||||
end
|
||||
|
||||
defp behaviour_exports(%{is_behaviour: true}), do: [{{:behaviour_info, 1}, :def}]
|
||||
defp behaviour_exports(%{is_behaviour: false}), do: []
|
||||
|
||||
defp behaviour_exports(module) when is_atom(module) do
|
||||
if {:behaviour_info, 1} in module.module_info(:functions) do
|
||||
[{{:behaviour_info, 1}, :def}]
|
||||
else
|
||||
[]
|
||||
end
|
||||
end
|
||||
|
||||
defp definitions_to_exports(definitions) do
|
||||
Enum.flat_map(definitions, fn {function, kind, _meta, _clauses} ->
|
||||
if kind in [:def, :defmacro] do
|
||||
[{function, kind}]
|
||||
else
|
||||
[]
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
@@ -1,527 +0,0 @@
|
||||
defmodule Module.Types do
|
||||
@moduledoc false
|
||||
|
||||
defmodule Error do
|
||||
defexception [:message]
|
||||
end
|
||||
|
||||
import Module.Types.Helpers
|
||||
alias Module.Types.{Expr, Pattern, Unify}
|
||||
|
||||
@doc false
|
||||
def warnings(module, file, defs, no_warn_undefined, cache) do
|
||||
stack = stack()
|
||||
|
||||
Enum.flat_map(defs, fn {{fun, arity} = function, kind, meta, clauses} ->
|
||||
context = context(with_file_meta(meta, file), module, function, no_warn_undefined, cache)
|
||||
|
||||
Enum.flat_map(clauses, fn {_meta, args, guards, body} ->
|
||||
def_expr = {kind, meta, [guards_to_expr(guards, {fun, [], args})]}
|
||||
|
||||
try do
|
||||
warnings_from_clause(args, guards, body, def_expr, stack, context)
|
||||
rescue
|
||||
e ->
|
||||
def_expr = {kind, meta, [guards_to_expr(guards, {fun, [], args}), [do: body]]}
|
||||
|
||||
error =
|
||||
Error.exception("""
|
||||
found error while checking types for #{Exception.format_mfa(module, fun, arity)}
|
||||
|
||||
#{Macro.to_string(def_expr)}
|
||||
|
||||
Please report this bug: https://github.com/elixir-lang/elixir/issues
|
||||
|
||||
#{Exception.format_banner(:error, e, __STACKTRACE__)}\
|
||||
""")
|
||||
|
||||
reraise error, __STACKTRACE__
|
||||
end
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
defp with_file_meta(meta, file) do
|
||||
case Keyword.fetch(meta, :file) do
|
||||
{:ok, {meta_file, _}} -> meta_file
|
||||
:error -> file
|
||||
end
|
||||
end
|
||||
|
||||
defp guards_to_expr([], left) do
|
||||
left
|
||||
end
|
||||
|
||||
defp guards_to_expr([guard | guards], left) do
|
||||
guards_to_expr(guards, {:when, [], [left, guard]})
|
||||
end
|
||||
|
||||
defp warnings_from_clause(args, guards, body, def_expr, stack, context) do
|
||||
head_stack = Unify.push_expr_stack(def_expr, stack)
|
||||
|
||||
with {:ok, _types, context} <- Pattern.of_head(args, guards, head_stack, context),
|
||||
{:ok, _type, context} <- Expr.of_expr(body, stack, context) do
|
||||
context.warnings
|
||||
else
|
||||
{:error, {type, error, context}} ->
|
||||
[error_to_warning(type, error, context) | context.warnings]
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def context(file, module, function, no_warn_undefined, cache) do
|
||||
%{
|
||||
# File of module
|
||||
file: file,
|
||||
# Module of definitions
|
||||
module: module,
|
||||
# Current function
|
||||
function: function,
|
||||
# List of calls to not warn on as undefined
|
||||
no_warn_undefined: no_warn_undefined,
|
||||
# A list of cached modules received from the parallel compiler
|
||||
cache: cache,
|
||||
# Expression variable to type variable
|
||||
vars: %{},
|
||||
# Type variable to expression variable
|
||||
types_to_vars: %{},
|
||||
# Type variable to type
|
||||
types: %{},
|
||||
# Trace of all variables that have been refined to a type,
|
||||
# including the type they were refined to, why, and where
|
||||
traces: %{},
|
||||
# Counter to give type variables unique names
|
||||
counter: 0,
|
||||
# Track if a variable was infered from a type guard function such is_tuple/1
|
||||
# or a guard function that fails such as elem/2, possible values are:
|
||||
# `:guarded` when `is_tuple(x)`
|
||||
# `:guarded` when `is_tuple and elem(x, 0)`
|
||||
# `:fail` when `elem(x, 0)`
|
||||
guard_sources: %{},
|
||||
# A list with all warnings from the running the code
|
||||
warnings: []
|
||||
}
|
||||
end
|
||||
|
||||
@doc false
|
||||
def stack() do
|
||||
%{
|
||||
# Stack of variables we have refined during unification,
|
||||
# used for creating relevant traces
|
||||
unify_stack: [],
|
||||
# Last expression we have recursed through during inference,
|
||||
# used for tracing
|
||||
last_expr: nil,
|
||||
# When false do not add a trace when a type variable is refined,
|
||||
# useful when merging contexts where the variables already have traces
|
||||
trace: true,
|
||||
# Track if we are in a context where type guard functions should
|
||||
# affect inference
|
||||
type_guards_enabled?: true,
|
||||
# Context used to determine if unification is bi-directional, :expr
|
||||
# is directional, :pattern is bi-directional
|
||||
context: nil
|
||||
}
|
||||
end
|
||||
|
||||
## VARIABLE LIFTING
|
||||
|
||||
@doc """
|
||||
Lifts type variables to their infered types from the context.
|
||||
"""
|
||||
def lift_types(types, context) do
|
||||
context = %{
|
||||
types: context.types,
|
||||
lifted_types: %{},
|
||||
lifted_counter: 0
|
||||
}
|
||||
|
||||
{types, _context} = Enum.map_reduce(types, context, &do_lift_type/2)
|
||||
types
|
||||
end
|
||||
|
||||
@doc """
|
||||
Lifts a single type to its infered type from the context.
|
||||
"""
|
||||
def lift_type(type, context) do
|
||||
context = %{
|
||||
types: context.types,
|
||||
lifted_types: %{},
|
||||
lifted_counter: 0
|
||||
}
|
||||
|
||||
{type, _context} = do_lift_type(type, context)
|
||||
type
|
||||
end
|
||||
|
||||
# Lift type variable to its infered (hopefully concrete) types from the context
|
||||
defp do_lift_type({:var, var}, context) do
|
||||
case Map.fetch(context.lifted_types, var) do
|
||||
{:ok, lifted_var} ->
|
||||
{{:var, lifted_var}, context}
|
||||
|
||||
:error ->
|
||||
case Map.fetch(context.types, var) do
|
||||
{:ok, :unbound} ->
|
||||
new_lifted_var(var, context)
|
||||
|
||||
{:ok, type} ->
|
||||
# Remove visited types to avoid infinite loops
|
||||
# then restore after we are done recursing on vars
|
||||
types = context.types
|
||||
context = %{context | types: Map.delete(context.types, var)}
|
||||
{type, context} = do_lift_type(type, context)
|
||||
{type, %{context | types: types}}
|
||||
|
||||
:error ->
|
||||
new_lifted_var(var, context)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp do_lift_type({:tuple, n, types}, context) do
|
||||
{types, context} = Enum.map_reduce(types, context, &do_lift_type/2)
|
||||
{{:tuple, n, types}, context}
|
||||
end
|
||||
|
||||
defp do_lift_type({:map, pairs}, context) do
|
||||
{pairs, context} =
|
||||
Enum.map_reduce(pairs, context, fn {kind, key, value}, context ->
|
||||
{key, context} = do_lift_type(key, context)
|
||||
{value, context} = do_lift_type(value, context)
|
||||
{{kind, key, value}, context}
|
||||
end)
|
||||
|
||||
{{:map, pairs}, context}
|
||||
end
|
||||
|
||||
defp do_lift_type({:list, type}, context) do
|
||||
{type, context} = do_lift_type(type, context)
|
||||
{{:list, type}, context}
|
||||
end
|
||||
|
||||
defp do_lift_type(other, context) do
|
||||
{other, context}
|
||||
end
|
||||
|
||||
defp new_lifted_var(original_var, context) do
|
||||
types = Map.put(context.lifted_types, original_var, context.lifted_counter)
|
||||
counter = context.lifted_counter + 1
|
||||
|
||||
type = {:var, context.lifted_counter}
|
||||
context = %{context | lifted_types: types, lifted_counter: counter}
|
||||
{type, context}
|
||||
end
|
||||
|
||||
## ERROR TO WARNING
|
||||
|
||||
# Collect relevant information from context and traces to report error
|
||||
def error_to_warning(:unable_unify, {left, right, stack}, context) do
|
||||
{fun, arity} = context.function
|
||||
line = get_meta(stack.last_expr)[:line]
|
||||
location = {context.file, line, {context.module, fun, arity}}
|
||||
|
||||
traces = type_traces(stack, context)
|
||||
traces = tag_traces(traces, context)
|
||||
|
||||
error = {:unable_unify, left, right, {location, stack.last_expr, traces}}
|
||||
{Module.Types, error, location}
|
||||
end
|
||||
|
||||
# Collect relevant traces from context.traces using stack.unify_stack
|
||||
defp type_traces(stack, context) do
|
||||
# TODO: Do we need the unify_stack or is enough to only get the last variable
|
||||
# in the stack since we get related variables anyway?
|
||||
stack =
|
||||
stack.unify_stack
|
||||
|> Enum.uniq()
|
||||
|> Enum.flat_map(&[&1 | related_variables(&1, context.types)])
|
||||
|> Enum.uniq()
|
||||
|
||||
Enum.flat_map(stack, fn var_index ->
|
||||
with %{^var_index => traces} <- context.traces,
|
||||
%{^var_index => expr_var} <- context.types_to_vars do
|
||||
Enum.map(traces, &{expr_var, &1})
|
||||
else
|
||||
_other -> []
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp related_variables(var, types) do
|
||||
Enum.flat_map(types, fn
|
||||
{related_var, {:var, ^var}} ->
|
||||
[related_var | related_variables(related_var, types)]
|
||||
|
||||
_ ->
|
||||
[]
|
||||
end)
|
||||
end
|
||||
|
||||
# Tag if trace is for a concrete type or type variable
|
||||
defp tag_traces(traces, context) do
|
||||
Enum.flat_map(traces, fn {var, {type, expr, location}} ->
|
||||
with {:var, var_index} <- type,
|
||||
%{^var_index => expr_var} <- context.types_to_vars do
|
||||
[{var, {:var, expr_var, expr, location}}]
|
||||
else
|
||||
_ -> [{var, {:type, type, expr, location}}]
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
## FORMAT WARNINGS
|
||||
|
||||
def format_warning({:unable_unify, left, right, {location, expr, traces}}) do
|
||||
cond do
|
||||
map_type?(left) and map_type?(right) and match?({:ok, _, _}, missing_field(left, right)) ->
|
||||
{:ok, atom, known_atoms} = missing_field(left, right)
|
||||
|
||||
# Drop the last trace which is the expression map.foo
|
||||
traces = Enum.drop(traces, 1)
|
||||
{traces, hints} = format_traces(traces, true)
|
||||
|
||||
[
|
||||
"undefined field \"#{atom}\" ",
|
||||
format_expr(expr, location),
|
||||
"expected one of the following fields: ",
|
||||
Enum.map_join(Enum.sort(known_atoms), ", ", & &1),
|
||||
"\n\n",
|
||||
traces,
|
||||
format_message_hints(hints),
|
||||
"Conflict found at"
|
||||
]
|
||||
|
||||
true ->
|
||||
simplify_left? = simplify_type?(left, right)
|
||||
simplify_right? = simplify_type?(right, left)
|
||||
|
||||
{traces, hints} = format_traces(traces, simplify_left? or simplify_right?)
|
||||
|
||||
[
|
||||
"incompatible types:\n\n ",
|
||||
Unify.format_type(left, simplify_left?),
|
||||
" !~ ",
|
||||
Unify.format_type(right, simplify_right?),
|
||||
"\n\n",
|
||||
format_expr(expr, location),
|
||||
traces,
|
||||
format_message_hints(hints),
|
||||
"Conflict found at"
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
defp missing_field(
|
||||
{:map, [{:required, {:atom, atom} = type, _}, {:optional, :dynamic, :dynamic}]},
|
||||
{:map, fields}
|
||||
) do
|
||||
matched_missing_field(fields, type, atom)
|
||||
end
|
||||
|
||||
defp missing_field(
|
||||
{:map, fields},
|
||||
{:map, [{:required, {:atom, atom} = type, _}, {:optional, :dynamic, :dynamic}]}
|
||||
) do
|
||||
matched_missing_field(fields, type, atom)
|
||||
end
|
||||
|
||||
defp missing_field(_, _), do: :error
|
||||
|
||||
defp matched_missing_field(fields, type, atom) do
|
||||
if List.keymember?(fields, type, 1) do
|
||||
:error
|
||||
else
|
||||
known_atoms = for {_, {:atom, atom}, _} <- fields, do: atom
|
||||
{:ok, atom, known_atoms}
|
||||
end
|
||||
end
|
||||
|
||||
defp format_traces([], _simplify?) do
|
||||
{[], []}
|
||||
end
|
||||
|
||||
defp format_traces(traces, simplify?) do
|
||||
traces
|
||||
|> Enum.reverse()
|
||||
|> Enum.map_reduce([], fn
|
||||
{var, {:type, type, expr, location}}, hints ->
|
||||
{hint, hints} = format_type_hint(type, expr, hints)
|
||||
|
||||
trace = [
|
||||
"where \"",
|
||||
Macro.to_string(var),
|
||||
"\" was given the type ",
|
||||
Unify.format_type(type, simplify?),
|
||||
hint,
|
||||
" in:\n\n # ",
|
||||
format_location(location),
|
||||
" ",
|
||||
indent(expr_to_string(expr)),
|
||||
"\n\n"
|
||||
]
|
||||
|
||||
{trace, hints}
|
||||
|
||||
{var1, {:var, var2, expr, location}}, hints ->
|
||||
trace = [
|
||||
"where \"",
|
||||
Macro.to_string(var1),
|
||||
"\" was given the same type as \"",
|
||||
Macro.to_string(var2),
|
||||
"\" in:\n\n # ",
|
||||
format_location(location),
|
||||
" ",
|
||||
indent(expr_to_string(expr)),
|
||||
"\n\n"
|
||||
]
|
||||
|
||||
{trace, hints}
|
||||
end)
|
||||
end
|
||||
|
||||
defp format_location({file, line, _mfa}) do
|
||||
format_location({file, line})
|
||||
end
|
||||
|
||||
defp format_location({file, line}) do
|
||||
file = Path.relative_to_cwd(file)
|
||||
line = if line, do: [Integer.to_string(line)], else: []
|
||||
[file, ?:, line, ?\n]
|
||||
end
|
||||
|
||||
defp simplify_type?(type, other) do
|
||||
map_type?(type) and not map_type?(other)
|
||||
end
|
||||
|
||||
## EXPRESSION FORMATTING
|
||||
|
||||
defp format_expr(nil, _location) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp format_expr(expr, location) do
|
||||
[
|
||||
"in expression:\n\n # ",
|
||||
format_location(location),
|
||||
" ",
|
||||
indent(expr_to_string(expr)),
|
||||
"\n\n"
|
||||
]
|
||||
end
|
||||
|
||||
@doc false
|
||||
def expr_to_string(expr) do
|
||||
expr
|
||||
|> reverse_rewrite()
|
||||
|> Macro.to_string()
|
||||
end
|
||||
|
||||
defp reverse_rewrite(guard) do
|
||||
Macro.prewalk(guard, fn
|
||||
{{:., _, [mod, fun]}, meta, args} -> erl_to_ex(mod, fun, args, meta)
|
||||
other -> other
|
||||
end)
|
||||
end
|
||||
|
||||
defp erl_to_ex(mod, fun, args, meta) do
|
||||
case :elixir_rewrite.erl_to_ex(mod, fun, args) do
|
||||
{Kernel, fun, args} -> {fun, meta, args}
|
||||
{mod, fun, args} -> {{:., [], [mod, fun]}, meta, args}
|
||||
end
|
||||
end
|
||||
|
||||
## Hints
|
||||
|
||||
defp format_message_hints(hints) do
|
||||
hints |> Enum.uniq() |> Enum.reverse() |> Enum.map(&format_message_hint/1)
|
||||
end
|
||||
|
||||
defp format_message_hint(:inferred_dot) do
|
||||
"""
|
||||
HINT: "var.field" (without parentheses) implies "var" is a map() while \
|
||||
"var.fun()" (with parentheses) implies "var" is an atom()
|
||||
|
||||
"""
|
||||
end
|
||||
|
||||
defp format_message_hint(:inferred_bitstring_spec) do
|
||||
"""
|
||||
HINT: all expressions given to binaries are assumed to be of type \
|
||||
integer() unless said otherwise. For example, <<expr>> assumes "expr" \
|
||||
is an integer. Pass a modifier, such as <<expr::float>> or <<expr::binary>>, \
|
||||
to change the default behaviour.
|
||||
|
||||
"""
|
||||
end
|
||||
|
||||
defp format_type_hint(type, expr, hints) do
|
||||
case format_type_hint(type, expr) do
|
||||
{message, hint} -> {message, [hint | hints]}
|
||||
:error -> {[], hints}
|
||||
end
|
||||
end
|
||||
|
||||
defp format_type_hint(type, expr) do
|
||||
cond do
|
||||
dynamic_map_dot?(type, expr) ->
|
||||
{" (due to calling var.field)", :inferred_dot}
|
||||
|
||||
dynamic_remote_call?(type, expr) ->
|
||||
{" (due to calling var.fun())", :inferred_dot}
|
||||
|
||||
inferred_bitstring_spec?(type, expr) ->
|
||||
{[], :inferred_bitstring_spec}
|
||||
|
||||
true ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
defp dynamic_map_dot?(type, expr) do
|
||||
with true <- map_type?(type),
|
||||
{{:., _meta1, [_map, _field]}, meta2, []} <- expr,
|
||||
true <- Keyword.get(meta2, :no_parens, false) do
|
||||
true
|
||||
else
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp dynamic_remote_call?(type, expr) do
|
||||
with true <- atom_type?(type),
|
||||
{{:., _meta1, [_module, _field]}, meta2, []} <- expr,
|
||||
false <- Keyword.get(meta2, :no_parens, false) do
|
||||
true
|
||||
else
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp inferred_bitstring_spec?(type, expr) do
|
||||
with true <- integer_type?(type),
|
||||
{:<<>>, _, args} <- expr,
|
||||
true <- Enum.any?(args, &match?({:"::", [{:inferred_bitstring_spec, true} | _], _}, &1)) do
|
||||
true
|
||||
else
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
## Formatting helpers
|
||||
|
||||
defp indent(string) do
|
||||
String.replace(string, "\n", " \n")
|
||||
end
|
||||
|
||||
defp map_type?({:map, _}), do: true
|
||||
defp map_type?(_other), do: false
|
||||
|
||||
defp atom_type?(:atom), do: true
|
||||
defp atom_type?({:atom, _}), do: false
|
||||
defp atom_type?({:union, union}), do: Enum.all?(union, &atom_type?/1)
|
||||
defp atom_type?(_other), do: false
|
||||
|
||||
defp integer_type?(:integer), do: true
|
||||
defp integer_type?(_other), do: false
|
||||
end
|
||||
@@ -1,498 +0,0 @@
|
||||
defmodule Module.Types.Expr do
|
||||
@moduledoc false
|
||||
|
||||
alias Module.Types.{Of, Pattern}
|
||||
import Module.Types.{Helpers, Unify}
|
||||
|
||||
def of_expr(expr, %{context: stack_context} = stack, context) when stack_context != :expr do
|
||||
of_expr(expr, %{stack | context: :expr}, context)
|
||||
end
|
||||
|
||||
# :atom
|
||||
def of_expr(atom, _stack, context) when is_atom(atom) do
|
||||
{:ok, {:atom, atom}, context}
|
||||
end
|
||||
|
||||
# 12
|
||||
def of_expr(literal, _stack, context) when is_integer(literal) do
|
||||
{:ok, :integer, context}
|
||||
end
|
||||
|
||||
# 1.2
|
||||
def of_expr(literal, _stack, context) when is_float(literal) do
|
||||
{:ok, :float, context}
|
||||
end
|
||||
|
||||
# "..."
|
||||
def of_expr(literal, _stack, context) when is_binary(literal) do
|
||||
{:ok, :binary, context}
|
||||
end
|
||||
|
||||
# #PID<...>
|
||||
def of_expr(literal, _stack, context) when is_pid(literal) do
|
||||
{:ok, :dynamic, context}
|
||||
end
|
||||
|
||||
# <<...>>>
|
||||
def of_expr({:<<>>, _meta, args}, stack, context) do
|
||||
result = Of.binary(args, stack, context, &of_expr/3)
|
||||
|
||||
case result do
|
||||
{:ok, context} -> {:ok, :binary, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# left | []
|
||||
def of_expr({:|, _meta, [left_expr, []]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
of_expr(left_expr, stack, context)
|
||||
end
|
||||
|
||||
# left | right
|
||||
def of_expr({:|, _meta, [left_expr, right_expr]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case of_expr(left_expr, stack, context) do
|
||||
{:ok, left, context} ->
|
||||
case of_expr(right_expr, stack, context) do
|
||||
{:ok, {:list, right}, context} ->
|
||||
{:ok, to_union([left, right], context), context}
|
||||
|
||||
{:ok, right, context} ->
|
||||
{:ok, to_union([left, right], context), context}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# []
|
||||
def of_expr([], _stack, context) do
|
||||
{:ok, {:list, :dynamic}, context}
|
||||
end
|
||||
|
||||
# [expr, ...]
|
||||
def of_expr(exprs, stack, context) when is_list(exprs) do
|
||||
stack = push_expr_stack(exprs, stack)
|
||||
|
||||
case map_reduce_ok(exprs, context, &of_expr(&1, stack, &2)) do
|
||||
{:ok, types, context} -> {:ok, {:list, to_union(types, context)}, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# __CALLER__
|
||||
def of_expr({:__CALLER__, _meta, var_context}, _stack, context) when is_atom(var_context) do
|
||||
struct_pair = {:required, {:atom, :__struct__}, {:atom, Macro.Env}}
|
||||
|
||||
pairs =
|
||||
Enum.map(Map.from_struct(Macro.Env.__struct__()), fn {key, _value} ->
|
||||
{:required, {:atom, key}, :dynamic}
|
||||
end)
|
||||
|
||||
{:ok, {:map, [struct_pair | pairs]}, context}
|
||||
end
|
||||
|
||||
# __STACKTRACE__
|
||||
def of_expr({:__STACKTRACE__, _meta, var_context}, _stack, context) when is_atom(var_context) do
|
||||
file = {:tuple, 2, [{:atom, :file}, {:list, :integer}]}
|
||||
line = {:tuple, 2, [{:atom, :line}, :integer]}
|
||||
file_line = {:list, {:union, [file, line]}}
|
||||
type = {:list, {:tuple, 4, [:atom, :atom, :integer, file_line]}}
|
||||
{:ok, type, context}
|
||||
end
|
||||
|
||||
# var
|
||||
def of_expr(var, _stack, context) when is_var(var) do
|
||||
{:ok, get_var!(var, context), context}
|
||||
end
|
||||
|
||||
# {left, right}
|
||||
def of_expr({left, right}, stack, context) do
|
||||
of_expr({:{}, [], [left, right]}, stack, context)
|
||||
end
|
||||
|
||||
# {...}
|
||||
def of_expr({:{}, _meta, exprs} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case map_reduce_ok(exprs, context, &of_expr(&1, stack, &2)) do
|
||||
{:ok, types, context} -> {:ok, {:tuple, length(types), types}, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# left = right
|
||||
def of_expr({:=, _meta, [left_expr, right_expr]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, left_type, context} <-
|
||||
Pattern.of_pattern(left_expr, stack, context),
|
||||
{:ok, right_type, context} <- of_expr(right_expr, stack, context),
|
||||
do: unify(right_type, left_type, %{stack | context: :pattern}, context)
|
||||
end
|
||||
|
||||
# %{map | ...}
|
||||
def of_expr({:%{}, _, [{:|, _, [map, args]}]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, map_type, context} <- of_expr(map, stack, context),
|
||||
{:ok, {:map, arg_pairs}, context} <- Of.closed_map(args, stack, context, &of_expr/3),
|
||||
dynamic_value_pairs =
|
||||
Enum.map(arg_pairs, fn {:required, key, _value} -> {:required, key, :dynamic} end),
|
||||
args_type = {:map, dynamic_value_pairs ++ [{:optional, :dynamic, :dynamic}]},
|
||||
{:ok, type, context} <- unify(args_type, map_type, stack, context) do
|
||||
# Retrieve map type and overwrite with the new value types from the map update
|
||||
{:map, pairs} = resolve_var(type, context)
|
||||
|
||||
updated_pairs =
|
||||
Enum.reduce(arg_pairs, pairs, fn {:required, key, value}, pairs ->
|
||||
List.keyreplace(pairs, key, 1, {:required, key, value})
|
||||
end)
|
||||
|
||||
{:ok, {:map, updated_pairs}, context}
|
||||
end
|
||||
end
|
||||
|
||||
# %Struct{map | ...}
|
||||
def of_expr({:%, meta, [module, {:%{}, _, [{:|, _, [_, _]}]} = update]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, struct, context} <- Of.struct(module, meta, context),
|
||||
{:ok, update, context} <- of_expr(update, stack, context) do
|
||||
unify(update, struct, stack, context)
|
||||
end
|
||||
end
|
||||
|
||||
# %{...}
|
||||
def of_expr({:%{}, _meta, args} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
Of.closed_map(args, stack, context, &of_expr/3)
|
||||
end
|
||||
|
||||
# %Struct{...}
|
||||
def of_expr({:%, meta1, [module, {:%{}, _meta2, args}]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, struct, context} <- Of.struct(module, meta1, context),
|
||||
{:ok, map, context} <- Of.open_map(args, stack, context, &of_expr/3) do
|
||||
unify(map, struct, stack, context)
|
||||
end
|
||||
end
|
||||
|
||||
# ()
|
||||
def of_expr({:__block__, _meta, []}, _stack, context) do
|
||||
{:ok, {:atom, nil}, context}
|
||||
end
|
||||
|
||||
# (expr; expr)
|
||||
def of_expr({:__block__, _meta, exprs}, stack, context) do
|
||||
case map_reduce_ok(exprs, context, &of_expr(&1, stack, &2)) do
|
||||
{:ok, expr_types, context} -> {:ok, Enum.at(expr_types, -1), context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# case expr do pat -> expr end
|
||||
def of_expr({:case, _meta, [case_expr, [{:do, clauses}]]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, _expr_type, context} <- of_expr(case_expr, stack, context),
|
||||
{:ok, context} <- of_clauses(clauses, stack, context),
|
||||
do: {:ok, :dynamic, context}
|
||||
end
|
||||
|
||||
# fn pat -> expr end
|
||||
def of_expr({:fn, _meta, clauses} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case of_clauses(clauses, stack, context) do
|
||||
{:ok, context} -> {:ok, :dynamic, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
@try_blocks [:do, :after]
|
||||
@try_clause_blocks [:catch, :else, :after]
|
||||
|
||||
# try do expr end
|
||||
def of_expr({:try, _meta, [blocks]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
{result, context} =
|
||||
reduce_ok(blocks, context, fn
|
||||
{:rescue, clauses}, context ->
|
||||
reduce_ok(clauses, context, fn
|
||||
{:->, _, [[{:in, _, [var, _exceptions]}], body]}, context = acc ->
|
||||
{_type, context} = new_pattern_var(var, context)
|
||||
|
||||
with {:ok, context} <- of_expr_context(body, stack, context) do
|
||||
{:ok, keep_warnings(acc, context)}
|
||||
end
|
||||
|
||||
{:->, _, [[var], body]}, context = acc ->
|
||||
{_type, context} = new_pattern_var(var, context)
|
||||
|
||||
with {:ok, context} <- of_expr_context(body, stack, context) do
|
||||
{:ok, keep_warnings(acc, context)}
|
||||
end
|
||||
end)
|
||||
|
||||
{block, body}, context = acc when block in @try_blocks ->
|
||||
with {:ok, context} <- of_expr_context(body, stack, context) do
|
||||
{:ok, keep_warnings(acc, context)}
|
||||
end
|
||||
|
||||
{block, clauses}, context when block in @try_clause_blocks ->
|
||||
of_clauses(clauses, stack, context)
|
||||
end)
|
||||
|
||||
case result do
|
||||
:ok -> {:ok, :dynamic, context}
|
||||
:error -> {:error, context}
|
||||
end
|
||||
end
|
||||
|
||||
# receive do pat -> expr end
|
||||
def of_expr({:receive, _meta, [blocks]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
{result, context} =
|
||||
reduce_ok(blocks, context, fn
|
||||
{:do, {:__block__, _, []}}, context ->
|
||||
{:ok, context}
|
||||
|
||||
{:do, clauses}, context ->
|
||||
of_clauses(clauses, stack, context)
|
||||
|
||||
{:after, [{:->, _meta, [head, body]}]}, context = acc ->
|
||||
with {:ok, _type, context} <- of_expr(head, stack, context),
|
||||
{:ok, _type, context} <- of_expr(body, stack, context),
|
||||
do: {:ok, keep_warnings(acc, context)}
|
||||
end)
|
||||
|
||||
case result do
|
||||
:ok -> {:ok, :dynamic, context}
|
||||
:error -> {:error, context}
|
||||
end
|
||||
end
|
||||
|
||||
# for pat <- expr do expr end
|
||||
def of_expr({:for, _meta, args} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
{clauses, [[{:do, block} | opts]]} = Enum.split(args, -1)
|
||||
|
||||
with {:ok, context} <- reduce_ok(clauses, context, &for_clause(&1, stack, &2)),
|
||||
{:ok, context} <- reduce_ok(opts, context, &for_option(&1, stack, &2)) do
|
||||
if Keyword.has_key?(opts, :reduce) do
|
||||
with {:ok, context} <- of_clauses(block, stack, context) do
|
||||
{:ok, :dynamic, context}
|
||||
end
|
||||
else
|
||||
with {:ok, _type, context} <- of_expr(block, stack, context) do
|
||||
{:ok, :dynamic, context}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# with pat <- expr do expr end
|
||||
def of_expr({:with, _meta, clauses} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case reduce_ok(clauses, context, &with_clause(&1, stack, &2)) do
|
||||
{:ok, _context} -> {:ok, :dynamic, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# fun.(arg)
|
||||
def of_expr({{:., _meta1, [fun]}, _meta2, args} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case of_expr(fun, stack, context) do
|
||||
{:ok, _fun_type, context} ->
|
||||
case map_reduce_ok(args, context, &of_expr(&1, stack, &2)) do
|
||||
{:ok, _arg_types, context} -> {:ok, :dynamic, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# expr.key_or_fun
|
||||
def of_expr({{:., _meta1, [expr1, key_or_fun]}, meta2, []} = expr2, stack, context)
|
||||
when not is_atom(expr1) do
|
||||
stack = push_expr_stack(expr2, stack)
|
||||
|
||||
if Keyword.get(meta2, :no_parens, false) do
|
||||
with {:ok, expr_type, context} <- of_expr(expr1, stack, context),
|
||||
{value_var, context} = add_var(context),
|
||||
pair_type = {:required, {:atom, key_or_fun}, value_var},
|
||||
optional_type = {:optional, :dynamic, :dynamic},
|
||||
map_field_type = {:map, [pair_type, optional_type]},
|
||||
{:ok, _map_type, context} <- unify(map_field_type, expr_type, stack, context),
|
||||
do: {:ok, value_var, context}
|
||||
else
|
||||
with {:ok, expr_type, context} <- of_expr(expr1, stack, context),
|
||||
{:ok, _map_type, context} <- unify(expr_type, :atom, stack, context),
|
||||
do: {:ok, :dynamic, context}
|
||||
end
|
||||
end
|
||||
|
||||
# expr.fun(arg)
|
||||
def of_expr({{:., meta1, [expr1, fun]}, _meta2, args} = expr2, stack, context) do
|
||||
context = Of.remote(expr1, fun, length(args), meta1, context)
|
||||
stack = push_expr_stack(expr2, stack)
|
||||
|
||||
with {:ok, _expr_type, context} <- of_expr(expr1, stack, context),
|
||||
{:ok, _fun_type, context} <- of_expr(fun, stack, context) do
|
||||
case map_reduce_ok(args, context, &of_expr(&1, stack, &2)) do
|
||||
{:ok, _arg_types, context} -> {:ok, :dynamic, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# &Foo.bar/1
|
||||
def of_expr({:&, meta, [{:/, _, [{{:., _, [module, fun]}, _, []}, arity]}]}, _stack, context)
|
||||
when is_atom(module) and is_atom(fun) do
|
||||
context = Of.remote(module, fun, arity, meta, context)
|
||||
{:ok, :dynamic, context}
|
||||
end
|
||||
|
||||
# &foo/1
|
||||
# & &1
|
||||
def of_expr({:&, _meta, _arg}, _stack, context) do
|
||||
# TODO: Function type
|
||||
{:ok, :dynamic, context}
|
||||
end
|
||||
|
||||
# fun(arg)
|
||||
def of_expr({fun, _meta, args} = expr, stack, context) when is_atom(fun) and is_list(args) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case map_reduce_ok(args, context, &of_expr(&1, stack, &2)) do
|
||||
{:ok, _arg_types, context} -> {:ok, :dynamic, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp for_clause({:<-, _, [left, expr]}, stack, context) do
|
||||
{pattern, guards} = extract_head([left])
|
||||
|
||||
with {:ok, _pattern_type, context} <- Pattern.of_pattern(pattern, stack, context),
|
||||
# TODO: Check that of_guard/3 returns a boolean
|
||||
{:ok, _guard_type, context} <- Pattern.of_guard(guards_to_or(guards), stack, context),
|
||||
{:ok, _expr_type, context} <- of_expr(expr, stack, context),
|
||||
do: {:ok, context}
|
||||
end
|
||||
|
||||
defp for_clause({:<<>>, _, [{:<-, _, [pattern, expr]}]}, stack, context) do
|
||||
# TODO: the compiler guarantees pattern is a binary but we need to check expr is a binary
|
||||
with {:ok, _pattern_type, context} <- Pattern.of_pattern(pattern, stack, context),
|
||||
{:ok, _expr_type, context} <- of_expr(expr, stack, context),
|
||||
do: {:ok, context}
|
||||
end
|
||||
|
||||
defp for_clause(list, stack, context) when is_list(list) do
|
||||
reduce_ok(list, context, &for_option(&1, stack, &2))
|
||||
end
|
||||
|
||||
defp for_clause(expr, stack, context) do
|
||||
of_expr_context(expr, stack, context)
|
||||
end
|
||||
|
||||
defp for_option({:into, expr}, stack, context) do
|
||||
of_expr_context(expr, stack, context)
|
||||
end
|
||||
|
||||
defp for_option({:reduce, expr}, stack, context) do
|
||||
of_expr_context(expr, stack, context)
|
||||
end
|
||||
|
||||
defp for_option({:uniq, _}, _stack, context) do
|
||||
{:ok, context}
|
||||
end
|
||||
|
||||
defp with_clause({:<-, _, [left, expr]}, stack, context) do
|
||||
{pattern, guards} = extract_head([left])
|
||||
|
||||
with {:ok, _pattern_type, context} <- Pattern.of_pattern(pattern, stack, context),
|
||||
# TODO: Check that of_guard/3 returns a boolean
|
||||
{:ok, _guard_type, context} <- Pattern.of_guard(guards_to_or(guards), stack, context),
|
||||
{:ok, _expr_type, context} <- of_expr(expr, stack, context),
|
||||
do: {:ok, context}
|
||||
end
|
||||
|
||||
defp with_clause(list, stack, context) when is_list(list) do
|
||||
reduce_ok(list, context, &with_option(&1, stack, &2))
|
||||
end
|
||||
|
||||
defp with_clause(expr, stack, context) do
|
||||
of_expr_context(expr, stack, context)
|
||||
end
|
||||
|
||||
defp with_option({:do, body}, stack, context) do
|
||||
of_expr_context(body, stack, context)
|
||||
end
|
||||
|
||||
defp with_option({:else, clauses}, stack, context) do
|
||||
of_clauses(clauses, stack, context)
|
||||
end
|
||||
|
||||
defp of_clauses(clauses, stack, context) do
|
||||
reduce_ok(clauses, context, fn {:->, _meta, [head, body]}, context = acc ->
|
||||
{patterns, guards} = extract_head(head)
|
||||
|
||||
with {:ok, _, context} <- Pattern.of_head(patterns, guards, stack, context),
|
||||
{:ok, _expr_type, context} <- of_expr(body, stack, context),
|
||||
do: {:ok, keep_warnings(acc, context)}
|
||||
end)
|
||||
end
|
||||
|
||||
defp keep_warnings(context, %{warnings: warnings}) do
|
||||
%{context | warnings: warnings}
|
||||
end
|
||||
|
||||
defp extract_head([{:when, _meta, args}]) do
|
||||
case Enum.split(args, -1) do
|
||||
{patterns, [guards]} -> {patterns, flatten_when(guards)}
|
||||
{patterns, []} -> {patterns, []}
|
||||
end
|
||||
end
|
||||
|
||||
defp extract_head(other) do
|
||||
{other, []}
|
||||
end
|
||||
|
||||
defp flatten_when({:when, _meta, [left, right]}) do
|
||||
[left | flatten_when(right)]
|
||||
end
|
||||
|
||||
defp flatten_when(other) do
|
||||
[other]
|
||||
end
|
||||
|
||||
defp of_expr_context(expr, stack, context) do
|
||||
case of_expr(expr, stack, context) do
|
||||
{:ok, _type, context} -> {:ok, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp new_pattern_var({:_, _meta, var_context}, context) when is_atom(var_context) do
|
||||
{:dynamic, context}
|
||||
end
|
||||
|
||||
defp new_pattern_var(var, context) do
|
||||
new_var(var, context)
|
||||
end
|
||||
end
|
||||
@@ -1,142 +0,0 @@
|
||||
defmodule Module.Types.Helpers do
|
||||
# AST and enumeration helpers.
|
||||
@moduledoc false
|
||||
|
||||
@doc """
|
||||
Guard function to check if an AST node is a variable.
|
||||
"""
|
||||
defmacro is_var(expr) do
|
||||
quote do
|
||||
is_tuple(unquote(expr)) and
|
||||
tuple_size(unquote(expr)) == 3 and
|
||||
is_atom(elem(unquote(expr), 0)) and
|
||||
is_atom(elem(unquote(expr), 2))
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns unique identifier for the current assignment of the variable.
|
||||
"""
|
||||
def var_name({_name, meta, _context}), do: Keyword.fetch!(meta, :version)
|
||||
|
||||
@doc """
|
||||
Returns the AST metadata.
|
||||
"""
|
||||
def get_meta({_, meta, _}), do: meta
|
||||
def get_meta(_other), do: []
|
||||
|
||||
@doc """
|
||||
Like `Enum.reduce/3` but only continues while `fun` returns `{:ok, acc}`
|
||||
and stops on `{:error, reason}`.
|
||||
"""
|
||||
def reduce_ok(list, acc, fun) do
|
||||
do_reduce_ok(list, acc, fun)
|
||||
end
|
||||
|
||||
defp do_reduce_ok([head | tail], acc, fun) do
|
||||
case fun.(head, acc) do
|
||||
{:ok, acc} ->
|
||||
do_reduce_ok(tail, acc, fun)
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_reduce_ok([], acc, _fun), do: {:ok, acc}
|
||||
|
||||
@doc """
|
||||
Like `Enum.unzip/1` but only continues while `fun` returns `{:ok, elem1, elem2}`
|
||||
and stops on `{:error, reason}`.
|
||||
"""
|
||||
def unzip_ok(list) do
|
||||
do_unzip_ok(list, [], [])
|
||||
end
|
||||
|
||||
defp do_unzip_ok([{:ok, head1, head2} | tail], acc1, acc2) do
|
||||
do_unzip_ok(tail, [head1 | acc1], [head2 | acc2])
|
||||
end
|
||||
|
||||
defp do_unzip_ok([{:error, reason} | _tail], _acc1, _acc2), do: {:error, reason}
|
||||
|
||||
defp do_unzip_ok([], acc1, acc2), do: {:ok, Enum.reverse(acc1), Enum.reverse(acc2)}
|
||||
|
||||
@doc """
|
||||
Like `Enum.map/2` but only continues while `fun` returns `{:ok, elem}`
|
||||
and stops on `{:error, reason}`.
|
||||
"""
|
||||
def map_ok(list, fun) do
|
||||
do_map_ok(list, [], fun)
|
||||
end
|
||||
|
||||
defp do_map_ok([head | tail], acc, fun) do
|
||||
case fun.(head) do
|
||||
{:ok, elem} ->
|
||||
do_map_ok(tail, [elem | acc], fun)
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_map_ok([], acc, _fun), do: {:ok, Enum.reverse(acc)}
|
||||
|
||||
@doc """
|
||||
Like `Enum.map_reduce/3` but only continues while `fun` returns `{:ok, elem, acc}`
|
||||
and stops on `{:error, reason}`.
|
||||
"""
|
||||
def map_reduce_ok(list, acc, fun) do
|
||||
do_map_reduce_ok(list, {[], acc}, fun)
|
||||
end
|
||||
|
||||
defp do_map_reduce_ok([head | tail], {list, acc}, fun) do
|
||||
case fun.(head, acc) do
|
||||
{:ok, elem, acc} ->
|
||||
do_map_reduce_ok(tail, {[elem | list], acc}, fun)
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_map_reduce_ok([], {list, acc}, _fun), do: {:ok, Enum.reverse(list), acc}
|
||||
|
||||
def flat_map_reduce_ok(list, acc, fun) do
|
||||
do_flat_map_reduce_ok(list, {[], acc}, fun)
|
||||
end
|
||||
|
||||
defp do_flat_map_reduce_ok([head | tail], {list, acc}, fun) do
|
||||
case fun.(head, acc) do
|
||||
{:ok, elems, acc} ->
|
||||
do_flat_map_reduce_ok(tail, {[elems | list], acc}, fun)
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_flat_map_reduce_ok([], {list, acc}, _fun),
|
||||
do: {:ok, Enum.reverse(Enum.concat(list)), acc}
|
||||
|
||||
@doc """
|
||||
Given a list of `[{:ok, term()} | {:error, term()}]` it returns a list of
|
||||
errors `{:error, [term()]}` in case of at least one error or `{:ok, [term()]}`
|
||||
if there are no errors.
|
||||
"""
|
||||
def oks_or_errors(list) do
|
||||
case Enum.split_with(list, &match?({:ok, _}, &1)) do
|
||||
{oks, []} -> {:ok, Enum.map(oks, fn {:ok, ok} -> ok end)}
|
||||
{_oks, errors} -> {:error, Enum.map(errors, fn {:error, error} -> error end)}
|
||||
end
|
||||
end
|
||||
|
||||
# TODO: Remove this and let multiple when be treated as multiple clauses,
|
||||
# meaning they will be intersection types
|
||||
def guards_to_or([]) do
|
||||
[]
|
||||
end
|
||||
|
||||
def guards_to_or(guards) do
|
||||
Enum.reduce(guards, fn guard, acc -> {{:., [], [:erlang, :orelse]}, [], [guard, acc]} end)
|
||||
end
|
||||
end
|
||||
@@ -1,319 +0,0 @@
|
||||
defmodule Module.Types.Of do
|
||||
# Typing functionality shared between Expr and Pattern.
|
||||
# Generic AST and Enum helpers go to Module.Types.Helpers.
|
||||
@moduledoc false
|
||||
|
||||
@prefix quote(do: ...)
|
||||
@suffix quote(do: ...)
|
||||
|
||||
alias Module.ParallelChecker
|
||||
|
||||
import Module.Types.Helpers
|
||||
import Module.Types.Unify
|
||||
|
||||
@doc """
|
||||
Handles open maps (with dynamic => dynamic).
|
||||
"""
|
||||
def open_map(args, stack, context, fun) do
|
||||
with {:ok, pairs, context} <- map_pairs(args, stack, context, fun) do
|
||||
pairs =
|
||||
for {key, value} <- pairs, not has_unbound_var?(key, context) do
|
||||
if singleton?(key, context) do
|
||||
{key, value}
|
||||
else
|
||||
{key, to_union([value, :dynamic], context)}
|
||||
end
|
||||
end
|
||||
|
||||
triplets = pairs_to_unions(pairs, [], context) ++ [{:optional, :dynamic, :dynamic}]
|
||||
{:ok, {:map, triplets}, context}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Handles closed maps (without dynamic => dynamic).
|
||||
"""
|
||||
def closed_map(args, stack, context, fun) do
|
||||
with {:ok, pairs, context} <- map_pairs(args, stack, context, fun) do
|
||||
{:ok, {:map, closed_to_unions(pairs, context)}, context}
|
||||
end
|
||||
end
|
||||
|
||||
defp map_pairs(pairs, stack, context, fun) do
|
||||
map_reduce_ok(pairs, context, fn {key, value}, context ->
|
||||
with {:ok, key_type, context} <- fun.(key, stack, context),
|
||||
{:ok, value_type, context} <- fun.(value, stack, context),
|
||||
do: {:ok, {key_type, value_type}, context}
|
||||
end)
|
||||
end
|
||||
|
||||
defp closed_to_unions([{key, value}], _context), do: [{:required, key, value}]
|
||||
|
||||
defp closed_to_unions(pairs, context) do
|
||||
case Enum.split_with(pairs, fn {key, _value} -> has_unbound_var?(key, context) end) do
|
||||
{[], pairs} -> pairs_to_unions(pairs, [], context)
|
||||
{[_ | _], pairs} -> pairs_to_unions([{:dynamic, :dynamic} | pairs], [], context)
|
||||
end
|
||||
end
|
||||
|
||||
defp pairs_to_unions([{key, value} | ahead], behind, context) do
|
||||
{matched_ahead, values} = find_matching_values(ahead, key, [], [])
|
||||
|
||||
# In case nothing matches, use the original ahead
|
||||
ahead = matched_ahead || ahead
|
||||
|
||||
all_values =
|
||||
[value | values] ++
|
||||
find_subtype_values(ahead, key, context) ++
|
||||
find_subtype_values(behind, key, context)
|
||||
|
||||
pairs_to_unions(ahead, [{key, to_union(all_values, context)} | behind], context)
|
||||
end
|
||||
|
||||
defp pairs_to_unions([], acc, context) do
|
||||
acc
|
||||
|> Enum.sort(&subtype?(elem(&1, 0), elem(&2, 0), context))
|
||||
|> Enum.map(fn {key, value} -> {:required, key, value} end)
|
||||
end
|
||||
|
||||
defp find_subtype_values(pairs, key, context) do
|
||||
for {pair_key, pair_value} <- pairs, subtype?(pair_key, key, context), do: pair_value
|
||||
end
|
||||
|
||||
defp find_matching_values([{key, value} | ahead], key, acc, values) do
|
||||
find_matching_values(ahead, key, acc, [value | values])
|
||||
end
|
||||
|
||||
defp find_matching_values([{_, _} = pair | ahead], key, acc, values) do
|
||||
find_matching_values(ahead, key, [pair | acc], values)
|
||||
end
|
||||
|
||||
defp find_matching_values([], _key, acc, [_ | _] = values), do: {Enum.reverse(acc), values}
|
||||
defp find_matching_values([], _key, _acc, []), do: {nil, []}
|
||||
|
||||
@doc """
|
||||
Handles structs.
|
||||
"""
|
||||
def struct(struct, meta, context) do
|
||||
context = remote(struct, :__struct__, 0, meta, context)
|
||||
|
||||
entries =
|
||||
for key <- Map.keys(struct.__struct__()), key != :__struct__ do
|
||||
{:required, {:atom, key}, :dynamic}
|
||||
end
|
||||
|
||||
{:ok, {:map, [{:required, {:atom, :__struct__}, {:atom, struct}} | entries]}, context}
|
||||
end
|
||||
|
||||
## Binary
|
||||
|
||||
@doc """
|
||||
Handles binaries.
|
||||
|
||||
In the stack, we add nodes such as <<expr>>, <<..., expr>>, etc,
|
||||
based on the position of the expression within the binary.
|
||||
"""
|
||||
def binary([], _stack, context, _fun) do
|
||||
{:ok, context}
|
||||
end
|
||||
|
||||
def binary([head], stack, context, fun) do
|
||||
head_stack = push_expr_stack({:<<>>, get_meta(head), [head]}, stack)
|
||||
binary_segment(head, head_stack, context, fun)
|
||||
end
|
||||
|
||||
def binary([head | tail], stack, context, fun) do
|
||||
head_stack = push_expr_stack({:<<>>, get_meta(head), [head, @suffix]}, stack)
|
||||
|
||||
case binary_segment(head, head_stack, context, fun) do
|
||||
{:ok, context} -> binary_many(tail, stack, context, fun)
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp binary_many([last], stack, context, fun) do
|
||||
last_stack = push_expr_stack({:<<>>, get_meta(last), [@prefix, last]}, stack)
|
||||
binary_segment(last, last_stack, context, fun)
|
||||
end
|
||||
|
||||
defp binary_many([head | tail], stack, context, fun) do
|
||||
head_stack = push_expr_stack({:<<>>, get_meta(head), [@prefix, head, @suffix]}, stack)
|
||||
|
||||
case binary_segment(head, head_stack, context, fun) do
|
||||
{:ok, context} -> binary_many(tail, stack, context, fun)
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp binary_segment({:"::", _meta, [expr, specifiers]}, stack, context, fun) do
|
||||
expected_type =
|
||||
collect_binary_specifier(specifiers, &binary_type(stack.context, &1)) || :integer
|
||||
|
||||
utf? = collect_binary_specifier(specifiers, &utf_type?/1)
|
||||
float? = collect_binary_specifier(specifiers, &float_type?/1)
|
||||
|
||||
# Special case utf and float specifiers because they can be two types as literals
|
||||
# but only a specific type as a variable in a pattern
|
||||
cond do
|
||||
stack.context == :pattern and utf? and is_binary(expr) ->
|
||||
{:ok, context}
|
||||
|
||||
stack.context == :pattern and float? and is_integer(expr) ->
|
||||
{:ok, context}
|
||||
|
||||
true ->
|
||||
with {:ok, type, context} <- fun.(expr, stack, context),
|
||||
{:ok, _type, context} <- unify(type, expected_type, stack, context),
|
||||
do: {:ok, context}
|
||||
end
|
||||
end
|
||||
|
||||
# Collect binary type specifiers,
|
||||
# from `<<pattern::integer-size(10)>>` collect `integer`
|
||||
defp collect_binary_specifier({:-, _meta, [left, right]}, fun) do
|
||||
collect_binary_specifier(left, fun) || collect_binary_specifier(right, fun)
|
||||
end
|
||||
|
||||
defp collect_binary_specifier(other, fun) do
|
||||
fun.(other)
|
||||
end
|
||||
|
||||
defp binary_type(:expr, {:float, _, _}), do: {:union, [:integer, :float]}
|
||||
defp binary_type(:expr, {:utf8, _, _}), do: {:union, [:integer, :binary]}
|
||||
defp binary_type(:expr, {:utf16, _, _}), do: {:union, [:integer, :binary]}
|
||||
defp binary_type(:expr, {:utf32, _, _}), do: {:union, [:integer, :binary]}
|
||||
defp binary_type(:pattern, {:utf8, _, _}), do: :integer
|
||||
defp binary_type(:pattern, {:utf16, _, _}), do: :integer
|
||||
defp binary_type(:pattern, {:utf32, _, _}), do: :integer
|
||||
defp binary_type(:pattern, {:float, _, _}), do: :float
|
||||
defp binary_type(_context, {:integer, _, _}), do: :integer
|
||||
defp binary_type(_context, {:bits, _, _}), do: :binary
|
||||
defp binary_type(_context, {:bitstring, _, _}), do: :binary
|
||||
defp binary_type(_context, {:bytes, _, _}), do: :binary
|
||||
defp binary_type(_context, {:binary, _, _}), do: :binary
|
||||
defp binary_type(_context, _specifier), do: nil
|
||||
|
||||
defp utf_type?({specifier, _, _}), do: specifier in [:utf8, :utf16, :utf32]
|
||||
defp utf_type?(_), do: false
|
||||
|
||||
defp float_type?({:float, _, _}), do: true
|
||||
defp float_type?(_), do: false
|
||||
|
||||
## Remote
|
||||
|
||||
@doc """
|
||||
Handles remote calls.
|
||||
"""
|
||||
def remote(module, fun, arity, meta, context) when is_atom(module) do
|
||||
# TODO: In the future we may want to warn for modules defined
|
||||
# in the local context
|
||||
if Keyword.get(meta, :context_module, false) and context.module != module do
|
||||
context
|
||||
else
|
||||
ParallelChecker.preload_module(context.cache, module)
|
||||
check_export(module, fun, arity, meta, context)
|
||||
end
|
||||
end
|
||||
|
||||
def remote(_module, _fun, _arity, _meta, context), do: context
|
||||
|
||||
defp check_export(module, fun, arity, meta, context) do
|
||||
case ParallelChecker.fetch_export(context.cache, module, fun, arity) do
|
||||
{:ok, :def, reason} ->
|
||||
check_deprecated(module, fun, arity, reason, meta, context)
|
||||
|
||||
{:ok, :defmacro, reason} ->
|
||||
context = warn(meta, context, {:unrequired_module, module, fun, arity})
|
||||
check_deprecated(module, fun, arity, reason, meta, context)
|
||||
|
||||
{:error, :module} ->
|
||||
if warn_undefined?(module, fun, arity, context) do
|
||||
warn(meta, context, {:undefined_module, module, fun, arity})
|
||||
else
|
||||
context
|
||||
end
|
||||
|
||||
{:error, :function} ->
|
||||
if warn_undefined?(module, fun, arity, context) do
|
||||
exports = ParallelChecker.all_exports(context.cache, module)
|
||||
warn(meta, context, {:undefined_function, module, fun, arity, exports})
|
||||
else
|
||||
context
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp check_deprecated(module, fun, arity, reason, meta, context) do
|
||||
if reason do
|
||||
warn(meta, context, {:deprecated, module, fun, arity, reason})
|
||||
else
|
||||
context
|
||||
end
|
||||
end
|
||||
|
||||
# The protocol code dispatches to unknown modules, so we ignore them here.
|
||||
#
|
||||
# try do
|
||||
# SomeProtocol.Atom.__impl__
|
||||
# rescue
|
||||
# ...
|
||||
# end
|
||||
#
|
||||
# But for protocols we don't want to traverse the protocol code anyway.
|
||||
# TODO: remove this clause once we no longer traverse the protocol code.
|
||||
defp warn_undefined?(_module, :__impl__, 1, _context), do: false
|
||||
defp warn_undefined?(_module, :module_info, 0, _context), do: false
|
||||
defp warn_undefined?(_module, :module_info, 1, _context), do: false
|
||||
defp warn_undefined?(:erlang, :orelse, 2, _context), do: false
|
||||
defp warn_undefined?(:erlang, :andalso, 2, _context), do: false
|
||||
|
||||
defp warn_undefined?(_, _, _, %{no_warn_undefined: :all}) do
|
||||
false
|
||||
end
|
||||
|
||||
defp warn_undefined?(module, fun, arity, context) do
|
||||
not Enum.any?(context.no_warn_undefined, &(&1 == module or &1 == {module, fun, arity}))
|
||||
end
|
||||
|
||||
defp warn(meta, context, warning) do
|
||||
{fun, arity} = context.function
|
||||
location = {context.file, meta[:line] || 0, {context.module, fun, arity}}
|
||||
%{context | warnings: [{__MODULE__, warning, location} | context.warnings]}
|
||||
end
|
||||
|
||||
## Warning formating
|
||||
|
||||
def format_warning({:undefined_module, module, fun, arity}) do
|
||||
[
|
||||
Exception.format_mfa(module, fun, arity),
|
||||
" is undefined (module ",
|
||||
inspect(module),
|
||||
" is not available or is yet to be defined)"
|
||||
]
|
||||
end
|
||||
|
||||
def format_warning({:undefined_function, module, fun, arity, exports}) do
|
||||
[
|
||||
Exception.format_mfa(module, fun, arity),
|
||||
" is undefined or private",
|
||||
UndefinedFunctionError.hint_for_loaded_module(module, fun, arity, exports)
|
||||
]
|
||||
end
|
||||
|
||||
def format_warning({:deprecated, module, fun, arity, reason}) do
|
||||
[
|
||||
Exception.format_mfa(module, fun, arity),
|
||||
" is deprecated. ",
|
||||
reason
|
||||
]
|
||||
end
|
||||
|
||||
def format_warning({:unrequired_module, module, fun, arity}) do
|
||||
[
|
||||
"you must require ",
|
||||
inspect(module),
|
||||
" before invoking the macro ",
|
||||
Exception.format_mfa(module, fun, arity)
|
||||
]
|
||||
end
|
||||
end
|
||||
@@ -1,553 +0,0 @@
|
||||
defmodule Module.Types.Pattern do
|
||||
@moduledoc false
|
||||
|
||||
alias Module.Types.Of
|
||||
import Module.Types.{Helpers, Unify}
|
||||
|
||||
@doc """
|
||||
Handles patterns and guards at once.
|
||||
"""
|
||||
def of_head(patterns, guards, stack, context) do
|
||||
with {:ok, types, context} <-
|
||||
map_reduce_ok(patterns, context, &of_pattern(&1, stack, &2)),
|
||||
# TODO: Check that of_guard/3 returns boolean() | :fail
|
||||
{:ok, _, context} <- of_guard(guards_to_or(guards), stack, context),
|
||||
do: {:ok, types, context}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Return the type and typing context of a pattern expression or an error
|
||||
in case of a typing conflict.
|
||||
"""
|
||||
def of_pattern(pattern, %{context: stack_context} = stack, context)
|
||||
when stack_context != :pattern do
|
||||
of_pattern(pattern, %{stack | context: :pattern}, context)
|
||||
end
|
||||
|
||||
# :atom
|
||||
def of_pattern(atom, _stack, context) when is_atom(atom) do
|
||||
{:ok, {:atom, atom}, context}
|
||||
end
|
||||
|
||||
# 12
|
||||
def of_pattern(literal, _stack, context) when is_integer(literal) do
|
||||
{:ok, :integer, context}
|
||||
end
|
||||
|
||||
# 1.2
|
||||
def of_pattern(literal, _stack, context) when is_float(literal) do
|
||||
{:ok, :float, context}
|
||||
end
|
||||
|
||||
# "..."
|
||||
def of_pattern(literal, _stack, context) when is_binary(literal) do
|
||||
{:ok, :binary, context}
|
||||
end
|
||||
|
||||
# <<...>>>
|
||||
def of_pattern({:<<>>, _meta, args}, stack, context) do
|
||||
result = Of.binary(args, stack, context, &of_pattern/3)
|
||||
|
||||
case result do
|
||||
{:ok, context} -> {:ok, :binary, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# left | []
|
||||
def of_pattern({:|, _meta, [left_expr, []]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
of_pattern(left_expr, stack, context)
|
||||
end
|
||||
|
||||
# left | right
|
||||
def of_pattern({:|, _meta, [left_expr, right_expr]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case of_pattern(left_expr, stack, context) do
|
||||
{:ok, left, context} ->
|
||||
case of_pattern(right_expr, stack, context) do
|
||||
{:ok, {:list, right}, context} ->
|
||||
{:ok, to_union([left, right], context), context}
|
||||
|
||||
{:ok, right, context} ->
|
||||
{:ok, to_union([left, right], context), context}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# []
|
||||
def of_pattern([], _stack, context) do
|
||||
{:ok, {:list, :dynamic}, context}
|
||||
end
|
||||
|
||||
# [expr, ...]
|
||||
def of_pattern(exprs, stack, context) when is_list(exprs) do
|
||||
stack = push_expr_stack(exprs, stack)
|
||||
|
||||
case map_reduce_ok(exprs, context, &of_pattern(&1, stack, &2)) do
|
||||
{:ok, types, context} -> {:ok, {:list, to_union(types, context)}, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# left ++ right
|
||||
def of_pattern(
|
||||
{{:., _meta1, [:erlang, :++]}, _meta2, [left_expr, right_expr]} = expr,
|
||||
stack,
|
||||
context
|
||||
) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case of_pattern(left_expr, stack, context) do
|
||||
{:ok, {:list, left}, context} ->
|
||||
case of_pattern(right_expr, stack, context) do
|
||||
{:ok, {:list, right}, context} ->
|
||||
{:ok, {:list, to_union([left, right], context)}, context}
|
||||
|
||||
{:ok, right, context} ->
|
||||
{:ok, {:list, to_union([left, right], context)}, context}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# _
|
||||
def of_pattern({:_, _meta, atom}, _stack, context) when is_atom(atom) do
|
||||
{:ok, :dynamic, context}
|
||||
end
|
||||
|
||||
# ^var
|
||||
def of_pattern({:^, _meta, [var]}, _stack, context) do
|
||||
{:ok, get_var!(var, context), context}
|
||||
end
|
||||
|
||||
# var
|
||||
def of_pattern(var, _stack, context) when is_var(var) do
|
||||
{type, context} = new_var(var, context)
|
||||
{:ok, type, context}
|
||||
end
|
||||
|
||||
# {left, right}
|
||||
def of_pattern({left, right}, stack, context) do
|
||||
of_pattern({:{}, [], [left, right]}, stack, context)
|
||||
end
|
||||
|
||||
# {...}
|
||||
def of_pattern({:{}, _meta, exprs} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
case map_reduce_ok(exprs, context, &of_pattern(&1, stack, &2)) do
|
||||
{:ok, types, context} -> {:ok, {:tuple, length(types), types}, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
# left = right
|
||||
def of_pattern({:=, _meta, [left_expr, right_expr]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, left_type, context} <- of_pattern(left_expr, stack, context),
|
||||
{:ok, right_type, context} <- of_pattern(right_expr, stack, context),
|
||||
do: unify(left_type, right_type, stack, context)
|
||||
end
|
||||
|
||||
# %{...}
|
||||
def of_pattern({:%{}, _meta, args} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
Of.open_map(args, stack, context, &of_pattern/3)
|
||||
end
|
||||
|
||||
# %Struct{...}
|
||||
def of_pattern({:%, meta1, [module, {:%{}, _meta2, args}]} = expr, stack, context)
|
||||
when is_atom(module) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, struct, context} <- Of.struct(module, meta1, context),
|
||||
{:ok, map, context} <- Of.open_map(args, stack, context, &of_pattern/3) do
|
||||
unify(map, struct, stack, context)
|
||||
end
|
||||
end
|
||||
|
||||
# %_{...}
|
||||
def of_pattern(
|
||||
{:%, _meta1, [{:_, _meta2, var_context}, {:%{}, _meta3, args}]} = expr,
|
||||
stack,
|
||||
context
|
||||
)
|
||||
when is_atom(var_context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, {:map, pairs}, context} <- Of.open_map(args, stack, context, &of_pattern/3) do
|
||||
{:ok, {:map, [{:required, {:atom, :__struct__}, :atom} | pairs]}, context}
|
||||
end
|
||||
end
|
||||
|
||||
# %var{...} and %^var{...}
|
||||
def of_pattern({:%, _meta1, [var, {:%{}, _meta2, args}]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
|
||||
with {:ok, var_type, context} = of_pattern(var, stack, context),
|
||||
{:ok, _, context} <- unify(var_type, :atom, stack, context),
|
||||
{:ok, {:map, pairs}, context} <- Of.open_map(args, stack, context, &of_pattern/3) do
|
||||
{:ok, {:map, [{:required, {:atom, :__struct__}, var_type} | pairs]}, context}
|
||||
end
|
||||
end
|
||||
|
||||
def unify_kinds(:required, _), do: :required
|
||||
def unify_kinds(_, :required), do: :required
|
||||
def unify_kinds(:optional, :optional), do: :optional
|
||||
|
||||
## GUARDS
|
||||
|
||||
# TODO: Some guards can be changed to intersection types or higher order types
|
||||
@boolean {:union, [{:atom, true}, {:atom, false}]}
|
||||
@number {:union, [:integer, :float]}
|
||||
|
||||
@guard_functions %{
|
||||
{:is_atom, 1} => {[:atom], @boolean},
|
||||
{:is_binary, 1} => {[:binary], @boolean},
|
||||
{:is_bitstring, 1} => {[:binary], @boolean},
|
||||
{:is_boolean, 1} => {[@boolean], @boolean},
|
||||
{:is_float, 1} => {[:float], @boolean},
|
||||
{:is_function, 1} => {[:fun], @boolean},
|
||||
{:is_function, 2} => {[:fun, :integer], @boolean},
|
||||
{:is_integer, 1} => {[:integer], @boolean},
|
||||
{:is_list, 1} => {[{:list, :dynamic}], @boolean},
|
||||
{:is_map, 1} => {[{:map, [{:optional, :dynamic, :dynamic}]}], @boolean},
|
||||
{:is_map_key, 2} => {[:dynamic, {:map, [{:optional, :dynamic, :dynamic}]}], :dynamic},
|
||||
{:is_number, 1} => {[@number], @boolean},
|
||||
{:is_pid, 1} => {[:pid], @boolean},
|
||||
{:is_port, 1} => {[:port], @boolean},
|
||||
{:is_reference, 1} => {[:reference], @boolean},
|
||||
{:is_tuple, 1} => {[:tuple], @boolean},
|
||||
{:<, 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:"=<", 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:>, 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:>=, 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:"/=", 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:"=/=", 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:==, 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:"=:=", 2} => {[:dynamic, :dynamic], @boolean},
|
||||
{:*, 2} => {[@number, @number], @number},
|
||||
{:+, 1} => {[@number], @number},
|
||||
{:+, 2} => {[@number, @number], @number},
|
||||
{:-, 1} => {[@number], @number},
|
||||
{:-, 2} => {[@number, @number], @number},
|
||||
{:/, 2} => {[@number, @number], @number},
|
||||
{:abs, 1} => {[@number], @number},
|
||||
{:ceil, 1} => {[@number], :integer},
|
||||
{:floor, 1} => {[@number], :integer},
|
||||
{:round, 1} => {[@number], :integer},
|
||||
{:trunc, 1} => {[@number], :integer},
|
||||
{:element, 2} => {[:integer, :tuple], :dynamic},
|
||||
{:hd, 1} => {[{:list, :dynamic}], :dynamic},
|
||||
{:length, 1} => {[{:list, :dynamic}], :integer},
|
||||
{:map_get, 2} => {[:dynamic, {:map, [{:optional, :dynamic, :dynamic}]}], :dynamic},
|
||||
{:map_size, 1} => {[{:map, [{:optional, :dynamic, :dynamic}]}], :integer},
|
||||
{:tl, 1} => {[{:list, :dynamic}], :dynamic},
|
||||
{:tuple_size, 1} => {[:tuple], :integer},
|
||||
{:node, 1} => {[{:union, [:pid, :reference, :port]}], :atom},
|
||||
{:binary_part, 3} => {[:binary, :integer, :integer], :binary},
|
||||
{:bit_size, 1} => {[:binary], :integer},
|
||||
{:byte_size, 1} => {[:binary], :integer},
|
||||
{:size, 1} => {[{:union, [:binary, :tuple]}], @boolean},
|
||||
{:div, 2} => {[:integer, :integer], :integer},
|
||||
{:rem, 2} => {[:integer, :integer], :integer},
|
||||
{:node, 0} => {[], :atom},
|
||||
{:self, 0} => {[], :pid},
|
||||
{:bnot, 1} => {[:integer], :integer},
|
||||
{:band, 2} => {[:integer, :integer], :integer},
|
||||
{:bor, 2} => {[:integer, :integer], :integer},
|
||||
{:bxor, 2} => {[:integer, :integer], :integer},
|
||||
{:bsl, 2} => {[:integer, :integer], :integer},
|
||||
{:bsr, 2} => {[:integer, :integer], :integer},
|
||||
{:or, 2} => {[@boolean, @boolean], @boolean},
|
||||
{:and, 2} => {[@boolean, @boolean], @boolean},
|
||||
{:xor, 2} => {[@boolean, @boolean], @boolean},
|
||||
{:not, 1} => {[@boolean], @boolean}
|
||||
|
||||
# Following guards are matched explicitly to handle
|
||||
# type guard functions such as is_atom/1
|
||||
# {:andalso, 2} => {[@boolean, @boolean], @boolean}
|
||||
# {:orelse, 2} => {[@boolean, @boolean], @boolean}
|
||||
}
|
||||
|
||||
@type_guards [
|
||||
:is_atom,
|
||||
:is_binary,
|
||||
:is_bitstring,
|
||||
:is_boolean,
|
||||
:is_float,
|
||||
:is_function,
|
||||
:is_function,
|
||||
:is_integer,
|
||||
:is_list,
|
||||
:is_map,
|
||||
:is_number,
|
||||
:is_pid,
|
||||
:is_port,
|
||||
:is_reference,
|
||||
:is_tuple
|
||||
]
|
||||
|
||||
@doc """
|
||||
Refines the type variables in the typing context using type check guards
|
||||
such as `is_integer/1`.
|
||||
"""
|
||||
def of_guard(expr, %{context: stack_context} = stack, context) when stack_context != :pattern do
|
||||
of_guard(expr, %{stack | context: :pattern}, context)
|
||||
end
|
||||
|
||||
def of_guard({{:., _, [:erlang, :andalso]}, _, [left, right]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
fresh_context = fresh_context(context)
|
||||
|
||||
with {:ok, left_type, left_context} <- of_guard(left, stack, fresh_context),
|
||||
{:ok, right_type, right_context} <- of_guard(right, stack, fresh_context),
|
||||
{:ok, context} <- merge_context_and(context, stack, left_context, right_context),
|
||||
{:ok, _, context} <- unify(left_type, @boolean, stack, context),
|
||||
{:ok, _, context} <- unify(right_type, @boolean, stack, context),
|
||||
do: {:ok, @boolean, context}
|
||||
end
|
||||
|
||||
def of_guard({{:., _, [:erlang, :orelse]}, _, [left, right]} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
fresh_context = fresh_context(context)
|
||||
|
||||
with {:ok, left_type, left_context} <- of_guard(left, stack, fresh_context),
|
||||
{:ok, _right_type, right_context} <- of_guard(right, stack, fresh_context),
|
||||
{:ok, context} <- merge_context_or(context, stack, left_context, right_context),
|
||||
{:ok, _, context} <- unify(left_type, @boolean, stack, context),
|
||||
do: {:ok, @boolean, context}
|
||||
end
|
||||
|
||||
# The unary operators + and - are special cased to avoid common warnings until
|
||||
# we add support for intersection types for the guard functions
|
||||
# -integer / +integer
|
||||
def of_guard({{:., _, [:erlang, guard]}, _, [integer]}, _stack, context)
|
||||
when guard in [:+, :-] and is_integer(integer) do
|
||||
{:ok, :integer, context}
|
||||
end
|
||||
|
||||
# -float / +float
|
||||
def of_guard({{:., _, [:erlang, guard]}, _, [float]}, _stack, context)
|
||||
when guard in [:+, :-] and is_float(float) do
|
||||
{:ok, :float, context}
|
||||
end
|
||||
|
||||
# fun(args)
|
||||
def of_guard({{:., _, [:erlang, guard]}, _, args} = expr, stack, context) do
|
||||
stack = push_expr_stack(expr, stack)
|
||||
{param_types, return_type} = guard_signature(guard, length(args))
|
||||
type_guard? = type_guard?(guard)
|
||||
|
||||
# Only check type guards in the context of and/or/not,
|
||||
# a type guard in the context of is_tuple(x) > :foo
|
||||
# should not affect the inference of x
|
||||
if not type_guard? or stack.type_guards_enabled? do
|
||||
arg_stack = %{stack | type_guards_enabled?: type_guard?}
|
||||
|
||||
with {:ok, arg_types, context} <-
|
||||
map_reduce_ok(args, context, &of_guard(&1, arg_stack, &2)),
|
||||
{:ok, context} <- unify_call(arg_types, param_types, stack, context) do
|
||||
{arg_types, guard_sources} =
|
||||
case arg_types do
|
||||
[{:var, index} | rest_arg_types] when type_guard? ->
|
||||
guard_sources =
|
||||
Map.update(context.guard_sources, index, [:guarded], &[:guarded | &1])
|
||||
|
||||
{rest_arg_types, guard_sources}
|
||||
|
||||
_ ->
|
||||
{arg_types, context.guard_sources}
|
||||
end
|
||||
|
||||
guard_sources =
|
||||
Enum.reduce(arg_types, guard_sources, fn
|
||||
{:var, index}, guard_sources ->
|
||||
Map.update(guard_sources, index, [:fail], &[:fail | &1])
|
||||
|
||||
_, guard_sources ->
|
||||
guard_sources
|
||||
end)
|
||||
|
||||
{:ok, return_type, %{context | guard_sources: guard_sources}}
|
||||
end
|
||||
else
|
||||
{:ok, return_type, context}
|
||||
end
|
||||
end
|
||||
|
||||
# map.field
|
||||
def of_guard({{:., meta1, [map, field]}, meta2, []}, stack, context) do
|
||||
of_guard({{:., meta1, [:erlang, :map_get]}, meta2, [field, map]}, stack, context)
|
||||
end
|
||||
|
||||
# var
|
||||
def of_guard(var, _stack, context) when is_var(var) do
|
||||
type = Map.fetch!(context.vars, var_name(var))
|
||||
{:ok, type, context}
|
||||
end
|
||||
|
||||
# other literals
|
||||
def of_guard(expr, stack, context) do
|
||||
# Fall back to of_pattern/3 for literals
|
||||
of_pattern(expr, stack, context)
|
||||
end
|
||||
|
||||
defp fresh_context(context) do
|
||||
types = Map.new(context.types, fn {var, _} -> {var, :unbound} end)
|
||||
traces = Map.new(context.traces, fn {var, _} -> {var, []} end)
|
||||
%{context | types: types, traces: traces}
|
||||
end
|
||||
|
||||
defp unify_call(args, params, stack, context) do
|
||||
reduce_ok(Enum.zip(args, params), context, fn {arg, param}, context ->
|
||||
case unify(arg, param, stack, context) do
|
||||
{:ok, _, context} -> {:ok, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp merge_context_and(context, stack, left, right) do
|
||||
with {:ok, context} <- unify_new_types(context, stack, left),
|
||||
{:ok, context} <- unify_new_types(context, stack, right) do
|
||||
guard_sources = and_guard_sources(left.guard_sources, right.guard_sources)
|
||||
guard_sources = merge_guard_sources([context.guard_sources, guard_sources])
|
||||
{:ok, %{context | guard_sources: guard_sources}}
|
||||
end
|
||||
end
|
||||
|
||||
defp unify_new_types(context, stack, new_context) do
|
||||
context = merge_traces(context, new_context)
|
||||
|
||||
reduce_ok(Map.to_list(new_context.types), context, fn
|
||||
{_index, :unbound}, context ->
|
||||
{:ok, context}
|
||||
|
||||
{index, new_type}, context ->
|
||||
case unify({:var, index}, new_type, %{stack | trace: false}, context) do
|
||||
{:ok, _, context} ->
|
||||
{:ok, context}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp merge_guard_sources(sources) do
|
||||
Enum.reduce(sources, fn left, right ->
|
||||
Map.merge(left, right, fn _index, left, right -> join_guard_source(left, right) end)
|
||||
end)
|
||||
end
|
||||
|
||||
defp join_guard_source(left, right) do
|
||||
sources = left ++ right
|
||||
|
||||
cond do
|
||||
:fail in sources -> [:fail]
|
||||
:guarded in sources -> [:guarded]
|
||||
true -> []
|
||||
end
|
||||
end
|
||||
|
||||
defp and_guard_sources(left, right) do
|
||||
Map.merge(left, right, fn _index, left, right ->
|
||||
# When the failing guard function wont fail due to type check function before it,
|
||||
# for example: is_list(x) and length(x)
|
||||
if :guarded in left and :fail in right do
|
||||
[:guarded]
|
||||
else
|
||||
join_guard_source(left, right)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp merge_traces(context, new_context) do
|
||||
traces =
|
||||
:maps.fold(
|
||||
fn index, new_traces, traces ->
|
||||
:maps.update_with(index, &(new_traces ++ &1), new_traces, traces)
|
||||
end,
|
||||
context.traces,
|
||||
new_context.traces
|
||||
)
|
||||
|
||||
%{context | traces: traces}
|
||||
end
|
||||
|
||||
defp merge_context_or(context, stack, left, right) do
|
||||
context =
|
||||
case {Map.to_list(left.types), Map.to_list(right.types)} do
|
||||
{[{index, :unbound}], [{index, type}]} ->
|
||||
refine_var(index, type, stack, context)
|
||||
|
||||
{[{index, type}], [{index, :unbound}]} ->
|
||||
refine_var(index, type, stack, context)
|
||||
|
||||
{[{index, left_type}], [{index, right_type}]} ->
|
||||
# Only include right side if left side is from type guard such as is_list(x),
|
||||
# do not refine in case of length(x)
|
||||
left_guard_sources = Map.get(left.guard_sources, index, [])
|
||||
|
||||
if :fail in left_guard_sources do
|
||||
guard_sources = Map.put(context.guard_sources, index, [:fail])
|
||||
context = %{context | guard_sources: guard_sources}
|
||||
refine_var(index, left_type, stack, context)
|
||||
else
|
||||
guard_sources =
|
||||
merge_guard_sources([
|
||||
context.guard_sources,
|
||||
left.guard_sources,
|
||||
right.guard_sources
|
||||
])
|
||||
|
||||
context = %{context | guard_sources: guard_sources}
|
||||
refine_var(index, to_union([left_type, right_type], context), stack, context)
|
||||
end
|
||||
|
||||
{left_types, _right_types} ->
|
||||
Enum.reduce(left_types, context, fn {index, left_type}, context ->
|
||||
left_guard_sources = Map.get(left.guard_sources, index, [])
|
||||
|
||||
if :fail in left_guard_sources do
|
||||
guard_sources =
|
||||
merge_guard_sources([
|
||||
context.guard_sources,
|
||||
left.guard_sources,
|
||||
right.guard_sources
|
||||
])
|
||||
|
||||
context = %{context | guard_sources: guard_sources}
|
||||
refine_var(index, left_type, stack, context)
|
||||
else
|
||||
context
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
{:ok, context}
|
||||
end
|
||||
|
||||
defp guard_signature(name, arity) do
|
||||
Map.fetch!(@guard_functions, {name, arity})
|
||||
end
|
||||
|
||||
defp type_guard?(name) do
|
||||
name in @type_guards
|
||||
end
|
||||
end
|
||||
@@ -1,700 +0,0 @@
|
||||
defmodule Module.Types.Unify do
|
||||
@moduledoc false
|
||||
|
||||
import Module.Types.Helpers
|
||||
|
||||
# Those are the simple types known to the system:
|
||||
#
|
||||
# :dynamic
|
||||
# {:var, var}
|
||||
# {:atom, atom} < :atom
|
||||
# :integer
|
||||
# :float
|
||||
# :pid
|
||||
# :port
|
||||
# :reference
|
||||
#
|
||||
# Those are the composite types:
|
||||
#
|
||||
# {:list, type}
|
||||
# {:tuple, size, [type]} < :tuple
|
||||
# {:union, [type]}
|
||||
# {:map, [{:required | :optional, key_type, value_type}]}
|
||||
#
|
||||
# Once new types are added, they should be considered in:
|
||||
#
|
||||
# * unify (all)
|
||||
# * format_type (all)
|
||||
# * subtype? (subtypes only)
|
||||
# * has_unbound_var? (composite only)
|
||||
# * recursive_type? (composite only)
|
||||
#
|
||||
|
||||
@doc """
|
||||
Unifies two types and returns the unified type and an updated typing context
|
||||
or an error in case of a typing conflict.
|
||||
"""
|
||||
def unify(source, target, stack, context) do
|
||||
case do_unify(source, target, stack, context) do
|
||||
{:ok, type, context} ->
|
||||
{:ok, type, context}
|
||||
|
||||
{:error, reason} ->
|
||||
if stack.context == :pattern do
|
||||
case do_unify(target, source, stack, context) do
|
||||
{:ok, type, context} ->
|
||||
{:ok, type, context}
|
||||
|
||||
{:error, _} ->
|
||||
{:error, reason}
|
||||
end
|
||||
else
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp do_unify(same, same, _stack, context) do
|
||||
{:ok, same, context}
|
||||
end
|
||||
|
||||
defp do_unify(type, {:var, var}, stack, context) do
|
||||
case context.types do
|
||||
%{^var => {:var, var_type}} ->
|
||||
do_unify(type, {:var, var_type}, stack, context)
|
||||
|
||||
%{} ->
|
||||
unify_var(var, type, stack, context, _var_source = false)
|
||||
end
|
||||
end
|
||||
|
||||
defp do_unify({:var, var}, type, stack, context) do
|
||||
case context.types do
|
||||
%{^var => {:var, var_type}} ->
|
||||
do_unify({:var, var_type}, type, stack, context)
|
||||
|
||||
%{} ->
|
||||
unify_var(var, type, stack, context, _var_source = true)
|
||||
end
|
||||
end
|
||||
|
||||
defp do_unify({:tuple, n, sources}, {:tuple, n, targets}, stack, context) do
|
||||
result =
|
||||
map_reduce_ok(Enum.zip(sources, targets), context, fn {source, target}, context ->
|
||||
unify(source, target, stack, context)
|
||||
end)
|
||||
|
||||
case result do
|
||||
{:ok, types, context} -> {:ok, {:tuple, n, types}, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_unify({:list, source}, {:list, target}, stack, context) do
|
||||
case unify(source, target, stack, context) do
|
||||
{:ok, type, context} -> {:ok, {:list, type}, context}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_unify({:map, source_pairs}, {:map, target_pairs}, stack, context) do
|
||||
unify_maps(source_pairs, target_pairs, stack, context)
|
||||
end
|
||||
|
||||
defp do_unify(source, :dynamic, _stack, context) do
|
||||
{:ok, source, context}
|
||||
end
|
||||
|
||||
defp do_unify(:dynamic, target, _stack, context) do
|
||||
{:ok, target, context}
|
||||
end
|
||||
|
||||
defp do_unify(source, target, stack, context) do
|
||||
cond do
|
||||
# This condition exists to handle unions with unbound vars.
|
||||
# TODO: handle unions properly. Note we can easily unify
|
||||
# "union < type" even if union has vars as the vars must be
|
||||
# type
|
||||
(match?({:union, _}, source) and has_unbound_var?(source, context)) or
|
||||
(match?({:union, _}, target) and has_unbound_var?(target, context)) ->
|
||||
{:ok, source, context}
|
||||
|
||||
subtype?(source, target, context) ->
|
||||
{:ok, source, context}
|
||||
|
||||
true ->
|
||||
error(:unable_unify, {source, target, stack}, context)
|
||||
end
|
||||
end
|
||||
|
||||
defp unify_var(var, :dynamic, _stack, context, _var_source?) do
|
||||
{:ok, {:var, var}, context}
|
||||
end
|
||||
|
||||
defp unify_var(var, type, stack, context, var_source?) do
|
||||
case context.types do
|
||||
%{^var => :unbound} ->
|
||||
context = refine_var(var, type, stack, context)
|
||||
stack = push_unify_stack(var, stack)
|
||||
|
||||
if recursive_type?(type, [], context) do
|
||||
if var_source? do
|
||||
error(:unable_unify, {{:var, var}, type, stack}, context)
|
||||
else
|
||||
error(:unable_unify, {type, {:var, var}, stack}, context)
|
||||
end
|
||||
else
|
||||
{:ok, {:var, var}, context}
|
||||
end
|
||||
|
||||
%{^var => var_type} ->
|
||||
# Only add trace if the variable wasn't already "expanded"
|
||||
context =
|
||||
if variable_expanded?(var, stack, context) do
|
||||
context
|
||||
else
|
||||
trace_var(var, type, stack, context)
|
||||
end
|
||||
|
||||
stack = push_unify_stack(var, stack)
|
||||
|
||||
unify_result =
|
||||
if var_source? do
|
||||
unify(var_type, type, stack, context)
|
||||
else
|
||||
unify(type, var_type, stack, context)
|
||||
end
|
||||
|
||||
case unify_result do
|
||||
{:ok, var_type, context} ->
|
||||
context = refine_var(var, var_type, stack, context)
|
||||
{:ok, {:var, var}, context}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# * All required keys on each side need to match to the other side.
|
||||
# * All optional keys on each side that do not match must be discarded.
|
||||
|
||||
defp unify_maps(source_pairs, target_pairs, stack, context) do
|
||||
{source_required, source_optional} = split_pairs(source_pairs)
|
||||
{target_required, target_optional} = split_pairs(target_pairs)
|
||||
|
||||
with {:ok, source_required_pairs, context} <-
|
||||
unify_source_required(source_required, target_pairs, stack, context),
|
||||
{:ok, target_required_pairs, context} <-
|
||||
unify_target_required(target_required, source_pairs, stack, context),
|
||||
{:ok, source_optional_pairs, context} <-
|
||||
unify_source_optional(source_optional, target_optional, stack, context),
|
||||
{:ok, target_optional_pairs, context} <-
|
||||
unify_target_optional(target_optional, source_optional, stack, context) do
|
||||
# Remove duplicate pairs from matching in both left and right directions
|
||||
pairs =
|
||||
Enum.uniq(
|
||||
source_required_pairs ++
|
||||
target_required_pairs ++
|
||||
source_optional_pairs ++
|
||||
target_optional_pairs
|
||||
)
|
||||
|
||||
{:ok, {:map, pairs}, context}
|
||||
else
|
||||
{:error, :unify} ->
|
||||
error(:unable_unify, {{:map, source_pairs}, {:map, target_pairs}, stack}, context)
|
||||
|
||||
{:error, context} ->
|
||||
{:error, context}
|
||||
end
|
||||
end
|
||||
|
||||
defp unify_source_required(source_required, target_pairs, stack, context) do
|
||||
map_reduce_ok(source_required, context, fn {source_key, source_value}, context ->
|
||||
Enum.find_value(target_pairs, fn {target_kind, target_key, target_value} ->
|
||||
with {:ok, key, context} <- unify(source_key, target_key, stack, context) do
|
||||
case unify(source_value, target_value, stack, context) do
|
||||
{:ok, value, context} ->
|
||||
{:ok, {:required, key, value}, context}
|
||||
|
||||
{:error, _reason} ->
|
||||
source_map = {:map, [{:required, source_key, source_value}]}
|
||||
target_map = {:map, [{target_kind, target_key, target_value}]}
|
||||
error(:unable_unify, {source_map, target_map, stack}, context)
|
||||
end
|
||||
else
|
||||
{:error, _reason} -> nil
|
||||
end
|
||||
end) || {:error, :unify}
|
||||
end)
|
||||
end
|
||||
|
||||
defp unify_target_required(target_required, source_pairs, stack, context) do
|
||||
map_reduce_ok(target_required, context, fn {target_key, target_value}, context ->
|
||||
Enum.find_value(source_pairs, fn {source_kind, source_key, source_value} ->
|
||||
with {:ok, key, context} <- unify(source_key, target_key, stack, context) do
|
||||
case unify(source_value, target_value, stack, context) do
|
||||
{:ok, value, context} ->
|
||||
{:ok, {:required, key, value}, context}
|
||||
|
||||
{:error, _reason} ->
|
||||
source_map = {:map, [{source_kind, source_key, source_value}]}
|
||||
target_map = {:map, [{:required, target_key, target_value}]}
|
||||
error(:unable_unify, {source_map, target_map, stack}, context)
|
||||
end
|
||||
else
|
||||
{:error, _reason} -> nil
|
||||
end
|
||||
end) || {:error, :unify}
|
||||
end)
|
||||
end
|
||||
|
||||
defp unify_source_optional(source_optional, target_optional, stack, context) do
|
||||
flat_map_reduce_ok(source_optional, context, fn {source_key, source_value}, context ->
|
||||
Enum.find_value(target_optional, fn {target_key, target_value} ->
|
||||
with {:ok, key, context} <- unify(source_key, target_key, stack, context) do
|
||||
case unify(source_value, target_value, stack, context) do
|
||||
{:ok, value, context} ->
|
||||
{:ok, [{:optional, key, value}], context}
|
||||
|
||||
{:error, _reason} ->
|
||||
source_map = {:map, [{:optional, source_key, source_value}]}
|
||||
target_map = {:map, [{:optional, target_key, target_value}]}
|
||||
error(:unable_unify, {source_map, target_map, stack}, context)
|
||||
end
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end) || {:ok, [], context}
|
||||
end)
|
||||
end
|
||||
|
||||
defp unify_target_optional(target_optional, source_optional, stack, context) do
|
||||
flat_map_reduce_ok(target_optional, context, fn {target_key, target_value}, context ->
|
||||
Enum.find_value(source_optional, fn {source_key, source_value} ->
|
||||
with {:ok, key, context} <- unify(source_key, target_key, stack, context) do
|
||||
case unify(source_value, target_value, stack, context) do
|
||||
{:ok, value, context} ->
|
||||
{:ok, [{:optional, key, value}], context}
|
||||
|
||||
{:error, _reason} ->
|
||||
source_map = {:map, [{:optional, source_key, source_value}]}
|
||||
target_map = {:map, [{:optional, target_key, target_value}]}
|
||||
error(:unable_unify, {source_map, target_map, stack}, context)
|
||||
end
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end) || {:ok, [], context}
|
||||
end)
|
||||
end
|
||||
|
||||
defp split_pairs(pairs) do
|
||||
{required, optional} =
|
||||
Enum.split_with(pairs, fn {kind, _key, _value} -> kind == :required end)
|
||||
|
||||
required = Enum.map(required, fn {_kind, key, value} -> {key, value} end)
|
||||
optional = Enum.map(optional, fn {_kind, key, value} -> {key, value} end)
|
||||
{required, optional}
|
||||
end
|
||||
|
||||
defp error(type, reason, context), do: {:error, {type, reason, context}}
|
||||
|
||||
@doc """
|
||||
Push expression to stack.
|
||||
|
||||
The expression stack is used to give the context where a type variable
|
||||
was refined when show a type conflict error.
|
||||
"""
|
||||
def push_expr_stack(expr, stack) do
|
||||
%{stack | last_expr: expr}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a variable.
|
||||
"""
|
||||
def get_var!(var, context) do
|
||||
Map.fetch!(context.vars, var_name(var))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds a variable to the typing context and returns its type variable.
|
||||
If the variable has already been added, return the existing type variable.
|
||||
"""
|
||||
def new_var(var, context) do
|
||||
var_name = var_name(var)
|
||||
|
||||
case context.vars do
|
||||
%{^var_name => type} ->
|
||||
{type, context}
|
||||
|
||||
%{} ->
|
||||
type = {:var, context.counter}
|
||||
vars = Map.put(context.vars, var_name, type)
|
||||
types_to_vars = Map.put(context.types_to_vars, context.counter, var)
|
||||
types = Map.put(context.types, context.counter, :unbound)
|
||||
traces = Map.put(context.traces, context.counter, [])
|
||||
|
||||
context = %{
|
||||
context
|
||||
| vars: vars,
|
||||
types_to_vars: types_to_vars,
|
||||
types: types,
|
||||
traces: traces,
|
||||
counter: context.counter + 1
|
||||
}
|
||||
|
||||
{type, context}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds an internal variable to the typing context and returns its type variable.
|
||||
An internal variable is used to help unify complex expressions,
|
||||
it does not belong to a specific AST expression.
|
||||
"""
|
||||
def add_var(context) do
|
||||
type = {:var, context.counter}
|
||||
types = Map.put(context.types, context.counter, :unbound)
|
||||
traces = Map.put(context.traces, context.counter, [])
|
||||
|
||||
context = %{
|
||||
context
|
||||
| types: types,
|
||||
traces: traces,
|
||||
counter: context.counter + 1
|
||||
}
|
||||
|
||||
{type, context}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Resolves a variable raising if it is unbound.
|
||||
"""
|
||||
def resolve_var({:var, var}, context) do
|
||||
case context.types do
|
||||
%{^var => :unbound} -> raise "cannot resolve unbound var"
|
||||
%{^var => type} -> resolve_var(type, context)
|
||||
end
|
||||
end
|
||||
|
||||
def resolve_var(other, _context), do: other
|
||||
|
||||
# Check unify stack to see if variable was already expanded
|
||||
defp variable_expanded?(var, stack, context) do
|
||||
Enum.any?(stack.unify_stack, &variable_same?(var, &1, context))
|
||||
end
|
||||
|
||||
defp variable_same?(left, right, context) do
|
||||
case context.types do
|
||||
%{^left => {:var, new_left}} ->
|
||||
variable_same?(new_left, right, context)
|
||||
|
||||
%{^right => {:var, new_right}} ->
|
||||
variable_same?(left, new_right, context)
|
||||
|
||||
%{} ->
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
defp push_unify_stack(var, stack) do
|
||||
%{stack | unify_stack: [var | stack.unify_stack]}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Set the type for a variable and add trace.
|
||||
"""
|
||||
def refine_var(var, type, stack, context) do
|
||||
types = Map.put(context.types, var, type)
|
||||
context = %{context | types: types}
|
||||
trace_var(var, type, stack, context)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Remove type variable and all its traces.
|
||||
"""
|
||||
def remove_var(var, context) do
|
||||
types = Map.delete(context.types, var)
|
||||
traces = Map.delete(context.traces, var)
|
||||
%{context | types: types, traces: traces}
|
||||
end
|
||||
|
||||
defp trace_var(var, type, %{trace: true, last_expr: last_expr} = _stack, context) do
|
||||
line = get_meta(last_expr)[:line]
|
||||
trace = {type, last_expr, {context.file, line}}
|
||||
traces = Map.update!(context.traces, var, &[trace | &1])
|
||||
%{context | traces: traces}
|
||||
end
|
||||
|
||||
defp trace_var(_var, _type, %{trace: false} = _stack, context) do
|
||||
context
|
||||
end
|
||||
|
||||
# Check if a variable is recursive and incompatible with itself
|
||||
# Bad: `{var} = var`
|
||||
# Good: `x = y; y = z; z = x`
|
||||
defp recursive_type?({:var, var} = parent, parents, context) do
|
||||
case context.types do
|
||||
%{^var => :unbound} ->
|
||||
false
|
||||
|
||||
%{^var => type} ->
|
||||
if type in parents do
|
||||
not Enum.all?(parents, &match?({:var, _}, &1))
|
||||
else
|
||||
recursive_type?(type, [parent | parents], context)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp recursive_type?({:list, type} = parent, parents, context) do
|
||||
recursive_type?(type, [parent | parents], context)
|
||||
end
|
||||
|
||||
defp recursive_type?({:union, types} = parent, parents, context) do
|
||||
Enum.any?(types, &recursive_type?(&1, [parent | parents], context))
|
||||
end
|
||||
|
||||
defp recursive_type?({:tuple, _, types} = parent, parents, context) do
|
||||
Enum.any?(types, &recursive_type?(&1, [parent | parents], context))
|
||||
end
|
||||
|
||||
defp recursive_type?({:map, pairs} = parent, parents, context) do
|
||||
Enum.any?(pairs, fn {_kind, key, value} ->
|
||||
recursive_type?(key, [parent | parents], context) or
|
||||
recursive_type?(value, [parent | parents], context)
|
||||
end)
|
||||
end
|
||||
|
||||
defp recursive_type?(_other, _parents, _context) do
|
||||
false
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the type has a type var.
|
||||
"""
|
||||
def has_unbound_var?({:var, var}, context) do
|
||||
case context.types do
|
||||
%{^var => :unbound} -> true
|
||||
%{^var => type} -> has_unbound_var?(type, context)
|
||||
end
|
||||
end
|
||||
|
||||
def has_unbound_var?({:tuple, _, args}, context),
|
||||
do: Enum.any?(args, &has_unbound_var?(&1, context))
|
||||
|
||||
def has_unbound_var?({:union, args}, context),
|
||||
do: Enum.any?(args, &has_unbound_var?(&1, context))
|
||||
|
||||
def has_unbound_var?({:list, arg}, context),
|
||||
do: has_unbound_var?(arg, context)
|
||||
|
||||
def has_unbound_var?({:map, pairs}, context) do
|
||||
Enum.any?(pairs, fn {_, key, value} ->
|
||||
has_unbound_var?(key, context) or has_unbound_var?(value, context)
|
||||
end)
|
||||
end
|
||||
|
||||
def has_unbound_var?(_type, _context), do: false
|
||||
|
||||
@doc """
|
||||
Returns true if it is a singleton type.
|
||||
|
||||
Only atoms are singleton types. Unbound vars are not
|
||||
considered singleton types.
|
||||
"""
|
||||
def singleton?({:var, var}, context) do
|
||||
case context.types do
|
||||
%{^var => :unbound} -> false
|
||||
%{^var => type} -> singleton?(type, context)
|
||||
end
|
||||
end
|
||||
|
||||
def singleton?({:atom, _}, _context), do: true
|
||||
def singleton?(_type, _context), do: false
|
||||
|
||||
@doc """
|
||||
Checks if the first argument is a subtype of the second argument.
|
||||
|
||||
This function assumes that:
|
||||
|
||||
* unbound variables are not subtype of anything
|
||||
|
||||
* dynamic is not considered a subtype of all other types but the top type.
|
||||
This allows this function can be used for ordering, in other cases, you
|
||||
may need to check for both sides
|
||||
|
||||
"""
|
||||
def subtype?(type, type, _context), do: true
|
||||
|
||||
def subtype?({:var, var}, other, context) do
|
||||
case context.types do
|
||||
%{^var => :unbound} -> false
|
||||
%{^var => type} -> subtype?(type, other, context)
|
||||
end
|
||||
end
|
||||
|
||||
def subtype?(other, {:var, var}, context) do
|
||||
case context.types do
|
||||
%{^var => :unbound} -> false
|
||||
%{^var => type} -> subtype?(other, type, context)
|
||||
end
|
||||
end
|
||||
|
||||
def subtype?(_, :dynamic, _context), do: true
|
||||
def subtype?({:atom, atom}, :atom, _context) when is_atom(atom), do: true
|
||||
|
||||
# Composite
|
||||
|
||||
def subtype?({:tuple, _, _}, :tuple, _context), do: true
|
||||
|
||||
def subtype?({:tuple, n, left_types}, {:tuple, n, right_types}, context) do
|
||||
left_types
|
||||
|> Enum.zip(right_types)
|
||||
|> Enum.any?(fn {left, right} -> subtype?(left, right, context) end)
|
||||
end
|
||||
|
||||
def subtype?({:map, left_pairs}, {:map, right_pairs}, context) do
|
||||
Enum.all?(left_pairs, fn
|
||||
{:required, left_key, left_value} ->
|
||||
Enum.any?(right_pairs, fn {_, right_key, right_value} ->
|
||||
subtype?(left_key, right_key, context) and subtype?(left_value, right_value, context)
|
||||
end)
|
||||
|
||||
{:optional, _, _} ->
|
||||
true
|
||||
end)
|
||||
end
|
||||
|
||||
def subtype?({:list, left}, {:list, right}, context) do
|
||||
subtype?(left, right, context)
|
||||
end
|
||||
|
||||
def subtype?({:union, left_types}, {:union, _} = right_union, context) do
|
||||
Enum.all?(left_types, &subtype?(&1, right_union, context))
|
||||
end
|
||||
|
||||
def subtype?(left, {:union, right_types}, context) do
|
||||
Enum.any?(right_types, &subtype?(left, &1, context))
|
||||
end
|
||||
|
||||
def subtype?({:union, left_types}, right, context) do
|
||||
Enum.all?(left_types, &subtype?(&1, right, context))
|
||||
end
|
||||
|
||||
def subtype?(_left, _right, _context), do: false
|
||||
|
||||
@doc """
|
||||
Returns a "simplified" union using `subtype?/3` to remove redundant types.
|
||||
|
||||
Due to limitations in `subtype?/3` some overlapping types may still be
|
||||
included. For example unions with overlapping non-concrete types such as
|
||||
`{boolean()} | {atom()}` will not be merged or types with variables that
|
||||
are distinct but equivalent such as `a | b when a ~ b`.
|
||||
"""
|
||||
def to_union([type], _context), do: type
|
||||
|
||||
def to_union(types, context) when types != [] do
|
||||
flat_types = flatten_union(types)
|
||||
|
||||
case unique_super_types(flat_types, context) do
|
||||
[type] -> type
|
||||
types -> {:union, types}
|
||||
end
|
||||
end
|
||||
|
||||
defp flatten_union(types) do
|
||||
Enum.flat_map(types, fn
|
||||
{:union, types} -> flatten_union(types)
|
||||
type -> [type]
|
||||
end)
|
||||
end
|
||||
|
||||
# Filter subtypes
|
||||
#
|
||||
# `boolean() | atom()` => `atom()`
|
||||
# `:foo | atom()` => `atom()`
|
||||
#
|
||||
# Does not merge `true | false` => `boolean()`
|
||||
defp unique_super_types([type | types], context) do
|
||||
types = Enum.reject(types, &subtype?(&1, type, context))
|
||||
|
||||
if Enum.any?(types, &subtype?(type, &1, context)) do
|
||||
unique_super_types(types, context)
|
||||
else
|
||||
[type | unique_super_types(types, context)]
|
||||
end
|
||||
end
|
||||
|
||||
defp unique_super_types([], _context) do
|
||||
[]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Formats types.
|
||||
|
||||
The second argument says when complex types such as maps and
|
||||
structs should be simplified and not shown.
|
||||
"""
|
||||
def format_type({:map, pairs}, true) do
|
||||
case List.keyfind(pairs, {:atom, :__struct__}, 1) do
|
||||
{:required, {:atom, :__struct__}, {:atom, struct}} ->
|
||||
"%#{inspect(struct)}{}"
|
||||
|
||||
_ ->
|
||||
"map()"
|
||||
end
|
||||
end
|
||||
|
||||
def format_type({:union, types}, simplify?) do
|
||||
"#{Enum.map_join(types, " | ", &format_type(&1, simplify?))}"
|
||||
end
|
||||
|
||||
def format_type({:tuple, _, types}, simplify?) do
|
||||
"{#{Enum.map_join(types, ", ", &format_type(&1, simplify?))}}"
|
||||
end
|
||||
|
||||
def format_type({:list, type}, simplify?) do
|
||||
"[#{format_type(type, simplify?)}]"
|
||||
end
|
||||
|
||||
def format_type({:map, pairs}, false) do
|
||||
case List.keytake(pairs, {:atom, :__struct__}, 1) do
|
||||
{{:required, {:atom, :__struct__}, {:atom, struct}}, pairs} ->
|
||||
"%#{inspect(struct)}{#{format_map_pairs(pairs)}}"
|
||||
|
||||
_ ->
|
||||
"%{#{format_map_pairs(pairs)}}"
|
||||
end
|
||||
end
|
||||
|
||||
def format_type({:atom, literal}, _simplify?) do
|
||||
inspect(literal)
|
||||
end
|
||||
|
||||
def format_type({:var, index}, _simplify?) do
|
||||
"var#{index}"
|
||||
end
|
||||
|
||||
def format_type(atom, _simplify?) when is_atom(atom) do
|
||||
"#{atom}()"
|
||||
end
|
||||
|
||||
defp format_map_pairs(pairs) do
|
||||
{atoms, others} = Enum.split_with(pairs, &match?({:required, {:atom, _}, _}, &1))
|
||||
{required, optional} = Enum.split_with(others, &match?({:required, _, _}, &1))
|
||||
|
||||
Enum.map_join(atoms ++ required ++ optional, ", ", fn
|
||||
{:required, {:atom, atom}, right} ->
|
||||
"#{atom}: #{format_type(right, false)}"
|
||||
|
||||
{:required, left, right} ->
|
||||
"#{format_type(left, false)} => #{format_type(right, false)}"
|
||||
|
||||
{:optional, left, right} ->
|
||||
"optional(#{format_type(left, false)}) => #{format_type(right, false)}"
|
||||
end)
|
||||
end
|
||||
end
|
||||
+5
-20
@@ -13,23 +13,8 @@ defmodule Node do
|
||||
@doc """
|
||||
Turns a non-distributed node into a distributed node.
|
||||
|
||||
This functionality starts the `:net_kernel` and other related
|
||||
processes.
|
||||
|
||||
This function is rarely invoked in practice. Instead, nodes are
|
||||
named and started via the command line by using the `--sname` and
|
||||
`--name` flags. If you need to use this function to dynamically
|
||||
name a node, please make sure the `epmd` operating system process
|
||||
is running by calling `epmd -daemon`.
|
||||
|
||||
Invoking this function when the distribution has already been started,
|
||||
either via the command line interface or dynamically, will return an
|
||||
error.
|
||||
|
||||
## Examples
|
||||
|
||||
{:ok, pid} = Node.start(:example, :shortnames, 15000)
|
||||
|
||||
This functionality starts the `:net_kernel` and other
|
||||
related processes.
|
||||
"""
|
||||
@spec start(node, :longnames | :shortnames, non_neg_integer) :: {:ok, pid} | {:error, term}
|
||||
def start(name, type \\ :longnames, tick_time \\ 15000) do
|
||||
@@ -106,7 +91,7 @@ defmodule Node do
|
||||
|
||||
For more information, see `:erlang.monitor_node/2`.
|
||||
|
||||
For monitoring status changes of all nodes, see `:net_kernel.monitor_nodes/2`.
|
||||
For monitoring status changes of all nodes, see `:net_kernel.monitor_nodes/3`.
|
||||
"""
|
||||
@spec monitor(t, boolean) :: true
|
||||
def monitor(node, flag) do
|
||||
@@ -119,7 +104,7 @@ defmodule Node do
|
||||
|
||||
For more information, see `:erlang.monitor_node/3`.
|
||||
|
||||
For monitoring status changes of all nodes, see `:net_kernel.monitor_nodes/2`.
|
||||
For monitoring status changes of all nodes, see `:net_kernel.monitor_nodes/3`.
|
||||
"""
|
||||
@spec monitor(t, boolean, [:allow_passive_connect]) :: true
|
||||
def monitor(node, flag, options) do
|
||||
@@ -219,7 +204,7 @@ 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/5`.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
|
||||
@@ -20,7 +20,7 @@ defmodule Path do
|
||||
|
||||
## Examples
|
||||
|
||||
### Unix-like operating systems
|
||||
### Unix
|
||||
|
||||
Path.absname("foo")
|
||||
#=> "/usr/local/foo"
|
||||
@@ -152,8 +152,8 @@ defmodule Path do
|
||||
|
||||
## Examples
|
||||
|
||||
Path.expand("/foo/bar/../baz")
|
||||
#=> "/foo/baz"
|
||||
Path.expand("/foo/bar/../bar")
|
||||
#=> "/foo/bar"
|
||||
|
||||
"""
|
||||
@spec expand(t) :: binary
|
||||
@@ -195,7 +195,7 @@ defmodule Path do
|
||||
|
||||
## Examples
|
||||
|
||||
### Unix-like operating systems
|
||||
### Unix
|
||||
|
||||
Path.type("/") #=> :absolute
|
||||
Path.type("/usr/local/bin") #=> :absolute
|
||||
@@ -223,7 +223,7 @@ defmodule Path do
|
||||
|
||||
## Examples
|
||||
|
||||
### Unix-like operating systems
|
||||
### Unix
|
||||
|
||||
Path.relative("/usr/local/bin") #=> "usr/local/bin"
|
||||
Path.relative("usr/local/bin") #=> "usr/local/bin"
|
||||
@@ -522,7 +522,6 @@ defmodule Path do
|
||||
do_join(left, right, os_type) |> remove_dir_sep(os_type)
|
||||
end
|
||||
|
||||
defp do_join(left, "/", os_type), do: remove_dir_sep(left, os_type)
|
||||
defp do_join("", right, os_type), do: relative(right, os_type)
|
||||
defp do_join("/", right, os_type), do: "/" <> relative(right, os_type)
|
||||
|
||||
@@ -565,6 +564,9 @@ defmodule Path do
|
||||
"""
|
||||
@spec split(t) :: [binary]
|
||||
|
||||
# Work around a bug in Erlang on UNIX
|
||||
def split(""), do: []
|
||||
|
||||
def split(path) do
|
||||
:filename.split(IO.chardata_to_string(path))
|
||||
end
|
||||
|
||||
+16
-38
@@ -20,7 +20,7 @@ defmodule Port do
|
||||
:ok
|
||||
|
||||
In the example above, we have created a new port that executes the
|
||||
program `cat`. `cat` is a program available on Unix-like operating systems that
|
||||
program `cat`. `cat` is a program available on UNIX systems that
|
||||
receives data from multiple inputs and concatenates them in the output.
|
||||
|
||||
After the port was created, we sent it two commands in the form of
|
||||
@@ -29,7 +29,7 @@ defmodule Port do
|
||||
|
||||
After sending those two messages, we invoked the IEx helper `flush()`,
|
||||
which printed all messages received from the port, in this case we got
|
||||
"hello" and "world" back. Note that the messages are in binary because we
|
||||
"hello" and "world" back. Notice the messages are in binary because we
|
||||
passed the `:binary` option when opening the port in `Port.open/2`. Without
|
||||
such option, it would have yielded a list of bytes.
|
||||
|
||||
@@ -124,42 +124,20 @@ defmodule Port do
|
||||
will have its stdin and stdout channels closed but **it won't be automatically
|
||||
terminated**.
|
||||
|
||||
While most Unix command line tools will exit once its communication channels
|
||||
are closed, not all command line applications will do so. You can easily check
|
||||
this by starting the port and then shutting down the VM and inspecting your
|
||||
operating system to see if the port process is still running.
|
||||
While most UNIX command line tools will exit once its communication channels
|
||||
are closed, not all command line applications will do so. While we encourage
|
||||
graceful termination by detecting if stdin/stdout has been closed, we do not
|
||||
always have control over how third-party software terminates. In those cases,
|
||||
you can wrap the application in a script that checks for stdin. Here is such
|
||||
script in Bash:
|
||||
|
||||
While we encourage graceful termination by detecting if stdin/stdout has been
|
||||
closed, we do not always have control over how third-party software terminates.
|
||||
In those cases, you can wrap the application in a script that checks for stdin.
|
||||
Here is such script that has been verified to work on bash shells:
|
||||
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Start the program in the background
|
||||
exec "$@" &
|
||||
pid1=$!
|
||||
|
||||
# Silence warnings from here on
|
||||
exec >/dev/null 2>&1
|
||||
|
||||
# Read from stdin in the background and
|
||||
# kill running program when stdin closes
|
||||
exec 0<&0 $(
|
||||
while read; do :; done
|
||||
kill -KILL $pid1
|
||||
) &
|
||||
pid2=$!
|
||||
|
||||
# Clean up
|
||||
wait $pid1
|
||||
ret=$?
|
||||
kill -KILL $pid2
|
||||
exit $ret
|
||||
|
||||
Note the program above hijacks stdin, so you won't be able to communicate
|
||||
with the underlying software via stdin (on the positive side, software that
|
||||
reads from stdin typically terminates when stdin closes).
|
||||
#!/bin/bash
|
||||
"$@" &
|
||||
pid=$!
|
||||
while read line ; do
|
||||
:
|
||||
done
|
||||
kill -KILL $pid
|
||||
|
||||
Now instead of:
|
||||
|
||||
@@ -180,7 +158,7 @@ defmodule Port do
|
||||
@type name ::
|
||||
{:spawn, charlist | binary}
|
||||
| {:spawn_driver, charlist | binary}
|
||||
| {:spawn_executable, :file.name_all()}
|
||||
| {:spawn_executable, charlist | atom}
|
||||
| {:fd, non_neg_integer, non_neg_integer}
|
||||
|
||||
@doc """
|
||||
|
||||
@@ -583,7 +583,7 @@ defmodule Process do
|
||||
send(:test, :hello)
|
||||
#=> :hello
|
||||
send(:wrong_name, :hello)
|
||||
** (ArgumentError) argument error
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec register(pid | port, atom) :: true
|
||||
@@ -620,7 +620,7 @@ defmodule Process do
|
||||
Process.unregister(:test)
|
||||
#=> true
|
||||
Process.unregister(:wrong_name)
|
||||
** (ArgumentError) argument error
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec unregister(atom) :: true
|
||||
@@ -705,10 +705,11 @@ defmodule Process do
|
||||
"""
|
||||
@spec flag(:error_handler, module) :: module
|
||||
@spec flag(:max_heap_size, heap_size) :: heap_size
|
||||
# :off_heap | :on_heap twice because :erlang.message_queue_data() is not exported
|
||||
@spec flag(:message_queue_data, :off_heap | :on_heap) :: :off_heap | :on_heap
|
||||
@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
|
||||
|
||||
+16
-37
@@ -43,14 +43,10 @@ defmodule Protocol do
|
||||
def size(tuple), do: tuple_size(tuple)
|
||||
end
|
||||
|
||||
Note that we didn't implement it for lists as we don't have the
|
||||
Notice we didn't implement it for lists as we don't have the
|
||||
`size` information on lists, rather its value needs to be
|
||||
computed with `length`.
|
||||
|
||||
The data structure you are implementing the protocol for
|
||||
must be the first argument to all functions defined in the
|
||||
protocol.
|
||||
|
||||
It is possible to implement protocols for all Elixir types:
|
||||
|
||||
* Structs (see below)
|
||||
@@ -167,15 +163,15 @@ defmodule Protocol do
|
||||
|
||||
* `:consolidated?` - returns whether the protocol is consolidated
|
||||
|
||||
* `:functions` - returns a keyword list of protocol functions and their arities
|
||||
* `:functions` - returns keyword list of protocol functions and their arities
|
||||
|
||||
* `:impls` - if consolidated, returns `{:consolidated, modules}` with the list of modules
|
||||
implementing the protocol, otherwise `:not_consolidated`
|
||||
implementing the protocol, otherwise `:not_consolidated`
|
||||
|
||||
* `:module` - the protocol module atom name
|
||||
|
||||
* `impl_for/1` - returns the module that implements the protocol for the given argument,
|
||||
`nil` otherwise
|
||||
* `impl_for/1` - receives a structure and returns the module that
|
||||
implements the protocol for the structure, `nil` otherwise
|
||||
|
||||
* `impl_for!/1` - same as above but raises an error if an implementation is
|
||||
not found
|
||||
@@ -191,22 +187,6 @@ defmodule Protocol do
|
||||
iex> Enumerable.impl_for(42)
|
||||
nil
|
||||
|
||||
In addition, every protocol implementation module contains the `__impl__/1` function. The
|
||||
function takes one of the following atoms:
|
||||
|
||||
* `:for` - returns the module responsible for the data structure of the protocol implementation
|
||||
|
||||
* `:protocol` - returns the protocol module for which this implementation is provided
|
||||
|
||||
For example, the module implementing the `Enumerable` protocol for lists is `Enumerable.List`.
|
||||
Therefore, we can invoke `__impl__/1` on this module:
|
||||
|
||||
iex(1)> Enumerable.List.__impl__(:for)
|
||||
List
|
||||
|
||||
iex(2)> Enumerable.List.__impl__(:protocol)
|
||||
Enumerable
|
||||
|
||||
## Consolidation
|
||||
|
||||
In order to cope with code loading in development, protocols in
|
||||
@@ -215,7 +195,7 @@ defmodule Protocol do
|
||||
|
||||
In order to speed up dispatching in production environments, where
|
||||
all implementations are known up-front, Elixir provides a feature
|
||||
called *protocol consolidation*. Consolidation directly links protocols
|
||||
called protocol consolidation. Consolidation directly links protocols
|
||||
to their implementations in a way that invoking a function from a
|
||||
consolidated protocol is equivalent to invoking two remote functions.
|
||||
|
||||
@@ -250,10 +230,9 @@ defmodule Protocol do
|
||||
Although doing so is not recommended as it may affect your test suite
|
||||
performance.
|
||||
|
||||
Finally, note all protocols are compiled with `debug_info` set to `true`,
|
||||
regardless of the option set by the `elixirc` compiler. The debug info is
|
||||
used for consolidation and it is removed after consolidation unless
|
||||
globally set.
|
||||
Finally note all protocols are compiled with `debug_info` set to `true`,
|
||||
regardless of the option set by `elixirc` compiler. The debug info is
|
||||
used for consolidation and it may be removed after consolidation.
|
||||
"""
|
||||
|
||||
@doc false
|
||||
@@ -479,7 +458,6 @@ defmodule Protocol do
|
||||
|
||||
defp extract_matching_by_attribute(paths, prefix, callback) do
|
||||
for path <- paths,
|
||||
path = to_charlist(path),
|
||||
file <- list_dir(path),
|
||||
mod = extract_from_file(path, file, prefix, callback),
|
||||
do: mod
|
||||
@@ -492,6 +470,8 @@ defmodule Protocol do
|
||||
end
|
||||
end
|
||||
|
||||
defp list_dir(path), do: list_dir(to_charlist(path))
|
||||
|
||||
defp extract_from_file(path, file, prefix, callback) do
|
||||
if :lists.prefix(prefix, file) and :filename.extension(file) == '.beam' do
|
||||
extract_from_beam(:filename.join(path, file), callback)
|
||||
@@ -551,14 +531,13 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
defp beam_protocol(protocol) do
|
||||
chunk_ids = [:debug_info, 'Docs', 'ExCk']
|
||||
chunk_ids = [:debug_info, 'Docs', 'ExDp']
|
||||
opts = [:allow_missing_chunks]
|
||||
|
||||
case :beam_lib.chunks(beam_file(protocol), chunk_ids, opts) do
|
||||
{:ok, {^protocol, [{:debug_info, debug_info} | chunks]}} ->
|
||||
{:debug_info_v1, _backend, {:elixir_v1, info, specs}} = debug_info
|
||||
%{attributes: attributes, definitions: definitions} = info
|
||||
chunks = :lists.filter(fn {_name, value} -> value != :missing_chunk end, chunks)
|
||||
chunks = :lists.map(fn {name, value} -> {List.to_string(name), value} end, chunks)
|
||||
|
||||
case attributes[:protocol] do
|
||||
@@ -640,14 +619,14 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
defp built_in_clause_for(mod, guard, protocol, meta, line) do
|
||||
x = {:x, [line: line, version: -1], __MODULE__}
|
||||
x = quote(line: line, do: x)
|
||||
guard = quote(line: line, do: :erlang.unquote(guard)(unquote(x)))
|
||||
body = load_impl(protocol, mod)
|
||||
{meta, [x], [guard], body}
|
||||
end
|
||||
|
||||
defp struct_clause_for(meta, line) do
|
||||
x = {:x, [line: line, version: -1], __MODULE__}
|
||||
x = quote(line: line, do: x)
|
||||
head = quote(line: line, do: %{__struct__: unquote(x)})
|
||||
guard = quote(line: line, do: :erlang.is_atom(unquote(x)))
|
||||
body = quote(line: line, do: struct_impl_for(unquote(x)))
|
||||
@@ -719,7 +698,7 @@ defmodule Protocol do
|
||||
nil
|
||||
end
|
||||
|
||||
# Disable Dialyzer checks - before and after consolidation
|
||||
# Disable dialyzer checks - before and after consolidation
|
||||
# the types could be more strict
|
||||
@dialyzer {:nowarn_function, __protocol__: 1, impl_for: 1, impl_for!: 1}
|
||||
|
||||
@@ -921,7 +900,7 @@ defmodule Protocol do
|
||||
"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 Protocol module documentation"
|
||||
"\"Consolidation\" section in the documentation for Kernel.defprotocol/2"
|
||||
|
||||
IO.warn(message, Macro.Env.stacktrace(env))
|
||||
end
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
defmodule Range do
|
||||
@moduledoc """
|
||||
Ranges represent a sequence of one or many, ascending
|
||||
or descending, consecutive integers.
|
||||
Defines a range.
|
||||
|
||||
A range represents a sequence of one or many,
|
||||
ascending or descending, consecutive integers.
|
||||
|
||||
Ranges can be either increasing (`first <= last`) or
|
||||
decreasing (`first > last`). Ranges are also always
|
||||
@@ -47,12 +49,6 @@ defmodule Range do
|
||||
|
||||
@doc """
|
||||
Creates a new range.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Range.new(-100, 100)
|
||||
-100..100
|
||||
|
||||
"""
|
||||
@spec new(integer, integer) :: t
|
||||
def new(first, last) when is_integer(first) and is_integer(last) do
|
||||
|
||||
+57
-75
@@ -149,11 +149,12 @@ defmodule Record do
|
||||
|
||||
## Examples
|
||||
|
||||
Record.is_record({User, "john", 27})
|
||||
#=> true
|
||||
|
||||
Record.is_record({})
|
||||
#=> false
|
||||
iex> record = {User, "john", 27}
|
||||
iex> Record.is_record(record)
|
||||
true
|
||||
iex> tuple = {}
|
||||
iex> Record.is_record(tuple)
|
||||
false
|
||||
|
||||
"""
|
||||
defguard is_record(data)
|
||||
@@ -240,8 +241,8 @@ defmodule Record do
|
||||
functions for defaults.
|
||||
|
||||
Record.defrecord(:my_rec, Record.extract(...))
|
||||
** (ArgumentError) invalid value for record field fun_field,
|
||||
cannot escape #Function<12.90072148/2 in :erl_eval.expr/5>.
|
||||
#=> ** (ArgumentError) invalid value for record field fun_field,
|
||||
#=> cannot escape #Function<12.90072148/2 in :erl_eval.expr/5>.
|
||||
|
||||
To work around this error, redefine the field with your own &M.f/a function,
|
||||
like so:
|
||||
@@ -255,11 +256,20 @@ defmodule Record do
|
||||
"""
|
||||
defmacro defrecord(name, tag \\ nil, kv) do
|
||||
quote bind_quoted: [name: name, tag: tag, kv: kv] do
|
||||
fields = Record.__fields__(:defrecord, kv)
|
||||
Record.__validate__(__MODULE__, name, fields)
|
||||
defined_arity =
|
||||
Enum.find(0..2, fn arity ->
|
||||
Module.defines?(__MODULE__, {name, arity})
|
||||
end)
|
||||
|
||||
if defined_arity do
|
||||
raise ArgumentError,
|
||||
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
|
||||
end
|
||||
|
||||
tag = tag || name
|
||||
|
||||
fields = Record.__fields__(:defrecord, kv)
|
||||
|
||||
defmacro unquote(name)(args \\ []) do
|
||||
Record.__access__(unquote(tag), unquote(fields), args, __CALLER__)
|
||||
end
|
||||
@@ -275,11 +285,20 @@ defmodule Record do
|
||||
"""
|
||||
defmacro defrecordp(name, tag \\ nil, kv) do
|
||||
quote bind_quoted: [name: name, tag: tag, kv: kv] do
|
||||
fields = Record.__fields__(:defrecordp, kv)
|
||||
Record.__validate__(__MODULE__, name, fields)
|
||||
defined_arity =
|
||||
Enum.find(0..2, fn arity ->
|
||||
Module.defines?(__MODULE__, {name, arity})
|
||||
end)
|
||||
|
||||
if defined_arity do
|
||||
raise ArgumentError,
|
||||
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
|
||||
end
|
||||
|
||||
tag = tag || name
|
||||
|
||||
fields = Record.__fields__(:defrecordp, kv)
|
||||
|
||||
defmacrop unquote(name)(args \\ []) do
|
||||
Record.__access__(unquote(tag), unquote(fields), args, __CALLER__)
|
||||
end
|
||||
@@ -290,38 +309,6 @@ defmodule Record do
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def __validate__(module, name, fields) do
|
||||
error_on_duplicate_record(module, name)
|
||||
# TODO: Make it raise on v2.0
|
||||
warn_on_duplicate_key(:lists.keysort(1, fields))
|
||||
end
|
||||
|
||||
defp error_on_duplicate_record(module, name) do
|
||||
defined_arity =
|
||||
Enum.find(0..2, fn arity ->
|
||||
Module.defines?(module, {name, arity})
|
||||
end)
|
||||
|
||||
if defined_arity do
|
||||
raise ArgumentError,
|
||||
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
|
||||
end
|
||||
end
|
||||
|
||||
defp warn_on_duplicate_key([]) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp warn_on_duplicate_key([{key, _} | [{key, _} | _] = rest]) do
|
||||
IO.warn("duplicate key #{inspect(key)} found in record")
|
||||
warn_on_duplicate_key(rest)
|
||||
end
|
||||
|
||||
defp warn_on_duplicate_key([_ | rest]) do
|
||||
warn_on_duplicate_key(rest)
|
||||
end
|
||||
|
||||
# Normalizes of record fields to have default values.
|
||||
@doc false
|
||||
def __fields__(type, fields) do
|
||||
@@ -401,7 +388,6 @@ defmodule Record do
|
||||
# Using {} here is safe, since it's not valid AST
|
||||
default = if Macro.Env.in_match?(caller), do: {:_, [], nil}, else: {}
|
||||
{default, keyword} = Keyword.pop(keyword, :_, default)
|
||||
{keyword, exprs} = hoist_expressions(keyword, caller)
|
||||
|
||||
{elements, remaining} =
|
||||
Enum.map_reduce(fields, keyword, fn {key, field_default}, remaining ->
|
||||
@@ -414,7 +400,6 @@ defmodule Record do
|
||||
case remaining do
|
||||
[] ->
|
||||
quote(do: {unquote(tag), unquote_splicing(elements)})
|
||||
|> maybe_prepend_reversed_exprs(exprs)
|
||||
|
||||
[{key, _} | _] ->
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
@@ -427,45 +412,27 @@ defmodule Record do
|
||||
raise ArgumentError, "cannot invoke update style macro inside match"
|
||||
end
|
||||
|
||||
{keyword, exprs} = hoist_expressions(keyword, caller)
|
||||
|
||||
if Keyword.has_key?(keyword, :_) do
|
||||
message = "updating a record with a default (:_) is equivalent to creating a new record"
|
||||
IO.warn(message, Macro.Env.stacktrace(caller))
|
||||
create(tag, fields, keyword, caller)
|
||||
else
|
||||
updates =
|
||||
Enum.map(keyword, fn {key, value} ->
|
||||
if index = find_index(fields, key, 2) do
|
||||
{index, value}
|
||||
else
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
end
|
||||
end)
|
||||
case build_updates(keyword, fields, [], [], []) do
|
||||
{updates, [], []} ->
|
||||
build_update(updates, var)
|
||||
|
||||
build_update(updates, var) |> maybe_prepend_reversed_exprs(exprs)
|
||||
{updates, vars, exprs} ->
|
||||
quote do
|
||||
{unquote_splicing(:lists.reverse(vars))} = {unquote_splicing(:lists.reverse(exprs))}
|
||||
unquote(build_update(updates, var))
|
||||
end
|
||||
|
||||
{:error, key} ->
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp hoist_expressions(keyword, %{context: nil}) do
|
||||
Enum.map_reduce(keyword, [], fn {key, expr}, acc ->
|
||||
if simple_argument?(expr) do
|
||||
{{key, expr}, acc}
|
||||
else
|
||||
var = Macro.var(key, __MODULE__)
|
||||
{{key, var}, [{:=, [], [var, expr]} | acc]}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp hoist_expressions(keyword, _), do: {keyword, []}
|
||||
|
||||
defp maybe_prepend_reversed_exprs(expr, []),
|
||||
do: expr
|
||||
|
||||
defp maybe_prepend_reversed_exprs(expr, exprs),
|
||||
do: {:__block__, [], :lists.reverse([expr | exprs])}
|
||||
|
||||
defp build_update(updates, initial) do
|
||||
updates
|
||||
|> Enum.sort(fn {left, _}, {right, _} -> right <= left end)
|
||||
@@ -474,6 +441,21 @@ defmodule Record do
|
||||
end)
|
||||
end
|
||||
|
||||
defp build_updates([{key, value} | rest], fields, updates, vars, exprs) do
|
||||
if index = find_index(fields, key, 2) do
|
||||
if simple_argument?(value) do
|
||||
build_updates(rest, fields, [{index, value} | updates], vars, exprs)
|
||||
else
|
||||
var = Macro.var(key, __MODULE__)
|
||||
build_updates(rest, fields, [{index, var} | updates], [var | vars], [value | exprs])
|
||||
end
|
||||
else
|
||||
{:error, key}
|
||||
end
|
||||
end
|
||||
|
||||
defp build_updates([], _fields, updates, vars, exprs), do: {updates, vars, exprs}
|
||||
|
||||
defp simple_argument?({name, _, ctx}) when is_atom(name) and is_atom(ctx), do: true
|
||||
defp simple_argument?(other), do: Macro.quoted_literal?(other)
|
||||
|
||||
|
||||
+28
-28
@@ -16,14 +16,13 @@ defmodule Regex do
|
||||
~r/foo/iu
|
||||
|
||||
Regular expressions created via sigils are pre-compiled and stored
|
||||
in the `.beam` file. Note that this may be a problem if you are precompiling
|
||||
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 that all of the structs fields are private. There is
|
||||
also not guarantee two regular expressions from the same source are
|
||||
equal, for example:
|
||||
Keep in mind it is not guaranteed two regular expressions from the
|
||||
same source are equal, for example:
|
||||
|
||||
~r/(?<foo>.)(?<bar>.)/ == ~r/(?<foo>.)(?<bar>.)/
|
||||
|
||||
@@ -38,10 +37,9 @@ defmodule Regex do
|
||||
|
||||
The modifiers available when creating a Regex are:
|
||||
|
||||
* `unicode` (u) - enables Unicode specific patterns like `\p` and causes
|
||||
character classes like `\w`, `\W`, `\s`, etc. to also match on Unicode
|
||||
(see examples below in "Character classes"). It expects valid Unicode
|
||||
strings to be given on match
|
||||
* `unicode` (u) - enables Unicode specific patterns like `\p` and change
|
||||
modifiers like `\w`, `\W`, `\s` and friends to also match on Unicode.
|
||||
It expects valid Unicode strings to be given on match
|
||||
|
||||
* `caseless` (i) - adds case insensitivity
|
||||
|
||||
@@ -88,8 +86,7 @@ defmodule Regex do
|
||||
|
||||
* `:none` - does not return matching subpatterns at all
|
||||
|
||||
* `:all_names` - captures all named subpattern matches in the Regex as a list
|
||||
ordered **alphabetically** by the names of the subpatterns
|
||||
* `:all_names` - captures all names in the Regex
|
||||
|
||||
* `list(binary)` - a list of named captures to capture
|
||||
|
||||
@@ -127,10 +124,6 @@ defmodule Regex do
|
||||
false
|
||||
iex> String.match?("josé", ~r/^[[:lower:]]+$/u)
|
||||
true
|
||||
iex> Regex.replace(~r/\s/, "Unicode\u00A0spaces", "-")
|
||||
"Unicode spaces"
|
||||
iex> Regex.replace(~r/\s/u, "Unicode\u00A0spaces", "-")
|
||||
"Unicode-spaces"
|
||||
|
||||
## Precompilation
|
||||
|
||||
@@ -140,10 +133,10 @@ defmodule Regex do
|
||||
shared during development is compiled on the target (such as dependencies,
|
||||
archives, and escripts) and, when running in production, the code must either
|
||||
be compiled on the target (via `mix compile` or similar) or released on the
|
||||
host (via `mix releases` or similar) with a matching OTP, operating system
|
||||
and architecture as the target.
|
||||
host (via `mix releases` or similar) with a matching OTP, OS and architecture
|
||||
as as the target.
|
||||
|
||||
If you know you are running on a different system than the current one and
|
||||
If you know you are running on a different system that the current one and
|
||||
you are doing multiple matches with the regex, you can manually invoke
|
||||
`Regex.recompile/1` or `Regex.recompile!/1` to perform a runtime version
|
||||
check and recompile the regex if necessary.
|
||||
@@ -224,7 +217,7 @@ defmodule Regex do
|
||||
and recompiles the regex in case of version mismatch.
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec recompile(t) :: {:ok, t} | {:error, any}
|
||||
@spec recompile(t) :: t
|
||||
def recompile(%Regex{} = regex) do
|
||||
version = version()
|
||||
|
||||
@@ -279,9 +272,17 @@ defmodule Regex do
|
||||
@doc """
|
||||
Returns `true` if the given `term` is a regex.
|
||||
Otherwise returns `false`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Regex.regex?(~r/foo/)
|
||||
true
|
||||
|
||||
iex> Regex.regex?(0)
|
||||
false
|
||||
|
||||
"""
|
||||
# TODO: deprecate permanently on Elixir v1.15
|
||||
@doc deprecated: "Use Kernel.is_struct/2 or pattern match on %Regex{} instead"
|
||||
@spec regex?(any) :: boolean
|
||||
def regex?(term)
|
||||
def regex?(%Regex{}), do: true
|
||||
def regex?(_), do: false
|
||||
@@ -292,7 +293,7 @@ defmodule Regex do
|
||||
|
||||
## Options
|
||||
|
||||
* `:return` - when set to `:index`, returns byte index and match length.
|
||||
* `:return` - set to `:index` to return byte index and match length.
|
||||
Defaults to `:binary`.
|
||||
* `:capture` - what to capture in the result. Check the moduledoc for `Regex`
|
||||
to see the possible capture values.
|
||||
@@ -328,7 +329,7 @@ defmodule Regex do
|
||||
|
||||
## Options
|
||||
|
||||
* `:return` - when set to `:index`, returns byte index and match length.
|
||||
* `:return` - set to `:index` to return byte index and match length.
|
||||
Defaults to `:binary`.
|
||||
|
||||
## Examples
|
||||
@@ -421,7 +422,7 @@ defmodule Regex do
|
||||
|
||||
## Options
|
||||
|
||||
* `:return` - when set to `:index`, returns byte index and match length.
|
||||
* `:return` - set to `:index` to return byte index and match length.
|
||||
Defaults to `:binary`.
|
||||
* `:capture` - what to capture in the result. Check the moduledoc for `Regex`
|
||||
to see the possible capture values.
|
||||
@@ -489,8 +490,7 @@ defmodule Regex do
|
||||
affect the splitting process.
|
||||
|
||||
* `:include_captures` - when `true`, includes in the result the matches of
|
||||
the regular expression. The matches are not counted towards the maximum
|
||||
number of parts if combined with the `:parts` option. Defaults to `false`.
|
||||
the regular expression. Defaults to `false`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -757,12 +757,12 @@ defmodule Regex do
|
||||
end
|
||||
end
|
||||
|
||||
defp get_index(_string, {pos, _length}) when pos < 0 do
|
||||
defp get_index(_string, {pos, _len}) when pos < 0 do
|
||||
""
|
||||
end
|
||||
|
||||
defp get_index(string, {pos, length}) do
|
||||
<<_::size(pos)-binary, res::size(length)-binary, _::binary>> = string
|
||||
defp get_index(string, {pos, len}) do
|
||||
<<_::size(pos)-binary, res::size(len)-binary, _::binary>> = string
|
||||
res
|
||||
end
|
||||
|
||||
|
||||
+36
-73
@@ -3,7 +3,7 @@ defmodule Registry do
|
||||
A local, decentralized and scalable key-value process storage.
|
||||
|
||||
It allows developers to lookup one or more processes with a given key.
|
||||
If the registry has `:unique` keys, a key points to 0 or 1 process.
|
||||
If the registry has `:unique` keys, a key points to 0 or 1 processes.
|
||||
If the registry allows `:duplicate` keys, a single key may point to any
|
||||
number of processes. In both cases, different keys could identify the
|
||||
same process.
|
||||
@@ -198,25 +198,17 @@ defmodule Registry do
|
||||
@type match_pattern :: atom | term
|
||||
|
||||
@typedoc "A guard to be evaluated when matching on objects in a registry"
|
||||
@type guard :: atom | tuple
|
||||
@type guard :: {atom | term}
|
||||
|
||||
@typedoc "A list of guards to be evaluated when matching on objects in a registry"
|
||||
@type guards :: [guard]
|
||||
@type guards :: [guard] | []
|
||||
|
||||
@typedoc "A pattern used to representing the output format part of a match spec"
|
||||
@type body :: [term]
|
||||
@type body :: [atom | tuple]
|
||||
|
||||
@typedoc "A full match spec used when selecting objects in the registry"
|
||||
@type spec :: [{match_pattern, guards, body}]
|
||||
|
||||
@typedoc "Options used for `child_spec/1` and `start_link/1`"
|
||||
@type start_option ::
|
||||
{:keys, keys}
|
||||
| {:name, registry}
|
||||
| {:partitions, pos_integer}
|
||||
| {:listeners, [atom]}
|
||||
| {:meta, [{meta_key, meta_value}]}
|
||||
|
||||
## Via callbacks
|
||||
|
||||
@doc false
|
||||
@@ -261,8 +253,9 @@ defmodule Registry do
|
||||
end
|
||||
|
||||
@doc false
|
||||
def unregister_name({registry, key}), do: unregister(registry, key)
|
||||
def unregister_name({registry, key, _value}), do: unregister(registry, key)
|
||||
def unregister_name({registry, key}) do
|
||||
unregister(registry, key)
|
||||
end
|
||||
|
||||
## Registry API
|
||||
|
||||
@@ -299,7 +292,7 @@ defmodule Registry do
|
||||
|
||||
The registry requires the following keys:
|
||||
|
||||
* `:keys` - chooses if keys are `:unique` or `:duplicate`
|
||||
* `:keys` - choose if keys are `:unique` or `:duplicate`
|
||||
* `:name` - the name of the registry and its tables
|
||||
|
||||
The following keys are optional:
|
||||
@@ -313,7 +306,14 @@ defmodule Registry do
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec start_link([start_option]) :: {:ok, pid} | {:error, term}
|
||||
@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)
|
||||
|
||||
@@ -375,11 +375,10 @@ defmodule Registry do
|
||||
See `Supervisor`.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec child_spec([start_option]) :: Supervisor.child_spec()
|
||||
def child_spec(options) do
|
||||
def child_spec(opts) do
|
||||
%{
|
||||
id: Keyword.get(options, :name, Registry),
|
||||
start: {Registry, :start_link, [options]},
|
||||
id: Keyword.get(opts, :name, Registry),
|
||||
start: {Registry, :start_link, [opts]},
|
||||
type: :supervisor
|
||||
}
|
||||
end
|
||||
@@ -599,8 +598,7 @@ defmodule Registry do
|
||||
Optionally, it is possible to pass a list of guard conditions for more precise matching.
|
||||
Each guard is a tuple, which describes checks that should be passed by assigned part of pattern.
|
||||
For example the `$1 > 1` guard condition would be expressed as the `{:>, :"$1", 1}` tuple.
|
||||
Please note that guard conditions will work only for assigned
|
||||
variables like `:"$1"`, `:"$2"`, and so forth.
|
||||
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.
|
||||
@@ -783,8 +781,7 @@ defmodule Registry do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Unregisters entries for keys matching a pattern associated to the current
|
||||
process in `registry`.
|
||||
Unregister entries for a given key matching a pattern.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -922,7 +919,7 @@ defmodule Registry do
|
||||
key_ets = key_ets || key_ets!(registry, key_partition)
|
||||
{pid_server, pid_ets} = pid_ets || pid_ets!(registry, pid_partition)
|
||||
|
||||
# Note that we write first to the pid_ets table because it will
|
||||
# Notice we write first to the pid_ets table because it will
|
||||
# always be able to do the cleanup. If we register first to the
|
||||
# key one and the process crashes, the key will stay there forever.
|
||||
Process.link(pid_server)
|
||||
@@ -930,13 +927,13 @@ defmodule Registry do
|
||||
counter = System.unique_integer()
|
||||
true = :ets.insert(pid_ets, {self, key, key_ets, counter})
|
||||
|
||||
case register_key(kind, key_ets, key, {key, {self, value}}) do
|
||||
:ok ->
|
||||
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, pid_server}
|
||||
ok
|
||||
|
||||
{:error, {:already_registered, ^self}} = error ->
|
||||
true = :ets.delete_object(pid_ets, {self, key, key_ets, counter})
|
||||
@@ -949,16 +946,16 @@ defmodule Registry do
|
||||
end
|
||||
end
|
||||
|
||||
defp register_key(:duplicate, key_ets, _key, entry) do
|
||||
defp register_key(:duplicate, pid_server, key_ets, _key, entry) do
|
||||
true = :ets.insert(key_ets, entry)
|
||||
:ok
|
||||
{:ok, pid_server}
|
||||
end
|
||||
|
||||
defp register_key(:unique, key_ets, key, entry) do
|
||||
defp register_key(:unique, pid_server, key_ets, key, entry) do
|
||||
if :ets.insert_new(key_ets, entry) do
|
||||
:ok
|
||||
{:ok, pid_server}
|
||||
else
|
||||
# Note that we have to call register_key recursively
|
||||
# Notice we have to call register_key recursively
|
||||
# because we are always at odds of a race condition.
|
||||
case :ets.lookup(key_ets, key) do
|
||||
[{^key, {pid, _}} = current] ->
|
||||
@@ -966,11 +963,11 @@ defmodule Registry do
|
||||
{:error, {:already_registered, pid}}
|
||||
else
|
||||
:ets.delete_object(key_ets, current)
|
||||
register_key(:unique, key_ets, key, entry)
|
||||
register_key(:unique, pid_server, key_ets, key, entry)
|
||||
end
|
||||
|
||||
[] ->
|
||||
register_key(:unique, key_ets, key, entry)
|
||||
register_key(:unique, pid_server, key_ets, key, entry)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1033,34 +1030,6 @@ defmodule Registry do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes registry metadata for the given `key` in `registry`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Registry.start_link(keys: :unique, name: Registry.DeleteMetaTest)
|
||||
iex> Registry.put_meta(Registry.DeleteMetaTest, :custom_key, "custom_value")
|
||||
:ok
|
||||
iex> Registry.meta(Registry.DeleteMetaTest, :custom_key)
|
||||
{:ok, "custom_value"}
|
||||
iex> Registry.delete_meta(Registry.DeleteMetaTest, :custom_key)
|
||||
:ok
|
||||
iex> Registry.meta(Registry.DeleteMetaTest, :custom_key)
|
||||
:error
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec delete_meta(registry, meta_key) :: :ok
|
||||
def delete_meta(registry, key) when is_atom(registry) and (is_atom(key) or is_tuple(key)) do
|
||||
try do
|
||||
:ets.delete(registry, key)
|
||||
:ok
|
||||
catch
|
||||
:error, :badarg ->
|
||||
raise ArgumentError, "unknown registry: #{inspect(registry)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the number of registered keys in a registry.
|
||||
It runs in constant time.
|
||||
@@ -1122,8 +1091,7 @@ defmodule Registry do
|
||||
Optionally, it is possible to pass a list of guard conditions for more precise matching.
|
||||
Each guard is a tuple, which describes checks that should be passed by assigned part of pattern.
|
||||
For example the `$1 > 1` guard condition would be expressed as the `{:>, :"$1", 1}` tuple.
|
||||
Please note that guard conditions will work only for assigned
|
||||
variables like `:"$1"`, `:"$2"`, and so forth.
|
||||
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.
|
||||
|
||||
Zero will be returned if there is no match.
|
||||
@@ -1190,8 +1158,7 @@ defmodule Registry do
|
||||
The second part, the guards, is a list of conditions that allow filtering the results.
|
||||
Each guard is a tuple, which describes checks that should be passed by assigned part of pattern.
|
||||
For example the `$1 > 1` guard condition would be expressed as the `{:>, :"$1", 1}` tuple.
|
||||
Please note that guard conditions will work only for assigned
|
||||
variables like `:"$1"`, `:"$2"`, and so forth.
|
||||
Please note that guard conditions will work only for assigned variables like `:"$1"`, `:"$2"`, etc.
|
||||
|
||||
The third part, the body, is a list of shapes of the returned entries. Like guards, you have access to
|
||||
assigned variables like `:"$1"`, which you can combine with hardcoded values to freely shape entries
|
||||
@@ -1353,14 +1320,10 @@ defmodule Registry.Supervisor 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}
|
||||
|
||||
%{
|
||||
id: pid_partition,
|
||||
start: {Registry.Partition, :start_link, [pid_partition, arg]}
|
||||
}
|
||||
worker(Registry.Partition, [pid_partition, arg], id: pid_partition)
|
||||
end
|
||||
|
||||
Supervisor.init(children, strategy: strategy_for_kind(kind))
|
||||
supervise(children, strategy: strategy_for_kind(kind))
|
||||
end
|
||||
|
||||
# Unique registries have their key partition hashed by key.
|
||||
|
||||
+49
-75
@@ -21,7 +21,7 @@ defmodule Stream do
|
||||
iex> Enum.map(stream, &(&1 + 1))
|
||||
[3, 5, 7]
|
||||
|
||||
Note that we started with a range and then we created a stream that is
|
||||
Notice we started with a range and then we created a stream that is
|
||||
meant to multiply each element in the range by 2. At this point, no
|
||||
computation was done. Only when `Enum.map/2` is called we actually
|
||||
enumerate over each element in the range, multiplying it by 2 and adding 1.
|
||||
@@ -46,7 +46,7 @@ defmodule Stream do
|
||||
6
|
||||
#=> [2, 4, 6]
|
||||
|
||||
Note that we first printed each element in the list, then multiplied each
|
||||
Notice that we first printed each element in the list, then multiplied each
|
||||
element by 2 and finally printed each new value. In this example, the list
|
||||
was enumerated three times. Let's see an example with streams:
|
||||
|
||||
@@ -68,7 +68,7 @@ defmodule Stream do
|
||||
its double. In this example, the list was enumerated just once!
|
||||
|
||||
That's what we meant when we said earlier that streams are composable,
|
||||
lazy enumerables. Note that we could call `Stream.map/2` multiple times,
|
||||
lazy enumerables. Notice we could call `Stream.map/2` multiple times,
|
||||
effectively composing the streams and keeping them lazy. The computations
|
||||
are only performed when you call a function from the `Enum` module.
|
||||
|
||||
@@ -107,7 +107,6 @@ defmodule Stream do
|
||||
@type index :: non_neg_integer
|
||||
|
||||
@type default :: any
|
||||
@type timer :: non_neg_integer | :infinity
|
||||
|
||||
# Require Stream.Reducers and its callbacks
|
||||
require Stream.Reducers, as: R
|
||||
@@ -506,10 +505,8 @@ defmodule Stream do
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
||||
"""
|
||||
@spec interval(timer()) :: Enumerable.t()
|
||||
def interval(n)
|
||||
when is_integer(n) and n >= 0
|
||||
when n == :infinity do
|
||||
@spec interval(non_neg_integer) :: Enumerable.t()
|
||||
def interval(n) when is_integer(n) and n >= 0 do
|
||||
unfold(0, fn count ->
|
||||
Process.sleep(n)
|
||||
{count, count + 1}
|
||||
@@ -790,10 +787,8 @@ defmodule Stream do
|
||||
[0]
|
||||
|
||||
"""
|
||||
@spec timer(timer()) :: Enumerable.t()
|
||||
def timer(n)
|
||||
when is_integer(n) and n >= 0
|
||||
when n == :infinity do
|
||||
@spec timer(non_neg_integer) :: Enumerable.t()
|
||||
def timer(n) when is_integer(n) and n >= 0 do
|
||||
take(interval(n), 1)
|
||||
end
|
||||
|
||||
@@ -801,12 +796,13 @@ defmodule Stream do
|
||||
Transforms an existing stream.
|
||||
|
||||
It expects an accumulator and a function that receives each stream element
|
||||
and an accumulator. It must return a tuple, where the first element is a new
|
||||
stream (often a list) or the atom `:halt`, and the second element is the
|
||||
accumulator to be used by the next element, if any, in both cases.
|
||||
and an accumulator, and must return a tuple containing a new stream
|
||||
(often a list) with the new accumulator or a tuple with `:halt` as first
|
||||
element and the accumulator as second.
|
||||
|
||||
Note: this function is equivalent to `Enum.flat_map_reduce/3`, except this
|
||||
function does not return the accumulator once the stream is processed.
|
||||
Note: this function is similar to `Enum.flat_map_reduce/3` except the
|
||||
latter returns both the flat list and accumulator, while this one returns
|
||||
only the stream.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -814,13 +810,13 @@ defmodule Stream do
|
||||
many of the functions defined in this module. For example, we can implement
|
||||
`Stream.take(enum, n)` as follows:
|
||||
|
||||
iex> enum = 1001..9999
|
||||
iex> enum = 1..100
|
||||
iex> n = 3
|
||||
iex> stream = Stream.transform(enum, 0, fn i, acc ->
|
||||
...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}
|
||||
...> end)
|
||||
iex> Enum.to_list(stream)
|
||||
[1001, 1002, 1003]
|
||||
[1, 2, 3]
|
||||
|
||||
"""
|
||||
@spec transform(Enumerable.t(), acc, fun) :: Enumerable.t()
|
||||
@@ -1260,37 +1256,41 @@ defmodule Stream do
|
||||
|
||||
def cycle(enumerable) do
|
||||
fn acc, fun ->
|
||||
step = &do_cycle_step(&1, &2)
|
||||
cycle = &Enumerable.reduce(enumerable, &1, step)
|
||||
reduce = check_cycle_first_element(cycle)
|
||||
do_cycle(reduce, [], cycle, acc, fun)
|
||||
inner = &do_cycle_each(&1, &2, fun)
|
||||
outer = &Enumerable.reduce(enumerable, &1, inner)
|
||||
reduce = check_cycle_first_element(outer)
|
||||
do_cycle(reduce, outer, acc)
|
||||
end
|
||||
end
|
||||
|
||||
defp do_cycle(reduce, inner_acc, _cycle, {:halt, acc}, _fun) do
|
||||
reduce.({:halt, inner_acc})
|
||||
defp do_cycle(_reduce, _cycle, {:halt, acc}) do
|
||||
{:halted, acc}
|
||||
end
|
||||
|
||||
defp do_cycle(reduce, inner_acc, cycle, {:suspend, acc}, fun) do
|
||||
{:suspended, acc, &do_cycle(reduce, inner_acc, cycle, &1, fun)}
|
||||
defp do_cycle(reduce, cycle, {:suspend, acc}) do
|
||||
{:suspended, acc, &do_cycle(reduce, cycle, &1)}
|
||||
end
|
||||
|
||||
defp do_cycle(reduce, inner_acc, cycle, {:cont, acc}, fun) do
|
||||
case reduce.({:cont, inner_acc}) do
|
||||
{:suspended, [element], new_reduce} ->
|
||||
do_cycle(new_reduce, inner_acc, cycle, fun.(element, acc), fun)
|
||||
defp do_cycle(reduce, cycle, acc) do
|
||||
try do
|
||||
reduce.(acc)
|
||||
catch
|
||||
{:stream_cycle, acc} ->
|
||||
{:halted, acc}
|
||||
else
|
||||
{state, acc} when state in [:done, :halted] ->
|
||||
do_cycle(cycle, cycle, {:cont, acc})
|
||||
|
||||
{_, [element]} ->
|
||||
do_cycle(cycle, [], cycle, fun.(element, acc), fun)
|
||||
|
||||
{_, []} ->
|
||||
do_cycle(cycle, [], cycle, {:cont, acc}, fun)
|
||||
{:suspended, acc, continuation} ->
|
||||
{:suspended, acc, &do_cycle(continuation, cycle, &1)}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_cycle_step(x, acc) do
|
||||
{:suspend, [x | acc]}
|
||||
defp do_cycle_each(x, acc, f) do
|
||||
case f.(x, acc) do
|
||||
{:halt, h} -> throw({:stream_cycle, h})
|
||||
{_, _} = o -> o
|
||||
end
|
||||
end
|
||||
|
||||
defp check_cycle_first_element(reduce) do
|
||||
@@ -1333,9 +1333,9 @@ defmodule Stream do
|
||||
## Examples
|
||||
|
||||
# Although not necessary, let's seed the random algorithm
|
||||
iex> :rand.seed(:exrop, {1, 2, 3})
|
||||
iex> :rand.seed(:exsplus, {1, 2, 3})
|
||||
iex> Stream.repeatedly(&:rand.uniform/0) |> Enum.take(3)
|
||||
[0.7498295129076106, 0.06161655489244533, 0.7924073127680873]
|
||||
[0.40502929729990744, 0.45336720247823126, 0.04094511692041057]
|
||||
|
||||
"""
|
||||
@spec repeatedly((() -> element)) :: Enumerable.t()
|
||||
@@ -1384,21 +1384,6 @@ defmodule Stream do
|
||||
fn file -> File.close(file) end
|
||||
)
|
||||
|
||||
iex> Stream.resource(
|
||||
...> fn ->
|
||||
...> {:ok, pid} = StringIO.open("string")
|
||||
...> pid
|
||||
...> end,
|
||||
...> fn pid ->
|
||||
...> case IO.getn(pid, "", 1) do
|
||||
...> :eof -> {:halt, pid}
|
||||
...> char -> {[char], pid}
|
||||
...> end
|
||||
...> end,
|
||||
...> fn pid -> StringIO.close(pid) end
|
||||
...> ) |> Enum.to_list()
|
||||
["s", "t", "r", "i", "n", "g"]
|
||||
|
||||
"""
|
||||
@spec resource((() -> acc), (acc -> {[element], acc} | {:halt, acc}), (acc -> term)) ::
|
||||
Enumerable.t()
|
||||
@@ -1418,21 +1403,23 @@ defmodule Stream do
|
||||
|
||||
defp do_resource(next_acc, next_fun, {:cont, acc}, fun, after_fun) do
|
||||
try do
|
||||
next_fun.(next_acc)
|
||||
# Optimize the most common cases
|
||||
case next_fun.(next_acc) do
|
||||
{[], next_acc} -> {:opt, {:cont, acc}, next_acc}
|
||||
{[v], next_acc} -> {:opt, fun.(v, acc), next_acc}
|
||||
{_, _} = other -> other
|
||||
end
|
||||
catch
|
||||
kind, reason ->
|
||||
after_fun.(next_acc)
|
||||
:erlang.raise(kind, reason, __STACKTRACE__)
|
||||
else
|
||||
{:opt, acc, next_acc} ->
|
||||
do_resource(next_acc, next_fun, acc, fun, after_fun)
|
||||
|
||||
{:halt, next_acc} ->
|
||||
do_resource(next_acc, next_fun, {:halt, acc}, fun, after_fun)
|
||||
|
||||
{[], next_acc} ->
|
||||
do_resource(next_acc, next_fun, {:cont, acc}, fun, after_fun)
|
||||
|
||||
{[v], next_acc} ->
|
||||
do_element_resource(next_acc, next_fun, acc, fun, after_fun, v)
|
||||
|
||||
{list, next_acc} when is_list(list) ->
|
||||
reduce = &Enumerable.List.reduce(list, &1, fun)
|
||||
do_list_resource(next_acc, next_fun, {:cont, acc}, fun, after_fun, reduce)
|
||||
@@ -1444,19 +1431,6 @@ defmodule Stream do
|
||||
end
|
||||
end
|
||||
|
||||
defp do_element_resource(next_acc, next_fun, acc, fun, after_fun, v) do
|
||||
try do
|
||||
fun.(v, acc)
|
||||
catch
|
||||
kind, reason ->
|
||||
after_fun.(next_acc)
|
||||
:erlang.raise(kind, reason, __STACKTRACE__)
|
||||
else
|
||||
acc ->
|
||||
do_resource(next_acc, next_fun, acc, fun, after_fun)
|
||||
end
|
||||
end
|
||||
|
||||
defp do_list_resource(next_acc, next_fun, acc, fun, after_fun, reduce) do
|
||||
try do
|
||||
reduce.(acc)
|
||||
|
||||
+81
-201
@@ -2,85 +2,25 @@ import Kernel, except: [length: 1]
|
||||
|
||||
defmodule String do
|
||||
@moduledoc ~S"""
|
||||
Strings in Elixir are UTF-8 encoded binaries.
|
||||
|
||||
Strings in Elixir are a sequence of Unicode characters,
|
||||
typically written between double quoted strings, such
|
||||
as `"hello"` and `"héllò"`.
|
||||
|
||||
In case a string must have a double-quote in itself,
|
||||
the double quotes must be escaped with a backslash,
|
||||
for example: `"this is a string with \"double quotes\""`.
|
||||
|
||||
You can concatenate two strings with the `<>/2` operator:
|
||||
|
||||
iex> "hello" <> " " <> "world"
|
||||
"hello world"
|
||||
|
||||
## Interpolation
|
||||
|
||||
Strings in Elixir also support interpolation. This allows
|
||||
you to place some value in the middle of a string by using
|
||||
the `#{}` syntax:
|
||||
|
||||
iex> name = "joe"
|
||||
iex> "hello #{name}"
|
||||
"hello joe"
|
||||
|
||||
Any Elixir expression is valid inside the interpolation.
|
||||
If a string is given, the string is interpolated as is.
|
||||
If any other value is given, Elixir will attempt to convert
|
||||
it to a string using the `String.Chars` protocol. This
|
||||
allows, for example, to output an integer from the interpolation:
|
||||
|
||||
iex> "2 + 2 = #{2 + 2}"
|
||||
"2 + 2 = 4"
|
||||
|
||||
In case the value you want to interpolate cannot be
|
||||
converted to a string, because it doesn't have an human
|
||||
textual representation, a protocol error will be raised.
|
||||
|
||||
## Escape characters
|
||||
|
||||
Besides allowing double-quotes to be escaped with a backslash,
|
||||
strings also support the following escape characters:
|
||||
|
||||
* `\a` - Bell
|
||||
* `\b` - Backspace
|
||||
* `\t` - Horizontal tab
|
||||
* `\n` - Line feed (New lines)
|
||||
* `\v` - Vertical tab
|
||||
* `\f` - Form feed
|
||||
* `\r` - Carriage return
|
||||
* `\e` - Command Escape
|
||||
* `\#` - Returns the `#` character itself, skipping interpolation
|
||||
* `\xNN` - A byte represented by the hexadecimal `NN`
|
||||
* `\uNNNN` - A Unicode code point represented by `NNNN`
|
||||
|
||||
Note it is generally not advised to use `\xNN` in Elixir
|
||||
strings, as introducing an invalid byte sequence would
|
||||
make the string invalid. If you have to introduce a
|
||||
character by its hexadecimal representation, it is best
|
||||
to work with Unicode code points, such as `\uNNNN`. In fact,
|
||||
understanding Unicode code points can be essential when doing
|
||||
low-level manipulations of string, so let's explore them in
|
||||
detail next.
|
||||
A String in Elixir is a UTF-8 encoded binary.
|
||||
|
||||
## Code points and grapheme cluster
|
||||
|
||||
The functions in this module act according to the Unicode
|
||||
Standard, version 12.1.0.
|
||||
Standard, version 11.0.0.
|
||||
|
||||
As per the standard, a code point is a single Unicode Character,
|
||||
which may be represented by one or more bytes.
|
||||
|
||||
For example, although the code point "é" is a single character,
|
||||
its underlying representation uses two bytes:
|
||||
For example, the code point "é" is two bytes:
|
||||
|
||||
iex> byte_size("é")
|
||||
2
|
||||
|
||||
However, this module returns the proper length:
|
||||
|
||||
iex> String.length("é")
|
||||
1
|
||||
iex> byte_size("é")
|
||||
2
|
||||
|
||||
Furthermore, this module also presents the concept of grapheme cluster
|
||||
(from now on referenced as graphemes). Graphemes can consist of multiple
|
||||
@@ -109,8 +49,11 @@ defmodule String do
|
||||
|
||||
In general, the functions in this module rely on the Unicode
|
||||
Standard, but do not contain any of the locale specific behaviour.
|
||||
|
||||
More information about graphemes can be found in the [Unicode
|
||||
Standard Annex #29](https://www.unicode.org/reports/tr29/).
|
||||
The current Elixir version implements Extended Grapheme Cluster
|
||||
algorithm.
|
||||
|
||||
For converting a binary to a different encoding and for Unicode
|
||||
normalization mechanisms, see Erlang's `:unicode` module.
|
||||
@@ -131,7 +74,7 @@ defmodule String do
|
||||
|
||||
* `Kernel.binary_part/3` - retrieves part of the binary
|
||||
* `Kernel.bit_size/1` and `Kernel.byte_size/1` - size related functions
|
||||
* `Kernel.is_bitstring/1` and `Kernel.is_binary/1` - type-check function
|
||||
* `Kernel.is_bitstring/1` and `Kernel.is_binary/1` - type checking function
|
||||
* Plus a number of functions for working with binaries (bytes)
|
||||
in the [`:binary` module](http://www.erlang.org/doc/man/binary.html)
|
||||
|
||||
@@ -193,15 +136,14 @@ defmodule String do
|
||||
|
||||
## Integer code points
|
||||
|
||||
Although code points are represented as integers, this module
|
||||
represents code points in their encoded format as strings.
|
||||
For example:
|
||||
Although code points could be represented as integers, this
|
||||
module represents all code points as strings. For example:
|
||||
|
||||
iex> String.codepoints("olá")
|
||||
["o", "l", "á"]
|
||||
|
||||
There are a couple of ways to retrieve the character code point.
|
||||
One may use the `?` construct:
|
||||
There are a couple of ways to retrieve a character integer
|
||||
code point. One may use the `?` construct:
|
||||
|
||||
iex> ?o
|
||||
111
|
||||
@@ -218,16 +160,9 @@ defmodule String do
|
||||
As we have seen above, code points can be inserted into
|
||||
a string by their hexadecimal code:
|
||||
|
||||
iex> "ol\u00E1"
|
||||
"ol\u0061\u0301" #=>
|
||||
"olá"
|
||||
|
||||
Finally, to convert a String into a list of integer
|
||||
code points, known as "charlists" in Elixir, you can call
|
||||
`String.to_charlist`:
|
||||
|
||||
iex> String.to_charlist("olá")
|
||||
[111, 108, 225]
|
||||
|
||||
## Self-synchronization
|
||||
|
||||
The UTF-8 encoding is self-synchronizing. This means that
|
||||
@@ -245,10 +180,10 @@ defmodule String do
|
||||
responsible to check the validity of the encoding. `String.chunk/2`
|
||||
can be used for breaking a string into valid and invalid parts.
|
||||
|
||||
## Compile binary patterns
|
||||
## Patterns
|
||||
|
||||
Many functions in this module work with patterns. For example,
|
||||
`String.split/3` can split a string into multiple strings given
|
||||
`String.split/2` can split a string into multiple strings given
|
||||
a pattern. This pattern can be a string, a list of strings or
|
||||
a compiled pattern:
|
||||
|
||||
@@ -277,13 +212,13 @@ defmodule String do
|
||||
"""
|
||||
@type t :: binary
|
||||
|
||||
@typedoc "A single Unicode code point encoded in UTF-8. It may be one or more bytes."
|
||||
@typedoc "A UTF-8 code point. It may be one or more bytes."
|
||||
@type codepoint :: t
|
||||
|
||||
@typedoc "Multiple code points that may be perceived as a single character by readers"
|
||||
@type grapheme :: t
|
||||
|
||||
@typedoc "Pattern used in functions like `replace/4` and `split/3`"
|
||||
@typedoc "Pattern used in functions like `replace/3` and `split/2`"
|
||||
@type pattern :: t | [t] | :binary.cp()
|
||||
|
||||
@conditional_mappings [:greek]
|
||||
@@ -374,10 +309,9 @@ defmodule String do
|
||||
@doc ~S"""
|
||||
Divides a string into parts based on a pattern.
|
||||
|
||||
Returns a list of these parts.
|
||||
|
||||
The `pattern` may be a string, a list of strings, a regular expression, or a
|
||||
compiled pattern.
|
||||
Returns a list of these parts. The pattern can
|
||||
be a string, a list of strings, a regular expression,
|
||||
or a compiled pattern.
|
||||
|
||||
The string is split into as many parts as possible by
|
||||
default, but can be controlled via the `:parts` option.
|
||||
@@ -486,18 +420,15 @@ defmodule String do
|
||||
end
|
||||
end
|
||||
|
||||
def split(string, pattern, []) when is_tuple(pattern) or is_binary(string) do
|
||||
:binary.split(string, pattern, [:global])
|
||||
end
|
||||
|
||||
def split(string, pattern, options) when is_binary(string) do
|
||||
parts = Keyword.get(options, :parts, :infinity)
|
||||
trim = Keyword.get(options, :trim, false)
|
||||
|
||||
case {parts, trim} do
|
||||
{:infinity, false} ->
|
||||
:binary.split(string, pattern, [:global])
|
||||
|
||||
_ ->
|
||||
pattern = maybe_compile_pattern(pattern)
|
||||
split_each(string, pattern, trim, parts_to_index(parts))
|
||||
end
|
||||
pattern = maybe_compile_pattern(pattern)
|
||||
split_each(string, pattern, trim, parts_to_index(parts))
|
||||
end
|
||||
|
||||
defp parts_to_index(:infinity), do: 0
|
||||
@@ -652,9 +583,9 @@ defmodule String do
|
||||
|
||||
String.normalize(string1, :nfd) == String.normalize(string2, :nfd)
|
||||
|
||||
If you plan to compare multiple strings, multiple times in a row, you
|
||||
may normalize them upfront and compare them directly to avoid multiple
|
||||
normalization passes.
|
||||
Therefore, if you plan to compare multiple strings, multiple times
|
||||
in a row, you may normalize them upfront and compare them directly
|
||||
to avoid multiple normalization passes.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -680,17 +611,6 @@ defmodule String do
|
||||
Converts all characters in `string` to Unicode normalization
|
||||
form identified by `form`.
|
||||
|
||||
Invalid Unicode codepoints are skipped and the remaining of
|
||||
the string is converted. If you want the algorithm to stop
|
||||
and return on invalid codepoint, use `:unicode.characters_to_nfd_binary/1`,
|
||||
`:unicode.characters_to_nfc_binary/1`, `:unicode.characters_to_nfkd_binary/1`,
|
||||
and `:unicode.characters_to_nfkc_binary/1` instead.
|
||||
|
||||
Normalization forms `:nfkc` and `:nfkd` should not be blindly applied
|
||||
to arbitrary text. Because they erase many formatting distinctions,
|
||||
they will prevent round-trip conversion to and from many legacy
|
||||
character sets.
|
||||
|
||||
## Forms
|
||||
|
||||
The supported forms are:
|
||||
@@ -703,14 +623,6 @@ defmodule String do
|
||||
* `:nfc` - Normalization Form Canonical Composition.
|
||||
Characters are decomposed and then recomposed by canonical equivalence.
|
||||
|
||||
* `:nfkd` - Normalization Form Compatibility Decomposition.
|
||||
Characters are decomposed by compatibility equivalence, and
|
||||
multiple combining characters are arranged in a specific
|
||||
order.
|
||||
|
||||
* `:nfkc` - Normalization Form Compatibility Composition.
|
||||
Characters are decomposed and then recomposed by compatibility equivalence.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> String.normalize("yêṩ", :nfd)
|
||||
@@ -719,40 +631,23 @@ defmodule String do
|
||||
iex> String.normalize("leña", :nfc)
|
||||
"leña"
|
||||
|
||||
iex> String.normalize("fi", :nfkd)
|
||||
"fi"
|
||||
|
||||
iex> String.normalize("fi", :nfkc)
|
||||
"fi"
|
||||
|
||||
"""
|
||||
# TODO: Fully deprecate it on v1.10
|
||||
@doc deprecated:
|
||||
"Use :unicode.characters_to_nfc_binary/1 or :unicode.characters_to_nfd_binary/1 instead"
|
||||
def normalize(string, form)
|
||||
|
||||
def normalize(string, :nfd) do
|
||||
case :unicode.characters_to_nfd_binary(string) do
|
||||
string when is_binary(string) -> string
|
||||
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfd)
|
||||
{:error, bad, rest} -> bad <> normalize(rest, :nfd)
|
||||
end
|
||||
end
|
||||
|
||||
def normalize(string, :nfc) do
|
||||
case :unicode.characters_to_nfc_binary(string) do
|
||||
string when is_binary(string) -> string
|
||||
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfc)
|
||||
end
|
||||
end
|
||||
|
||||
def normalize(string, :nfkd) do
|
||||
case :unicode.characters_to_nfkd_binary(string) do
|
||||
string when is_binary(string) -> string
|
||||
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfkd)
|
||||
end
|
||||
end
|
||||
|
||||
def normalize(string, :nfkc) do
|
||||
case :unicode.characters_to_nfkc_binary(string) do
|
||||
string when is_binary(string) -> string
|
||||
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfkc)
|
||||
{:error, bad, rest} -> bad <> normalize(rest, :nfc)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1316,12 +1211,12 @@ defmodule String do
|
||||
end
|
||||
|
||||
defp pad(kind, string, count, padding) do
|
||||
string_length = length(string)
|
||||
string_len = length(string)
|
||||
|
||||
if string_length >= count do
|
||||
if string_len >= count do
|
||||
string
|
||||
else
|
||||
filler = build_filler(count - string_length, padding, padding, 0, [])
|
||||
filler = build_filler(count - string_len, padding, padding, 0, [])
|
||||
|
||||
case kind do
|
||||
:leading -> [filler | string]
|
||||
@@ -1357,26 +1252,26 @@ defmodule String do
|
||||
|
||||
@doc false
|
||||
@deprecated "Use String.pad_leading/2 instead"
|
||||
def rjust(subject, length) do
|
||||
rjust(subject, length, ?\s)
|
||||
def rjust(subject, len) do
|
||||
rjust(subject, len, ?\s)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use String.pad_leading/3 with a binary padding instead"
|
||||
def rjust(subject, length, pad) when is_integer(pad) and is_integer(length) and length >= 0 do
|
||||
pad(:leading, subject, length, [<<pad::utf8>>])
|
||||
def rjust(subject, len, pad) when is_integer(pad) and is_integer(len) and len >= 0 do
|
||||
pad(:leading, subject, len, [<<pad::utf8>>])
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use String.pad_trailing/2 instead"
|
||||
def ljust(subject, length) do
|
||||
ljust(subject, length, ?\s)
|
||||
def ljust(subject, len) do
|
||||
ljust(subject, len, ?\s)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use String.pad_trailing/3 with a binary padding instead"
|
||||
def ljust(subject, length, pad) when is_integer(pad) and is_integer(length) and length >= 0 do
|
||||
pad(:trailing, subject, length, [<<pad::utf8>>])
|
||||
def ljust(subject, len, pad) when is_integer(pad) and is_integer(len) and len >= 0 do
|
||||
pad(:trailing, subject, len, [<<pad::utf8>>])
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
@@ -1385,8 +1280,7 @@ defmodule String do
|
||||
|
||||
The `subject` is always a string.
|
||||
|
||||
The `pattern` may be a string, a list of strings, a regular expression, or a
|
||||
compiled pattern.
|
||||
The `pattern` may be a string, a regular expression, or a compiled pattern.
|
||||
|
||||
The `replacement` may be a string or a function that receives the matched
|
||||
pattern and must return the replacement as a string or iodata.
|
||||
@@ -1409,7 +1303,7 @@ defmodule String do
|
||||
"a-b,c"
|
||||
|
||||
The pattern may also be a list of strings and the replacement may also
|
||||
be a function that receives the matches:
|
||||
be a function that receives the matched patterns:
|
||||
|
||||
iex> String.replace("a,b,c", ["a", "c"], fn <<char>> -> <<char + 1>> end)
|
||||
"b,b,d"
|
||||
@@ -1421,9 +1315,10 @@ defmodule String do
|
||||
iex> String.replace("a,b,c", ~r/,(.)/, ",\\1\\g{1}")
|
||||
"a,bb,cc"
|
||||
|
||||
Note that we had to escape the backslash escape character (i.e., we used `\\N`
|
||||
Notice we had to escape the backslash escape character (i.e., we used `\\N`
|
||||
instead of just `\N` to escape the backslash; same thing for `\\g{N}`). By
|
||||
giving `\0`, one can inject the whole match in the replacement string.
|
||||
giving `\0`, one can inject the whole matched pattern in the replacement
|
||||
string.
|
||||
|
||||
A compiled pattern can also be given:
|
||||
|
||||
@@ -1445,38 +1340,35 @@ defmodule String do
|
||||
"""
|
||||
@spec replace(t, pattern | Regex.t(), t | (t -> t | iodata), keyword) :: t
|
||||
def replace(subject, pattern, replacement, options \\ [])
|
||||
when is_binary(subject) and
|
||||
(is_binary(replacement) or is_function(replacement, 1)) and
|
||||
is_list(options) do
|
||||
replace_guarded(subject, pattern, replacement, options)
|
||||
end
|
||||
|
||||
defp replace_guarded(subject, %{__struct__: Regex} = regex, replacement, options) do
|
||||
def replace(subject, %{__struct__: Regex} = regex, replacement, options)
|
||||
when is_binary(replacement) or is_function(replacement, 1) do
|
||||
Regex.replace(regex, subject, replacement, options)
|
||||
end
|
||||
|
||||
defp replace_guarded(subject, "", "", _) do
|
||||
def replace(subject, "", "", _) when is_binary(subject) do
|
||||
subject
|
||||
end
|
||||
|
||||
defp replace_guarded(subject, "", replacement_binary, options)
|
||||
when is_binary(replacement_binary) do
|
||||
def replace(subject, "", replacement, options)
|
||||
when is_binary(subject) and is_binary(replacement) do
|
||||
if Keyword.get(options, :global, true) do
|
||||
IO.iodata_to_binary([replacement_binary | intersperse_bin(subject, replacement_binary)])
|
||||
IO.iodata_to_binary([replacement | intersperse_bin(subject, replacement)])
|
||||
else
|
||||
replacement_binary <> subject
|
||||
replacement <> subject
|
||||
end
|
||||
end
|
||||
|
||||
defp replace_guarded(subject, "", replacement_fun, options) do
|
||||
def replace(subject, "", replacement, options)
|
||||
when is_binary(subject) and is_function(replacement, 1) do
|
||||
if Keyword.get(options, :global, true) do
|
||||
IO.iodata_to_binary([replacement_fun.("") | intersperse_fun(subject, replacement_fun)])
|
||||
IO.iodata_to_binary([replacement.("") | intersperse_fun(subject, replacement)])
|
||||
else
|
||||
IO.iodata_to_binary([replacement_fun.("") | subject])
|
||||
IO.iodata_to_binary([replacement.("") | subject])
|
||||
end
|
||||
end
|
||||
|
||||
defp replace_guarded(subject, pattern, replacement, options) do
|
||||
def replace(subject, pattern, replacement, options) when is_binary(subject) do
|
||||
if insert = Keyword.get(options, :insert_replaced) do
|
||||
IO.warn(
|
||||
"String.replace/4 with :insert_replaced option is deprecated. " <>
|
||||
@@ -1596,13 +1488,10 @@ defmodule String do
|
||||
:binary.copy(subject, n)
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Returns a list of code points encoded as strings.
|
||||
@doc """
|
||||
Returns all code points in the string.
|
||||
|
||||
To retrieve code points in their natural integer
|
||||
representation, see `to_charlist/1`. For details about
|
||||
code points and graphemes, see the `String` module
|
||||
documentation.
|
||||
For details about code points and graphemes, see the `String` module documentation.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1804,9 +1693,6 @@ defmodule String do
|
||||
iex> String.next_grapheme("olá")
|
||||
{"o", "lá"}
|
||||
|
||||
iex> String.next_grapheme("")
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec next_grapheme(t) :: {grapheme, t} | nil
|
||||
def next_grapheme(binary) do
|
||||
@@ -1817,9 +1703,9 @@ defmodule String do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the size (in bytes) of the next grapheme.
|
||||
Returns the size of the next grapheme.
|
||||
|
||||
The result is a tuple with the next grapheme size in bytes and
|
||||
The result is a tuple with the next grapheme size and
|
||||
the remainder of the string or `nil` in case the string
|
||||
reached its end.
|
||||
|
||||
@@ -1828,9 +1714,6 @@ defmodule String do
|
||||
iex> String.next_grapheme_size("olá")
|
||||
{1, "lá"}
|
||||
|
||||
iex> String.next_grapheme_size("")
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec next_grapheme_size(t) :: {pos_integer, t} | nil
|
||||
defdelegate next_grapheme_size(string), to: String.Unicode
|
||||
@@ -1847,9 +1730,6 @@ defmodule String do
|
||||
iex> String.first("եոգլի")
|
||||
"ե"
|
||||
|
||||
iex> String.first("")
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec first(t) :: grapheme | nil
|
||||
def first(string) do
|
||||
@@ -1943,7 +1823,8 @@ defmodule String do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a substring starting at the offset `start`, and of the given `length`.
|
||||
Returns a substring starting at the offset `start`, and of
|
||||
length `len`.
|
||||
|
||||
If the offset is greater than string length, then it returns `""`.
|
||||
|
||||
@@ -1984,22 +1865,22 @@ defmodule String do
|
||||
""
|
||||
end
|
||||
|
||||
def slice(string, start, length) when start >= 0 and length >= 0 do
|
||||
def slice(string, start, len) when start >= 0 and len >= 0 do
|
||||
case String.Unicode.split_at(string, start) do
|
||||
{_, nil} ->
|
||||
""
|
||||
|
||||
{start_bytes, rest} ->
|
||||
{len_bytes, _} = String.Unicode.split_at(rest, length)
|
||||
{len_bytes, _} = String.Unicode.split_at(rest, len)
|
||||
binary_part(string, start_bytes, len_bytes)
|
||||
end
|
||||
end
|
||||
|
||||
def slice(string, start, length) when start < 0 and length >= 0 do
|
||||
def slice(string, start, len) when start < 0 and len >= 0 do
|
||||
start = length(string) + start
|
||||
|
||||
case start >= 0 do
|
||||
true -> slice(string, start, length)
|
||||
true -> slice(string, start, len)
|
||||
false -> ""
|
||||
end
|
||||
end
|
||||
@@ -2250,13 +2131,13 @@ defmodule String do
|
||||
For example, take the grapheme "é" which is made of the characters
|
||||
"e" and the acute accent. The following returns `true`:
|
||||
|
||||
iex> String.contains?(String.normalize("é", :nfd), "e")
|
||||
iex> String.contains?(:unicode.characters_to_nfd_binary("é"), "e")
|
||||
true
|
||||
|
||||
However, if "é" is represented by the single character "e with acute"
|
||||
accent, then it will return `false`:
|
||||
|
||||
iex> String.contains?(String.normalize("é", :nfc), "e")
|
||||
iex> String.contains?(:unicode.characters_to_nfc_binary("é"), "e")
|
||||
false
|
||||
|
||||
"""
|
||||
@@ -2369,7 +2250,7 @@ defmodule String do
|
||||
Passing a string that does not represent an integer leads to an error:
|
||||
|
||||
String.to_integer("invalid data")
|
||||
** (ArgumentError) argument error
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec to_integer(String.t()) :: integer
|
||||
@@ -2411,7 +2292,7 @@ defmodule String do
|
||||
3.0
|
||||
|
||||
String.to_float("3")
|
||||
** (ArgumentError) argument error
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec to_float(String.t()) :: float
|
||||
@@ -2603,7 +2484,6 @@ defmodule String do
|
||||
[eq: "fox ", del: "ho", ins: "jum", eq: "ps over the ", del: "dog", ins: "lazy cat"]
|
||||
|
||||
"""
|
||||
@doc since: "1.3.0"
|
||||
@spec myers_difference(t, t) :: [{:eq | :ins | :del, t}]
|
||||
def myers_difference(string1, string2) do
|
||||
graphemes(string1)
|
||||
|
||||
+26
-36
@@ -21,19 +21,14 @@ defmodule StringIO do
|
||||
`string` will be the initial input of the newly created
|
||||
device.
|
||||
|
||||
If the `:capture_prompt` option is set to `true`,
|
||||
prompts (specified as arguments to `IO.get*` functions)
|
||||
are captured in the output.
|
||||
|
||||
The device will be created and sent to the function given.
|
||||
When the function returns, the device will be closed. The final
|
||||
result will be a tuple with `:ok` and the result of the function.
|
||||
|
||||
## Options
|
||||
|
||||
* `:capture_prompt` - if set to `true`, prompts (specified as
|
||||
arguments to `IO.get*` functions) are captured in the output.
|
||||
Defaults to `false`.
|
||||
|
||||
* `:encoding` (since v1.10.0) - encoding of the IO device. Allowed
|
||||
values are `:unicode` (default) and `:latin1`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> StringIO.open("foo", [], fn pid ->
|
||||
@@ -174,8 +169,7 @@ defmodule StringIO do
|
||||
@impl true
|
||||
def init({string, options}) do
|
||||
capture_prompt = options[:capture_prompt] || false
|
||||
encoding = options[:encoding] || :unicode
|
||||
{:ok, %{encoding: encoding, input: string, output: "", capture_prompt: capture_prompt}}
|
||||
{:ok, %{input: string, output: "", capture_prompt: capture_prompt}}
|
||||
end
|
||||
|
||||
@impl true
|
||||
@@ -203,7 +197,7 @@ defmodule StringIO do
|
||||
|
||||
defp io_request(from, reply_as, req, state) do
|
||||
{reply, state} = io_request(req, state)
|
||||
io_reply(from, reply_as, reply)
|
||||
io_reply(from, reply_as, to_reply(reply))
|
||||
state
|
||||
end
|
||||
|
||||
@@ -251,16 +245,12 @@ defmodule StringIO do
|
||||
get_line(encoding, "", state)
|
||||
end
|
||||
|
||||
defp io_request({:setopts, [encoding: encoding]}, state) when encoding in [:latin1, :unicode] do
|
||||
{:ok, %{state | encoding: encoding}}
|
||||
end
|
||||
|
||||
defp io_request({:setopts, _opts}, state) do
|
||||
{{:error, :enotsup}, state}
|
||||
end
|
||||
|
||||
defp io_request(:getopts, state) do
|
||||
{[binary: true, encoding: state.encoding], state}
|
||||
{{:ok, [binary: true, encoding: :unicode]}, state}
|
||||
end
|
||||
|
||||
defp io_request({:get_geometry, :columns}, state) do
|
||||
@@ -281,10 +271,10 @@ defmodule StringIO do
|
||||
|
||||
## put_chars
|
||||
|
||||
defp put_chars(encoding, chars, req, state) do
|
||||
case :unicode.characters_to_binary(chars, encoding, state.encoding) do
|
||||
defp put_chars(encoding, chars, req, %{output: output} = state) do
|
||||
case :unicode.characters_to_binary(chars, encoding, :unicode) do
|
||||
string when is_binary(string) ->
|
||||
{:ok, %{state | output: state.output <> string}}
|
||||
{:ok, %{state | output: output <> string}}
|
||||
|
||||
{_, _, _} ->
|
||||
{{:error, req}, state}
|
||||
@@ -318,25 +308,22 @@ defmodule StringIO do
|
||||
{chars, rest}
|
||||
end
|
||||
|
||||
defp get_chars(input, :unicode, count) do
|
||||
with {:ok, count} <- split_at(input, count, 0) do
|
||||
<<chars::binary-size(count), rest::binary>> = input
|
||||
{chars, rest}
|
||||
defp get_chars(input, encoding, count) do
|
||||
try do
|
||||
case :file_io_server.count_and_find(input, count, encoding) do
|
||||
{buf_count, split_pos} when buf_count < count or split_pos == :none ->
|
||||
{input, ""}
|
||||
|
||||
{_buf_count, split_pos} ->
|
||||
<<chars::binary-size(split_pos), rest::binary>> = input
|
||||
{chars, rest}
|
||||
end
|
||||
catch
|
||||
:exit, :invalid_unicode ->
|
||||
{:error, :invalid_unicode}
|
||||
end
|
||||
end
|
||||
|
||||
defp split_at(_, 0, acc),
|
||||
do: {:ok, acc}
|
||||
|
||||
defp split_at(<<h::utf8, t::binary>>, count, acc),
|
||||
do: split_at(t, count - 1, acc + byte_size(<<h::utf8>>))
|
||||
|
||||
defp split_at(<<_, _::binary>>, _count, _acc),
|
||||
do: {:error, :invalid_unicode}
|
||||
|
||||
defp split_at(<<>>, _count, acc),
|
||||
do: {:ok, acc}
|
||||
|
||||
## get_line
|
||||
|
||||
defp get_line(encoding, prompt, %{input: input} = state) do
|
||||
@@ -458,4 +445,7 @@ defmodule StringIO do
|
||||
defp io_reply(from, reply_as, reply) do
|
||||
send(from, {:io_reply, reply_as, reply})
|
||||
end
|
||||
|
||||
defp to_reply(list) when is_list(list), do: IO.chardata_to_string(list)
|
||||
defp to_reply(other), do: other
|
||||
end
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user