Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||
-50
@@ -1,50 +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 13.0
|
||||
alias: FreeBSD Stable
|
||||
|
||||
freebsd_instance:
|
||||
image_family: freebsd-13-0
|
||||
cpu: 8
|
||||
memory: 7424Mi
|
||||
|
||||
env:
|
||||
CHECK_REPRODUCIBLE: true
|
||||
LC_ALL: en_US.UTF-8
|
||||
PATH: $PATH:/usr/local/lib/erlang24/bin
|
||||
|
||||
install_script:
|
||||
- pkg install -y erlang-runtime24 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
|
||||
+3
-5
@@ -1,10 +1,9 @@
|
||||
[
|
||||
inputs: [
|
||||
"lib/*/{lib,unicode,test}/**/*.{ex,exs}",
|
||||
"lib/*/*.exs",
|
||||
"lib/ex_unit/examples/*.exs",
|
||||
".formatter.exs"
|
||||
"lib/*/mix.exs"
|
||||
],
|
||||
|
||||
locals_without_parens: [
|
||||
# Formatter tests
|
||||
assert_format: 2,
|
||||
@@ -14,6 +13,5 @@
|
||||
|
||||
# Errors tests
|
||||
assert_eval_raise: 3
|
||||
],
|
||||
normalize_bitstring_modifiers: false
|
||||
]
|
||||
]
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
lib/elixir/test/elixir/fixtures/*.txt text eol=lf
|
||||
*.ex diff=elixir
|
||||
*.exs diff=elixir
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
blank_issues_enabled: true
|
||||
|
||||
contact_links:
|
||||
- name: Discuss proposals
|
||||
url: https://groups.google.com/g/elixir-lang-core
|
||||
about: Send proposals for new ideas to our mailing list
|
||||
|
||||
- name: Ask questions and support
|
||||
url: https://elixirforum.com/
|
||||
about: Ask questions, provide support and more on Elixir Forum
|
||||
@@ -1,53 +0,0 @@
|
||||
---
|
||||
name: Report an issue
|
||||
description:
|
||||
Tell us about something that is not working the way we (probably) intend
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: >
|
||||
Thank you for contributing to Elixir! :heart:
|
||||
|
||||
|
||||
Please, do not use this form for guidance, questions or support.
|
||||
Try instead in [Elixir Forum](https://elixirforum.com),
|
||||
the [IRC Chat](https://web.libera.chat/#elixir),
|
||||
[Stack Overflow](https://stackoverflow.com/questions/tagged/elixir),
|
||||
[Slack](https://elixir-slackin.herokuapp.com),
|
||||
[Discord](https://discord.gg/elixir) or in other online communities.
|
||||
|
||||
- type: textarea
|
||||
id: elixir-and-otp-version
|
||||
attributes:
|
||||
label: Elixir and Erlang/OTP versions
|
||||
description: Paste the output of `elixir --version` here.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating system
|
||||
description: The operating system that this issue is happening on.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: current-behavior
|
||||
attributes:
|
||||
label: Current behavior
|
||||
description: >
|
||||
Include code samples, errors, and stacktraces if appropriate.
|
||||
|
||||
|
||||
If reporting a bug, please include the reproducing steps.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected-behavior
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
description: A short description on how you expect the code to behave.
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,6 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -1,87 +0,0 @@
|
||||
name: builds.hex.pm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- v*.*
|
||||
tags:
|
||||
- v*
|
||||
|
||||
env:
|
||||
ELIXIR_OPTS: "--warnings-as-errors"
|
||||
ERLC_OPTS: "warnings_as_errors"
|
||||
LANG: C.UTF-8
|
||||
|
||||
concurrency: builds_txt
|
||||
|
||||
jobs:
|
||||
release_pre_built:
|
||||
strategy:
|
||||
fail-fast: true
|
||||
max-parallel: 1
|
||||
matrix:
|
||||
include:
|
||||
- otp: 25
|
||||
otp_version: '25.3'
|
||||
build_docs: build_docs
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin
|
||||
- uses: ./.github/workflows/release_pre_built
|
||||
with:
|
||||
otp_version: ${{ matrix.otp_version }}
|
||||
otp: ${{ matrix.otp }}
|
||||
build_docs: ${{ matrix.build_docs }}
|
||||
- name: Utils.sh
|
||||
run: |
|
||||
cat << 'EOF' > utils.sh
|
||||
function purge_key() {
|
||||
curl \
|
||||
-X POST \
|
||||
-H "Fastly-Key: ${FASTLY_KEY}" \
|
||||
-H "Accept: application/json" \
|
||||
-H "Content-Length: 0" \
|
||||
"https://api.fastly.com/service/$1/purge/$2"
|
||||
}
|
||||
function purge() {
|
||||
purge_key ${FASTLY_REPO_SERVICE_ID} $1
|
||||
purge_key ${FASTLY_BUILDS_SERVICE_ID} $1
|
||||
sleep 2
|
||||
purge_key ${FASTLY_REPO_SERVICE_ID} $1
|
||||
purge_key ${FASTLY_BUILDS_SERVICE_ID} $1
|
||||
sleep 2
|
||||
purge_key ${FASTLY_REPO_SERVICE_ID} $1
|
||||
purge_key ${FASTLY_BUILDS_SERVICE_ID} $1
|
||||
}
|
||||
EOF
|
||||
chmod +x utils.sh
|
||||
- name: Upload Docs to S3
|
||||
if: ${{ matrix.build_docs }}
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.HEX_AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.HEX_AWS_SECRET_ACCESS_KEY }}
|
||||
AWS_REGION: ${{ secrets.HEX_AWS_REGION }}
|
||||
AWS_S3_BUCKET: ${{ secrets.HEX_AWS_S3_BUCKET }}
|
||||
FASTLY_REPO_SERVICE_ID: ${{ secrets.HEX_FASTLY_REPO_SERVICE_ID }}
|
||||
FASTLY_BUILDS_SERVICE_ID: ${{ secrets.HEX_FASTLY_BUILDS_SERVICE_ID }}
|
||||
FASTLY_KEY: ${{ secrets.HEX_FASTLY_KEY }}
|
||||
run: |
|
||||
source utils.sh
|
||||
version=$(echo ${{ github.ref_name }} | sed -e 's/^v//g')
|
||||
for f in doc/*; do
|
||||
if [ -d "$f" ]; then
|
||||
app=`echo $f | sed s/"doc\/"//`
|
||||
tarball="${app}-${version}.tar.gz"
|
||||
surrogate_key="docs/${app}-${version}"
|
||||
tar -czf "${tarball}" -C "doc/${app}" .
|
||||
aws s3 cp "${tarball}" "s3://${{ env.AWS_S3_BUCKET }}/docs/${tarball}" \
|
||||
--cache-control "public,max-age=3600" \
|
||||
--metadata "{\"surrogate-key\":\"${surrogate_key}\",\"surrogate-control\":\"public,max-age=604800\"}"
|
||||
purge "${surrogate_key}"
|
||||
fi
|
||||
done
|
||||
@@ -1,129 +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
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test_linux:
|
||||
name: Linux, ${{ matrix.otp_release }}, Ubuntu 20.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- otp_release: OTP-25.0
|
||||
otp_latest: true
|
||||
- otp_release: OTP-24.3
|
||||
- otp_release: OTP-24.0
|
||||
- otp_release: OTP-23.3
|
||||
- otp_release: OTP-23.0
|
||||
- otp_release: master
|
||||
development: true
|
||||
- otp_release: maint
|
||||
development: true
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Install Erlang/OTP
|
||||
run: |
|
||||
cd $RUNNER_TEMP
|
||||
wget -O otp.tar.gz https://repo.hex.pm/builds/otp/ubuntu-20.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 "$(pwd)/otp/bin" >> $GITHUB_PATH
|
||||
- name: Compile Elixir
|
||||
run: |
|
||||
rm -rf .git
|
||||
make compile
|
||||
echo "$PWD/bin" >> $GITHUB_PATH
|
||||
- name: Build info
|
||||
run: bin/elixir --version
|
||||
- name: Check format
|
||||
run: make test_formatted && echo "All Elixir source code files are properly formatted."
|
||||
- name: Run Dialyzer
|
||||
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
|
||||
continue-on-error: ${{ matrix.development }}
|
||||
- name: Elixir test suite
|
||||
run: make test_elixir
|
||||
continue-on-error: ${{ matrix.development }}
|
||||
- name: Check reproducible builds
|
||||
run: taskset 1 make check_reproducible
|
||||
if: ${{ matrix.otp_latest }}
|
||||
- name: Build docs
|
||||
if: ${{ matrix.otp_latest }}
|
||||
run: |
|
||||
git config --global advice.detachedHead false
|
||||
EX_DOC_LATEST_STABLE_VERSION=$(curl -s https://hex.pm/api/packages/ex_doc | jq --raw-output '.latest_stable_version')
|
||||
for branch in main v${EX_DOC_LATEST_STABLE_VERSION}; do
|
||||
echo "Building docs with ExDoc ${branch}"
|
||||
cd ..
|
||||
git clone https://github.com/elixir-lang/ex_doc.git --branch ${branch} --depth 1
|
||||
cd ex_doc
|
||||
../elixir/bin/mix do local.rebar --force + local.hex --force + deps.get + compile
|
||||
cd ../elixir/
|
||||
make docs
|
||||
rm -rf ../ex_doc/
|
||||
done
|
||||
|
||||
test_windows:
|
||||
name: Windows, OTP-${{ matrix.otp_release }}, Windows Server 2019
|
||||
strategy:
|
||||
matrix:
|
||||
otp_release: ['23.3']
|
||||
runs-on: windows-2019
|
||||
steps:
|
||||
- name: Configure Git
|
||||
run: git config --global core.autocrlf input
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Cache Erlang/OTP package
|
||||
uses: actions/cache@v3
|
||||
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: |
|
||||
del c:/Windows/System32/drivers/etc/hosts
|
||||
make --keep-going test_elixir
|
||||
|
||||
check_posix_compliant:
|
||||
name: Check POSIX-compliant
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
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"
|
||||
@@ -1,72 +0,0 @@
|
||||
# #!/usr/bin/env elixir
|
||||
[tag] = System.argv()
|
||||
|
||||
Mix.install([
|
||||
{:req, "~> 0.2.1"},
|
||||
{:jason, "~> 1.0"}
|
||||
])
|
||||
|
||||
%{status: 200, body: release} =
|
||||
Req.get!("https://api.github.com/repos/elixir-lang/elixir/releases/tags/#{tag}")
|
||||
|
||||
if release["draft"] do
|
||||
raise "cannot notify a draft release"
|
||||
end
|
||||
|
||||
## Notify on elixir-lang-ann
|
||||
|
||||
names_and_checksums =
|
||||
for asset <- release["assets"],
|
||||
name = asset["name"],
|
||||
name =~ ~r/.sha\d+sum$/,
|
||||
do: {name, Req.get!(asset["browser_download_url"]).body}
|
||||
|
||||
line_items =
|
||||
for {name, checksum_and_name} <- Enum.sort(names_and_checksums) do
|
||||
[checksum | _] = String.split(checksum_and_name, " ")
|
||||
root = Path.rootname(name)
|
||||
"." <> type = Path.extname(name)
|
||||
" * #{root} - #{type} - #{checksum}\n"
|
||||
end
|
||||
|
||||
mail = %{
|
||||
"From" => "jose.valim@dashbit.co",
|
||||
"To" => "elixir-lang-ann@googlegroups.com",
|
||||
"Subject" => "Elixir #{tag} released",
|
||||
"HtmlBody" => "https://github.com/elixir-lang/elixir/releases/tag/#{tag}\n\n#{line_items}",
|
||||
"MessageStream" => "outbound"
|
||||
}
|
||||
|
||||
if System.get_env("DRYRUN") do
|
||||
IO.puts("MAIL")
|
||||
IO.inspect(mail)
|
||||
else
|
||||
headers = %{
|
||||
"X-Postmark-Server-Token" => System.fetch_env!("ELIXIR_LANG_ANN_TOKEN")
|
||||
}
|
||||
|
||||
resp = Req.post!("https://api.postmarkapp.com/email", {:json, mail}, headers: headers)
|
||||
IO.puts("#{resp.status} elixir-lang-ann\n#{inspect(resp.body)}")
|
||||
end
|
||||
|
||||
## Notify on Elixir Forum
|
||||
|
||||
post = %{
|
||||
"title" => "Elixir #{tag} released",
|
||||
"raw" => "https://github.com/elixir-lang/elixir/releases/tag/#{tag}\n\n#{release["body"]}",
|
||||
# Elixir News
|
||||
"category" => 28
|
||||
}
|
||||
|
||||
if System.get_env("DRYRUN") do
|
||||
IO.puts("POST")
|
||||
IO.inspect(post)
|
||||
else
|
||||
headers = %{
|
||||
"api-key" => System.fetch_env!("ELIXIR_FORUM_TOKEN"),
|
||||
"api-username" => "Elixir"
|
||||
}
|
||||
|
||||
resp = Req.post!("https://elixirforum.com/posts.json", {:json, post}, headers: headers)
|
||||
IO.puts("#{resp.status} Elixir Forum\n#{inspect(resp.body)}")
|
||||
end
|
||||
@@ -1,28 +0,0 @@
|
||||
name: Notify
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
runs-on: ubuntu-20.04
|
||||
name: Notify
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- uses: erlef/setup-beam@v1
|
||||
with:
|
||||
otp-version: '25.0'
|
||||
elixir-version: '1.14.0'
|
||||
- name: Run Elixir script
|
||||
env:
|
||||
ELIXIR_FORUM_TOKEN: ${{ secrets.ELIXIR_FORUM_TOKEN }}
|
||||
ELIXIR_LANG_ANN_TOKEN: ${{ secrets.ELIXIR_LANG_ANN_TOKEN }}
|
||||
run: |
|
||||
elixir .github/workflows/notify.exs ${{ github.ref_name }}
|
||||
@@ -1,96 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
env:
|
||||
ELIXIR_OPTS: "--warnings-as-errors"
|
||||
ERLC_OPTS: "warnings_as_errors"
|
||||
LANG: C.UTF-8
|
||||
|
||||
jobs:
|
||||
create_draft_release:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-20.04
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Create draft release
|
||||
run: |
|
||||
gh release create \
|
||||
--repo ${{ github.repository }} \
|
||||
--title ${{ github.ref_name }} \
|
||||
--notes '' \
|
||||
--draft \
|
||||
${{ github.ref_name }}
|
||||
release_pre_built:
|
||||
needs: create_draft_release
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
include:
|
||||
- otp: 23
|
||||
otp_version: 23.3
|
||||
- otp: 24
|
||||
otp_version: 24.3
|
||||
- otp: 25
|
||||
otp_version: 25.0
|
||||
build_docs: build_docs
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- uses: erlef/setup-beam@v1
|
||||
with:
|
||||
otp-version: ${{ matrix.otp_version }}
|
||||
version-type: strict
|
||||
- name: Build Elixir Release
|
||||
run: |
|
||||
make Precompiled.zip
|
||||
mv Precompiled.zip elixir-otp-${{ matrix.otp }}.zip
|
||||
shasum -a 1 elixir-otp-${{ matrix.otp }}.zip > elixir-otp-${{ matrix.otp }}.zip.sha1sum
|
||||
shasum -a 256 elixir-otp-${{ matrix.otp }}.zip > elixir-otp-${{ matrix.otp }}.zip.sha256sum
|
||||
echo "$PWD/bin" >> $GITHUB_PATH
|
||||
- name: Upload Pre-built
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
gh release upload --clobber "${{ github.ref_name }}" \
|
||||
elixir-otp-${{ matrix.otp }}.zip \
|
||||
elixir-otp-${{ matrix.otp }}.zip.sha{1,256}sum
|
||||
- name: Get latest stable ExDoc version
|
||||
if: ${{ matrix.build_docs }}
|
||||
run: |
|
||||
EX_DOC_LATEST_STABLE_VERSION=$(curl -s https://hex.pm/api/packages/ex_doc | jq --raw-output '.latest_stable_version')
|
||||
echo "EX_DOC_LATEST_STABLE_VERSION=${EX_DOC_LATEST_STABLE_VERSION}" >> $GITHUB_ENV
|
||||
- uses: actions/checkout@v3
|
||||
if: ${{ matrix.build_docs }}
|
||||
with:
|
||||
repository: elixir-lang/ex_doc
|
||||
ref: v${{ env.EX_DOC_LATEST_STABLE_VERSION }}
|
||||
path: ex_doc
|
||||
- name: Build ex_doc
|
||||
if: ${{ matrix.build_docs }}
|
||||
run: |
|
||||
mv ex_doc ../ex_doc
|
||||
cd ../ex_doc
|
||||
../elixir/bin/mix do local.rebar --force + local.hex --force + deps.get + compile
|
||||
cd ../elixir
|
||||
- name: Build Docs
|
||||
if: ${{ matrix.build_docs }}
|
||||
run: |
|
||||
make Docs.zip
|
||||
shasum -a 1 Docs.zip > Docs.zip.sha1sum
|
||||
shasum -a 256 Docs.zip > Docs.zip.sha256sum
|
||||
- name: Upload Docs
|
||||
if: ${{ matrix.build_docs }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
gh release upload --clobber "${{ github.ref_name }}" \
|
||||
Docs.zip \
|
||||
Docs.zip.sha{1,256}sum
|
||||
@@ -1,51 +0,0 @@
|
||||
name: "Release pre built"
|
||||
description: "Builds elixir release, ExDoc and generates docs"
|
||||
inputs:
|
||||
otp:
|
||||
description: "The major OTP version"
|
||||
otp_version:
|
||||
description: "The exact OTP version (major.minor[.patch])"
|
||||
build_docs:
|
||||
description: "If docs have to be built or not"
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: erlef/setup-beam@v1
|
||||
with:
|
||||
otp-version: ${{ inputs.otp_version }}
|
||||
version-type: strict
|
||||
- name: Build Elixir Release
|
||||
shell: bash
|
||||
run: |
|
||||
make Precompiled.zip
|
||||
mv Precompiled.zip elixir-otp-${{ inputs.otp }}.zip
|
||||
shasum -a 1 elixir-otp-${{ inputs.otp }}.zip > elixir-otp-${{ inputs.otp }}.zip.sha1sum
|
||||
shasum -a 256 elixir-otp-${{ inputs.otp }}.zip > elixir-otp-${{ inputs.otp }}.zip.sha256sum
|
||||
echo "$PWD/bin" >> $GITHUB_PATH
|
||||
- name: Get latest stable ExDoc version
|
||||
if: ${{ inputs.build_docs }}
|
||||
shell: bash
|
||||
run: |
|
||||
EX_DOC_LATEST_STABLE_VERSION=$(curl -s https://hex.pm/api/packages/ex_doc | jq --raw-output '.latest_stable_version')
|
||||
echo "EX_DOC_LATEST_STABLE_VERSION=${EX_DOC_LATEST_STABLE_VERSION}" >> $GITHUB_ENV
|
||||
- uses: actions/checkout@v3
|
||||
if: ${{ inputs.build_docs }}
|
||||
with:
|
||||
repository: elixir-lang/ex_doc
|
||||
ref: v${{ env.EX_DOC_LATEST_STABLE_VERSION }}
|
||||
path: ex_doc
|
||||
- name: Build ex_doc
|
||||
if: ${{ inputs.build_docs }}
|
||||
shell: bash
|
||||
run: |
|
||||
mv ex_doc ../ex_doc
|
||||
cd ../ex_doc
|
||||
../elixir/bin/mix do local.rebar --force + local.hex --force + deps.get + compile
|
||||
cd ../elixir
|
||||
- name: Build Docs
|
||||
if: ${{ inputs.build_docs }}
|
||||
shell: bash
|
||||
run: |
|
||||
make Docs.zip
|
||||
shasum -a 1 Docs.zip > Docs.zip.sha1sum
|
||||
shasum -a 256 Docs.zip > Docs.zip.sha256sum
|
||||
+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
|
||||
+134
-502
@@ -1,600 +1,232 @@
|
||||
# Changelog for Elixir v1.14
|
||||
# Changelog for Elixir v1.9
|
||||
|
||||
Elixir v1.14 brings many improvements to the debugging experience in Elixir
|
||||
and data-type inspection. It also includes a new abstraction for easy
|
||||
partitioning of processes called `PartitionSupervisor`, as well as improved
|
||||
compilation times and error messages.
|
||||
## Releases
|
||||
|
||||
Elixir v1.14 is the last version to support Erlang/OTP 23. Consider updating
|
||||
to Erlang/OTP 24 or Erlang/OTP 25.
|
||||
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.
|
||||
|
||||
## `dbg`
|
||||
You can start a new project and assemble a release for it in three easy steps:
|
||||
|
||||
`Kernel.dbg/2` is a new macro that's somewhat similar to `IO.inspect/2`, but
|
||||
specifically tailored for **debugging**.
|
||||
$ mix new my_app
|
||||
$ cd my_app
|
||||
$ MIX_ENV=prod mix release
|
||||
|
||||
When called, it prints the value of whatever you pass to it, plus the debugged
|
||||
code itself as well as its location. This code:
|
||||
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
|
||||
# In my_file.exs
|
||||
feature = %{name: :dbg, inspiration: "Rust"}
|
||||
dbg(feature)
|
||||
dbg(Map.put(feature, :in_version, "1.14.0"))
|
||||
```
|
||||
* `bin/my_app start`, `bin/my_app start_iex`, `bin/my_app restart`, and `bin/my_app stop` - for general management of the release
|
||||
|
||||
Prints this:
|
||||
* `bin/my_app rpc COMMAND` and `bin/my_app remote` - for running commands on the running system or to connect to the running system
|
||||
|
||||
```shell
|
||||
$ elixir my_file.exs
|
||||
[my_file.exs:2: (file)]
|
||||
feature #=> %{inspiration: "Rust", name: :dbg}
|
||||
* `bin/my_app eval COMMAND` - to start a fresh system that runs a single command and then shuts down
|
||||
|
||||
[my_file.exs:3: (file)]
|
||||
Map.put(feature, :in_version, "1.14.0") #=> %{in_version: "1.14.0", inspiration: "Rust", name: :dbg}
|
||||
```
|
||||
* `bin/my_app daemon` and `bin/my_app daemon_iex` - to start the system as a daemon on Unix-like systems
|
||||
|
||||
`dbg/2` can do more. It's a macro, so it *understands Elixir code*. You can see
|
||||
that when you pass a series of `|>` pipes to it. `dbg/2` will print the value
|
||||
for every step of the pipeline. This code:
|
||||
* `bin/my_app install` - to install the system as a service on Windows machines
|
||||
|
||||
```elixir
|
||||
# In dbg_pipes.exs
|
||||
__ENV__.file
|
||||
|> String.split("/", trim: true)
|
||||
|> List.last()
|
||||
|> File.exists?()
|
||||
|> dbg()
|
||||
```
|
||||
### Why releases?
|
||||
|
||||
Prints this:
|
||||
Releases allow developers to precompile and package all of their code and the runtime into a single unit. The benefits of releases are:
|
||||
|
||||
```shell
|
||||
$ elixir dbg_pipes.exs
|
||||
[dbg_pipes.exs:5: (file)]
|
||||
__ENV__.file #=> "/home/myuser/dbg_pipes.exs"
|
||||
|> String.split("/", trim: true) #=> ["home", "myuser", "dbg_pipes.exs"]
|
||||
|> List.last() #=> "dbg_pipes.exs"
|
||||
|> File.exists?() #=> true
|
||||
```
|
||||
* 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.
|
||||
|
||||
### IEx and Prying
|
||||
* Configuration and customization. Releases give developers fine grained control over system configuration and the VM flags used to start the system.
|
||||
|
||||
`dbg/2` supports configurable backends. IEx automatically replaces the default
|
||||
backend by one that halts the code execution with `IEx.Pry`, giving developers
|
||||
the option to access local variables, imports, and more. This also works with
|
||||
pipelines: if you pass a series of `|>` pipe calls to `dbg` (or pipe into it at the
|
||||
end, like `|> dbg()`), you'll be able to step through every line in the pipeline.
|
||||
* 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.
|
||||
|
||||
You can keep the default behaviour by passing the `--no-pry` option to IEx.
|
||||
* Multiple releases. You can assemble different releases with different configuration per application or even with different applications altogether.
|
||||
|
||||
## PartitionSupervisor
|
||||
### Hooks and Configuration
|
||||
|
||||
`PartitionSupervisor` is a new module that implements a new supervisor type. The
|
||||
partition supervisor is designed to help with situations where you have a single
|
||||
supervised process that becomes a bottleneck. If that process's state can be
|
||||
easily partitioned, then you can use `PartitionSupervisor` to supervise multiple
|
||||
isolated copies of that process running concurrently, each assigned its own
|
||||
partition.
|
||||
Releases also provide built-in hooks for configuring almost every need of the production system:
|
||||
|
||||
For example, imagine you have an `ErrorReporter` process that you use to report
|
||||
errors to a monitoring service.
|
||||
* `config/config.exs` (and `config/prod.exs`) - provides build-time application configuration, which is executed when the release is assembled
|
||||
|
||||
```elixir
|
||||
# Application supervisor:
|
||||
children = [
|
||||
# ...,
|
||||
ErrorReporter
|
||||
]
|
||||
* `config/releases.exs` - provides runtime application configuration. It is executed every time the release boots and is further extensible via config providers
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_one)
|
||||
```
|
||||
* `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
|
||||
|
||||
As the concurrency of your application goes up, the `ErrorReporter` process
|
||||
might receive requests from many other processes and eventually become a
|
||||
bottleneck. In a case like this, it could help to spin up multiple copies of the
|
||||
`ErrorReporter` process under a `PartitionSupervisor`.
|
||||
* `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
|
||||
|
||||
```elixir
|
||||
# Application supervisor
|
||||
children = [
|
||||
{PartitionSupervisor, child_spec: ErrorReporter, name: Reporters}
|
||||
]
|
||||
```
|
||||
We have written extensive documentation on releases, so we recommend checking it out for more information.
|
||||
|
||||
The `PartitionSupervisor` will spin up a number of processes equal to
|
||||
`System.schedulers_online()` by default (most often one per core). Now, when
|
||||
routing requests to `ErrorReporter` processes we can use a `:via` tuple and
|
||||
route the requests through the partition supervisor.
|
||||
## Configuration overhaul
|
||||
|
||||
```elixir
|
||||
partitioning_key = self()
|
||||
ErrorReporter.report({:via, PartitionSupervisor, {Reporters, partitioning_key}}, error)
|
||||
```
|
||||
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`.
|
||||
|
||||
Using `self()` as the partitioning key here means that the same process will
|
||||
always report errors to the same `ErrorReporter` process, ensuring a form of
|
||||
back-pressure. You can use any term as the partitioning key.
|
||||
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.
|
||||
|
||||
### A Common Example
|
||||
## Other enhancements
|
||||
|
||||
A common and practical example of a good use case for `PartitionSupervisor` is
|
||||
partitioning something like a `DynamicSupervisor`. When starting many processes
|
||||
under it, a dynamic supervisor can be a bottleneck, especially if said processes
|
||||
take a long time to initialize. Instead of starting a single `DynamicSupervisor`,
|
||||
you can start multiple:
|
||||
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.
|
||||
|
||||
```elixir
|
||||
children = [
|
||||
{PartitionSupervisor, child_spec: DynamicSupervisor, name: MyApp.DynamicSupervisors}
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_one)
|
||||
```
|
||||
|
||||
Now you start processes on the dynamic supervisor for the right partition.
|
||||
For instance, you can partition by PID, like in the previous example:
|
||||
|
||||
```elixir
|
||||
DynamicSupervisor.start_child(
|
||||
{:via, PartitionSupervisor, {MyApp.DynamicSupervisors, self()}},
|
||||
my_child_specification
|
||||
)
|
||||
```
|
||||
|
||||
## Improved errors on binaries and evaluation
|
||||
|
||||
Erlang/OTP 25 improved errors on binary construction and evaluation. These improvements
|
||||
apply to Elixir as well. Before v1.14, errors when constructing binaries would
|
||||
often be hard-to-debug generic "argument errors". With Erlang/OTP 25 and Elixir v1.14,
|
||||
more detail is provided for easier debugging. This work is part of [EEP
|
||||
54](https://www.erlang.org/eeps/eep-0054).
|
||||
|
||||
Before:
|
||||
|
||||
```elixir
|
||||
int = 1
|
||||
bin = "foo"
|
||||
int <> bin
|
||||
#=> ** (ArgumentError) argument error
|
||||
```
|
||||
|
||||
Now:
|
||||
|
||||
```elixir
|
||||
int = 1
|
||||
bin = "foo"
|
||||
int <> bin
|
||||
#=> ** (ArgumentError) construction of binary failed:
|
||||
#=> segment 1 of type 'binary':
|
||||
#=> expected a binary but got: 1
|
||||
```
|
||||
|
||||
## Slicing with steps
|
||||
|
||||
Elixir v1.12 introduced **stepped ranges**, which are ranges where you can
|
||||
specify the "step":
|
||||
|
||||
```elixir
|
||||
Enum.to_list(1..10//3)
|
||||
#=> [1, 4, 7, 10]
|
||||
```
|
||||
|
||||
Stepped ranges are particularly useful for numerical operations involving
|
||||
vectors and matrices (see [Nx](https://github.com/elixir-nx/nx), for example).
|
||||
However, the Elixir standard library was not making use of stepped ranges in its
|
||||
APIs. Elixir v1.14 starts to take advantage of steps with support for stepped
|
||||
ranges in a couple of functions. One of them is `Enum.slice/2`:
|
||||
|
||||
```elixir
|
||||
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
|
||||
Enum.slice(letters, 0..5//2)
|
||||
#=> ["a", "c", "e"]
|
||||
```
|
||||
|
||||
`binary_slice/2` (and `binary_slice/3` for completeness) has been added to the
|
||||
`Kernel` module, that works with bytes and also support stepped ranges:
|
||||
|
||||
```elixir
|
||||
binary_slice("Elixir", 1..5//2)
|
||||
#=> "lxr"
|
||||
```
|
||||
|
||||
## Expression-based inspection and `Inspect` improvements
|
||||
|
||||
In Elixir, it's conventional to implement the `Inspect` protocol for opaque
|
||||
structs so that they're inspected with a special notation, resembling this:
|
||||
|
||||
```elixir
|
||||
MapSet.new([:apple, :banana])
|
||||
#MapSet<[:apple, :banana]>
|
||||
```
|
||||
|
||||
This is generally done when the struct content or part of it is private and the
|
||||
`%name{...}` representation would reveal fields that are not part of the public
|
||||
API.
|
||||
|
||||
The downside of the `#name<...>` convention is that *the inspected output is not
|
||||
valid Elixir code*. For example, you cannot copy the inspected output and paste
|
||||
it into an IEx session.
|
||||
|
||||
Elixir v1.14 changes the convention for some of the standard-library structs.
|
||||
The `Inspect` implementation for those structs now returns a string with a valid
|
||||
Elixir expression that recreates the struct when evaluated. In the `MapSet`
|
||||
example above, this is what we have now:
|
||||
|
||||
```elixir
|
||||
fruits = MapSet.new([:apple, :banana])
|
||||
MapSet.put(fruits, :pear)
|
||||
#=> MapSet.new([:apple, :banana, :pear])
|
||||
```
|
||||
|
||||
The `MapSet.new/1` expression evaluates to exactly the struct that we're
|
||||
inspecting. This allows us to hide the internals of `MapSet`, while keeping
|
||||
it as valid Elixir code. This expression-based inspection has been
|
||||
implemented for `Version.Requirement`, `MapSet`, and `Date.Range`.
|
||||
|
||||
Finally, we have improved the `Inspect` protocol for structs so that
|
||||
fields are inspected in the order they are declared in `defstruct`.
|
||||
The option `:optional` has also been added when deriving the `Inspect`
|
||||
protocol, giving developers more control over the struct representation.
|
||||
See the updated documentation for `Inspect` for a general rundown on
|
||||
the approaches and options available.
|
||||
|
||||
## v1.14.5 (2023-05-22)
|
||||
|
||||
This release contains fixes for Erlang/OTP 26.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [CLI] Fix a bug where stdout would block when there was no attached terminal on Windows when running on Erlang/OTP 26
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix] Properly set SSL configuration for Mix downloads when running on Erlang/OTP 26
|
||||
|
||||
## v1.14.4 (2023-04-03)
|
||||
|
||||
This release adds basic support for Erlang/OTP 26. When migrating
|
||||
to Erlang/OTP 26, keep it mind it changes how maps are stored
|
||||
internally and they will be printed and traversed in a different
|
||||
order (note maps never provided a guarantee of their order).
|
||||
To aid migration, this release adds `:sort_maps` to `inspect`
|
||||
custom options, in case you want to sort them before inspection:
|
||||
|
||||
inspect(map, custom_options: [sort_maps: true])
|
||||
|
||||
### Enhancements
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Inspect] Add `:sort_maps` to `Inspect.Opts.custom_options`
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx] Support shell history in Erlang/OTP 26+
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix compile.elixir] Optimize application tracer
|
||||
|
||||
### Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Properly handle blocks with comments in all cases in `Code.quoted_to_string_with_comments/2`
|
||||
* [Kernel] Fix `debug_info/4` when returning core_v1
|
||||
* [Kernel] Store complete path on `quote keep: true` to avoid invalid stacktraces
|
||||
* [Kernel] Fix column count when tokenizing escaped interpolations
|
||||
* [Stream] Fix `Stream.zip/1` hanging on empty list
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix format] Don't call formatter on directories
|
||||
|
||||
## v1.14.3 (2023-01-14)
|
||||
## v1.9.2 (2019-10-12)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Elixir
|
||||
#### Mix
|
||||
|
||||
* [Kernel] Speed up loading of runtime modules in the parallel compiler
|
||||
* [Range] Optimize range membership implementation
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit] Return values from running doctests and make their order consistent
|
||||
* [mix release] Allow `{:from_app, app_name}` as a version for releases
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Calendar] Fix handling of negative years in `Calendar.strftime/2`
|
||||
* [DateTime] Consistently merge precision of subsecond operations (the bug was that subsecond precision was lost in functions like `DateTime.add/3`)
|
||||
* [Exception] Improve blaming of FunctionClauseError with `is_struct/2` guards
|
||||
* [Kernel] Fix invalid variable scoping in `defguard` expansion
|
||||
* [Kernel] Do not warn on captured underscored vars from `defmodule`
|
||||
* [Kernel] Do not crash for missing line info on type warnings
|
||||
* [NaiveDateTime] Consistently merge precision of subsecond operations (the bug was that subsecond precision was lost in functions like `NaiveDateTime.add/3`)
|
||||
* [Macro] Fix `Macro.to_string/1` for large negative integers
|
||||
* [Macro] Properly type and escape expansion of `__ENV__` in macros
|
||||
* [Path] Make sure `Path.wildcard/2` expands `..` symlinks accordingly
|
||||
* [Range] Address corner cases in `Range.disjoint?/2` implementation
|
||||
* [Time] Consistently merge precision of subsecond operations (the bug was that subsecond precision was lost in functions like `Time.add/3`)
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.DocTest] Remove unnecessary literal quotes from error message on reports
|
||||
|
||||
## v1.14.2 (2022-11-11)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Add `Code.eval_quoted_with_env/4` with support for the `:prune_binding` option
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.Case] Allow test cases to not be registered on use
|
||||
* [ExUnit.DocTest] Include `:doctest` and `:doctest_line` as meta tags
|
||||
* [ExUnit.Formatter] Expose `ExUnit.Formatter.format_assertion_diff/4`
|
||||
* [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
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix] `Mix.install/2` accepts atoms as paths
|
||||
* [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.Formatter] Fix `size*unit` shortcut in bitstring
|
||||
* [Kernel] Generate unique variables for macro expansion of `defguard`
|
||||
* [Protocol] Expand `:for` in protocols with the appropriate env
|
||||
* [Code] Fix formatter wrongly removing nested parens in nested calls
|
||||
|
||||
#### ExUnit
|
||||
#### Logger
|
||||
|
||||
* [ExUnit] Do not run duplicate cases on `ExUnit.run/1`
|
||||
* [Logger] Do not crash translator on poorly formatted supervisor names
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix test] Ensure proper error message when there is no test directory
|
||||
* [mix compile] Raise readable error for mismatched sources during compilation
|
||||
* [mix release] Preserve UTF8 encoding in release config files
|
||||
|
||||
## v1.14.1 (2022-10-10)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Kernel] Perform partial expansion of literals in module attributes
|
||||
* [Kernel] Do not add compile-time dependencies for literals as defaults in `Application.compile_env/3` inside module attributes
|
||||
* [Macro] Add `Macro.expand_literals/2` and `Macro.expand_literals/3`
|
||||
* [System] Add `:close_stdin` to `System.shell/2`
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix test] Accept `--all-warnings` option
|
||||
|
||||
## 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Kernel] Fix misleading warning when `:uniq` is given in `for` comprehensions and the result is unused
|
||||
* [Kernel] Improve error message for when there is a conflicting struct and ignoring module conflict
|
||||
* [Kernel] Do not delete `@enforce_keys` attribute after `defstruct` declaration
|
||||
* [Kernel] Do not crash the checker on modules with missing `:debug_info` chunk
|
||||
* [Macro] Fix error in `Macro.to_string/2` when converting an AST with `:erlang.binary_to_atom/2`
|
||||
* [String] Fix `String.split/3` and `String.next_grapheme/1` returning invalid results on invalid UTF-8 encoding
|
||||
* [System] Do not close stdin by default in `System.shell/2`
|
||||
* [URI] Do not return `uri.port` as `:undefined` in certain cases in `URI.new/1`
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.DocTest] Do not crash when both `:moduledoc` and functions are specified in `:only`
|
||||
|
||||
#### IEx
|
||||
|
||||
* [CLI] Fix invalid argument handling when `--no-pry` is given
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix format] Do not cache inputs from `.formatter.exs` so they are properly re-evaluted on every call
|
||||
|
||||
## v1.14.0 (2022-09-01)
|
||||
## v1.9.0 (2019-06-24)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### EEx
|
||||
|
||||
* [EEx] Support multi-line comments to EEx via `<%!-- --%>`
|
||||
* [EEx] Add `EEx.tokenize/2`
|
||||
* [EEx] Allow more complex mixed expressions when tokenizing
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Access] Add `Access.slice/1`
|
||||
* [Application] Add `Application.compile_env/4` and `Application.compile_env!/3` to read the compile-time environment inside macros
|
||||
* [Calendar] Support ISO8601 basic format parsing with `DateTime.from_iso8601/2`
|
||||
* [Calendar] Add `day`/`hour`/`minute` on `add`/`diff` across different calendar modules
|
||||
* [Code] Add `:normalize_bitstring_modifiers` to `Code.format_string!/2`
|
||||
* [Code] Emit deprecation and type warnings for invalid options in on `Code.compile_string/2` and `Code.compile_quoted/2`
|
||||
* [Code] Warn if an outdated lexical tracker is given on eval
|
||||
* [Code] Add `Code.env_for_eval/1` and `Code.eval_quoted_with_env/3`
|
||||
* [Code] Improve stacktraces from eval operations on Erlang/OTP 25+
|
||||
* [Code.Fragment] Add support for `__MODULE__` in several functions
|
||||
* [Code.Fragment] Support surround and context suggestions across multiple lines
|
||||
* [Enum] Allow slicing with steps in `Enum.slice/2`
|
||||
* [File] Support `dereference_symlinks: true` in `File.cp/3` and `File.cp_r/3`
|
||||
* [Float] Do not show floats in scientific notation if below `1.0e16` and the fractional value is precisely zero
|
||||
* [Float] Add `Float.min_finite/0` and `Float.max_finite/0`
|
||||
* [Inspect] Improve error reporting when there is a faulty implementation of the `Inspect` protocol
|
||||
* [Inspect] Allow `:optional` when deriving the Inspect protocol for hiding fields that match their default value
|
||||
* [Inspect] Inspect struct fields in the order they are declared in `defstruct`
|
||||
* [Inspect] Use expression-based inspection for `Date.Range`, `MapSet`, and `Version.Requirement`
|
||||
* [IO] Support `Macro.Env` and keywords as stacktrace definitions in `IO.warn/2`
|
||||
* [IO] Add `IO.ANSI.syntax_colors/0` and related configuration to be shared across IEx and `dbg`
|
||||
* [Kernel] Add new `dbg/0-2` macro
|
||||
* [Kernel] Allow any guard expression as the size of a bitstring in a pattern match
|
||||
* [Kernel] Allow composite types with pins as the map key in a pattern match
|
||||
* [Kernel] Print escaped version of control chars when they show up as unexpected tokens
|
||||
* [Kernel] Warn on confusable non-ASCII identifiers
|
||||
* [Kernel] Add `..` as a nullary operator that returns `0..-1//1`
|
||||
* [Kernel] Implement Unicode Technical Standard #39 recommendations. In particular, we warn for confusable scripts and restrict identifiers to single-scripts or highly restrictive mixed-scripts
|
||||
* [Kernel] Automatically perform NFC conversion of identifiers
|
||||
* [Kernel] Add `binary_slice/2` and `binary_slice/3`
|
||||
* [Kernel] Lazily expand module attributes to avoid compile-time deps
|
||||
* [Kernel] Automatically cascade `generated: true` annotations on macro expansion
|
||||
* [Keyword] Add `Keyword.from_keys/2` and `Keyword.replace_lazy/3`
|
||||
* [List] Add `List.keysort/3` with support for a `sorter` function
|
||||
* [Macro] Add `Macro.classify_atom/1` and `Macro.inspect_atom/2`
|
||||
* [Macro] Add `Macro.path/2`
|
||||
* [Macro.Env] Add `Macro.Env.prune_compile_info/1`
|
||||
* [Map] Add `Map.from_keys/2` and `Map.replace_lazy/3`
|
||||
* [MapSet] Add `MapSet.filter/2`, `MapSet.reject/2`, and `MapSet.symmetric_difference/2`
|
||||
* [Node] Add `Node.spawn_monitor/2` and `Node.spawn_monitor/4`
|
||||
* [Module] Support new `@after_verify` attribute for executing code whenever a module is verified
|
||||
* [PartitionSupervisor] Add `PartitionSupervisor` that starts multiple isolated partitions of the same child for scalability
|
||||
* [Path] Add `Path.safe_relative/1` and `Path.safe_relative_to/2`
|
||||
* [Registry] Add `Registry.count_select/2`
|
||||
* [Stream] Add `Stream.duplicate/2` and `Stream.transform/5`
|
||||
* [String] Support empty lookup lists in `String.replace/3`, `String.split/3`, and `String.splitter/3`
|
||||
* [String] Allow slicing with steps in `String.slice/2`
|
||||
* [Task] Add `:zip_input_on_exit` option to `Task.async_stream/3`
|
||||
* [Task] Store `:mfa` in the `Task` struct for reflection purposes
|
||||
* [URI] Add `URI.append_query/2`
|
||||
* [Version] Add `Version.to_string/1`
|
||||
* [Version] Colorize `Version.Requirement` source in the `Inspect` protocol
|
||||
* [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 `ExUnit.Callbacks.start_link_supervised!/2`
|
||||
* [ExUnit] Add `ExUnit.run/1` to rerun test modules
|
||||
* [ExUnit] Colorize summary in yellow with message when all tests are excluded
|
||||
* [ExUnit] Display friendly error when test name is too long
|
||||
* [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] Evaluate `--dot-iex` line by line
|
||||
* [IEx] Add line-by-line evaluation of IEx breakpoints
|
||||
* [IEx.Autocomplete] Autocomplete bitstrings modifiers (after `::` inside `<<...>>`)
|
||||
* [IEx.Helpers] Allow an atom to be given to `pid/1`
|
||||
* [IEx.Helpers] Support sigils in `h/1`
|
||||
* [IEx.CLI] Copy ticktime from remote node on IEx `--remsh`
|
||||
* [IEx.CLI] Automatically add a host on node given to `--remsh`
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Add `Logger.put_process_level/2`
|
||||
* [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 `:config_path` and `:lockfile` options to `Mix.install/2`
|
||||
* [mix compile] Add `--no-optional-deps` to skip optional dependencies to test compilation works without optional dependencies
|
||||
* [mix compile] Include column information on error diagnostics when possible
|
||||
* [mix deps] `Mix.Dep.Converger` now tells which deps formed a cycle
|
||||
* [mix do] Support `--app` option to restrict recursive tasks in umbrella projects
|
||||
* [mix do] Allow using `+` as a task separator instead of comma
|
||||
* [mix format] Support filename in `mix format -` when reading from stdin
|
||||
* [mix format] Compile if `mix format` plugins are missing
|
||||
* [mix new] Do not allow projects to be created with application names that conflict with multi-arg Erlang VM switches
|
||||
* [mix profile] Return the return value of the profiled function
|
||||
* [mix release] Make BEAM compression opt-in
|
||||
* [mix release] Let `:runtime_config_path` accept `false` to skip the `config/runtime.exs`
|
||||
* [mix test] Improve error message when suite fails due to coverage
|
||||
* [mix test] Support `:test_elixirc_options` and default to not generating docs nor debug info chunk for tests
|
||||
* [mix xref] Support `--group` flag in `mix xref graph`
|
||||
* [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] Consistently trim newlines when you have a single EEx expression per line on multiple lines
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Calendar] Handle widths with "0" in them in `Calendar.strftime/3`
|
||||
* [CLI] Improve errors on incorrect `--rpc-eval` usage
|
||||
* [CLI] Return proper exit code on Windows
|
||||
* [Code] Do not emit warnings when formatting code
|
||||
* [Enum] Allow slices to overflow on both starting and ending positions
|
||||
* [Kernel] Do not allow restricted characters in identifiers according to UTS39
|
||||
* [Kernel] Define `__exception__` field as `true` when expanding exceptions in typespecs
|
||||
* [Kernel] Warn if any of `True`, `False`, and `Nil` aliases are used
|
||||
* [Kernel] Warn on underived `@derive` attributes
|
||||
* [Kernel] Remove compile-time dependency from `defimpl :for`
|
||||
* [Kernel] Track all arities on imported functions
|
||||
* [Kernel] Fix equality in guards for dynamic ranges without steps
|
||||
* [Module] Fix loop while unifying type variables
|
||||
* [Protocol] Warn if a protocol has no definitions
|
||||
* [Regex] Show list options when inspecting a Regex manually defined with `Regex.compile/2`
|
||||
* [String] Allow slices to overflow on both starting and ending positions
|
||||
* [System] Raise non-generic exception on missing env in `System.fetch_env!/1` to mirror map operations
|
||||
* [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] Do not crash when diffing unknown bindings in guards
|
||||
* [ExUnit] Properly print diffs when comparing improper lists with strings at the tail position
|
||||
* [ExUnit] Add short hash to `tmp_dir` in ExUnit to avoid test name collision
|
||||
* [ExUnit] Do not store logs in the CLI formatter (this reduces memory usage for suites with `capture_log`)
|
||||
* [ExUnit] Run `ExUnit.after_suite/1` callback even when no tests run
|
||||
* [ExUnit] Fix scenario where `setup` with imported function from within `describe` failed to compile
|
||||
* [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] Disallow short-hand pipe after matches
|
||||
* [IEx] Fix `exports/1` in IEx for long function names
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix compile.elixir] Fix `--warnings-as-errors` when used with `--all-warnings`
|
||||
* [mix compile.elixir] Ensure semantic recompilation cascades to path dependencies
|
||||
* [mix compile.elixir] Lock the compiler to avoid concurrent usage
|
||||
* [mix format] Do not add new lines if the formatted file is empty
|
||||
* [mix format] Properly compile dependencies on `mix format`
|
||||
* [mix release] Only set `RELEASE_MODE` after `env.{sh,bat}` are executed
|
||||
* [mix release] Allow application mode configuration to cascade to dependencies
|
||||
* [mix xref] Do not emit already consolidated warnings during `mix xref trace`
|
||||
* [Mix] Do not start apps with `runtime: false` on `Mix.install/2`
|
||||
|
||||
### 3. Soft deprecations (no warnings emitted)
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [File] Passing a callback as third argument to `File.cp/3` and `File.cp_r/3` is deprecated.
|
||||
Instead pass the callback the `:on_conflict` key of a keyword list
|
||||
|
||||
#### EEx
|
||||
|
||||
* [EEx] Using `<%# ... %>` for comments is deprecated. Please use `<% # ... %>` or the new multi-line comments with `<%!-- ... --%>`
|
||||
* [IEx] Automatically shut down IEx if we receive EOF
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Deprecate `Logger.enable/1` and `Logger.disable/1` in favor of `Logger.put_process_level/2`
|
||||
* [Logger] Don't discard Logger messages from other nodes as to leave a trail on both systems
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix cmd] The `--app` option in `mix cmd CMD` is deprecated in favor of the more efficient `mix do --app app cmd CMD`
|
||||
* [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
|
||||
|
||||
### 4. Hard deprecations
|
||||
### 3. Soft-deprecations (no warnings emitted)
|
||||
|
||||
#### Mix
|
||||
|
||||
* [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
|
||||
|
||||
* [Application] Calling `Application.get_env/3` and friends in the module body is now discouraged, use `Application.compile_env/3` instead
|
||||
* [Bitwise] `use Bitwise` is deprecated, use `import Bitwise` instead
|
||||
* [Bitwise] `~~~` is deprecated in favor of `bnot` for clarity
|
||||
* [Kernel.ParallelCompiler] Returning a list or two-element tuple from `:each_cycle` is deprecated, return a `{:compile | :runtime, modules, warnings}` tuple instead
|
||||
* [Kernel] Deprecate the operator `<|>` to avoid ambiguity with upcoming extended numerical operators
|
||||
* [String] Deprecate passing a binary compiled pattern to `String.starts_with?/2`
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Deprecate `$levelpad` on message formatting
|
||||
* [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] `Mix.Tasks.Xref.calls/1` is deprecated in favor of compilation tracers
|
||||
* [Mix.Project] Deprecate `Mix.Project.load_paths/1` in favor of `Mix.Project.compile_path/1`
|
||||
|
||||
### 5. Backwards incompatible changes
|
||||
## v1.8
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix local.rebar] Remove support for rebar2, which has not been updated in 5 years, and is no longer supported on recent Erlang/OTP versions
|
||||
|
||||
## v1.13
|
||||
|
||||
The CHANGELOG for v1.13 releases can be found [in the v1.13 branch](https://github.com/elixir-lang/elixir/blob/v1.13/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).
|
||||
|
||||
+10
-16
@@ -13,23 +13,17 @@ The goal of the Code of Conduct is to specify a baseline standard of behavior so
|
||||
These are the values Elixir developers should aspire to:
|
||||
|
||||
* Be friendly and welcoming
|
||||
* Be kind
|
||||
* Be patient
|
||||
* Remember that people have varying communication styles and that not everyone is using their native language. (Meaning and tone can be lost in translation.)
|
||||
* Interpret the arguments of others in good faith, do not seek to disagree.
|
||||
* When we do disagree, try to understand why.
|
||||
* Be thoughtful
|
||||
* Productive communication requires effort. Think about how your words will be interpreted.
|
||||
* Remember that sometimes it is best to refrain entirely from commenting.
|
||||
* Be respectful
|
||||
* In particular, respect differences of opinion. It is important that we resolve disagreements and differing views constructively.
|
||||
* Be constructive
|
||||
* Avoid derailing: stay on topic; if you want to talk about something else, start a new conversation.
|
||||
* Avoid unconstructive criticism: don't merely decry the current state of affairs; offer — or at least solicit — suggestions as to how things may be improved.
|
||||
* Avoid harsh words and stern tone: we are all aligned towards the well-being of the community and the progress of the ecosystem. Harsh words exclude, demotivate, and lead to unnecessary conflict.
|
||||
* Avoid snarking (pithy, unproductive, sniping comments).
|
||||
* Avoid microaggressions (brief and commonplace verbal, behavioral and environmental indignities that communicate hostile, derogatory or negative slights and insults towards a project, person or group).
|
||||
* Be responsible
|
||||
* What you say and do matters. Take responsibility for your words and actions, including their consequences, whether intended or otherwise.
|
||||
* Avoid destructive behavior
|
||||
* Derailing: stay on topic; if you want to talk about something else, start a new conversation.
|
||||
* Unconstructive criticism: don't merely decry the current state of affairs; offer (or at least solicit) suggestions as to how things may be improved.
|
||||
* Snarking (pithy, unproductive, sniping comments).
|
||||
|
||||
The following actions are explicitly forbidden:
|
||||
|
||||
@@ -47,11 +41,11 @@ Explicit enforcement of the Code of Conduct applies to the official mediums oper
|
||||
|
||||
* The [official GitHub projects][1] and code reviews.
|
||||
* The official elixir-lang mailing lists.
|
||||
* The **[#elixir][2]** IRC channel on [Libera.Chat][3].
|
||||
* The **[#elixir-lang][2]** IRC channel on [Freenode][3].
|
||||
|
||||
Other Elixir activities (such as conferences, meetups, and unofficial forums) are encouraged to adopt this Code of Conduct. Such groups must provide their own contact information.
|
||||
|
||||
Project maintainers may block, remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct.
|
||||
Project maintainers may remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by emailing: elixir-lang-conduct@googlegroups.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. **All reports will be kept confidential**.
|
||||
|
||||
@@ -59,8 +53,8 @@ Instances of abusive, harassing, or otherwise unacceptable behavior may be repor
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This document was based on the Code of Conduct from the Go project (dated Sep/2021) and the Contributor Covenant (v1.4).
|
||||
This document was based on the Code of Conduct from the Go project with parts derived from Django's Code of Conduct, Rust's Code of Conduct and the Contributor Covenant.
|
||||
|
||||
[1]: https://github.com/elixir-lang/
|
||||
[2]: https://web.libera.chat/#elixir
|
||||
[3]: https://libera.chat/
|
||||
[2]: https://webchat.freenode.net/?channels=#elixir-lang
|
||||
[3]: https://www.freenode.net
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
### Precheck
|
||||
|
||||
* Do not use the issue tracker for help or support (try Elixir Forum, Stack Overflow, IRC, etc.)
|
||||
* For proposing a new feature, please start a discussion on the Elixir Core mailing list: https://groups.google.com/group/elixir-lang-core
|
||||
* For bugs, do a quick search and make sure the bug has not yet been reported
|
||||
* Please disclose security vulnerabilities privately at elixir-security@googlegroups.com
|
||||
* Finally, be nice and have fun!
|
||||
|
||||
### Environment
|
||||
|
||||
* Elixir & Erlang/OTP versions (elixir --version):
|
||||
* Operating system:
|
||||
|
||||
### Current behavior
|
||||
|
||||
Include code samples, errors and stacktraces if appropriate.
|
||||
|
||||
### Expected behavior
|
||||
|
||||
A short description on how you expect the code to behave.
|
||||
@@ -1,13 +1,9 @@
|
||||
PREFIX ?= /usr/local
|
||||
TEST_FILES ?= "*_test.exs"
|
||||
SHARE_PREFIX ?= $(PREFIX)/share
|
||||
MAN_PREFIX ?= $(SHARE_PREFIX)/man
|
||||
CANONICAL := 1.14/
|
||||
CANONICAL ?= main/
|
||||
DOCS_FORMAT ?= html
|
||||
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))
|
||||
@@ -23,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 >= 23)])' -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 23.0 is required to build Elixir"; \
|
||||
echo "At least Erlang/OTP 20.0 is required to build Elixir"; \
|
||||
exit 1; \
|
||||
fi
|
||||
endef
|
||||
@@ -49,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
|
||||
@@ -77,14 +73,14 @@ 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}' $<
|
||||
|
||||
# Since Mix depends on EEx and EEx depends on Mix,
|
||||
# we first compile EEx without the .app file,
|
||||
# then Mix, and then compile EEx fully
|
||||
# then Mix and then compile EEx fully
|
||||
elixir: stdlib lib/eex/ebin/Elixir.EEx.beam mix ex_unit logger eex iex
|
||||
|
||||
stdlib: $(KERNEL) VERSION
|
||||
@@ -93,10 +89,11 @@ $(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)" app
|
||||
$(Q) $(MAKE) unicode
|
||||
$(Q) $(MAKE) app
|
||||
|
||||
app: $(APP)
|
||||
$(APP): lib/elixir/src/elixir.app.src lib/elixir/ebin VERSION $(GENERATE_APP)
|
||||
@@ -106,7 +103,7 @@ unicode: $(UNICODE)
|
||||
$(UNICODE): lib/elixir/unicode/*
|
||||
@ echo "==> unicode (compile)";
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/unicode.ex -o lib/elixir/ebin;
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/security.ex -o lib/elixir/ebin;
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/properties.ex -o lib/elixir/ebin;
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/tokenizer.ex -o lib/elixir/ebin;
|
||||
|
||||
$(eval $(call APP_TEMPLATE,ex_unit,ExUnit))
|
||||
@@ -128,7 +125,7 @@ install: compile
|
||||
$(Q) for file in "$(DESTDIR)$(PREFIX)"/$(LIBDIR)/elixir/bin/*; do \
|
||||
ln -sf "../$(LIBDIR)/elixir/bin/$${file##*/}" "$(DESTDIR)$(PREFIX)/$(BINDIR)/"; \
|
||||
done
|
||||
"$(MAKE)" install_man
|
||||
$(MAKE) install_man
|
||||
|
||||
check_reproducible: compile
|
||||
$(Q) echo "==> Checking for reproducible builds..."
|
||||
@@ -136,31 +133,28 @@ 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
|
||||
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:
|
||||
rm -rf ebin
|
||||
rm -rf lib/*/ebin
|
||||
rm -rf $(PARSER)
|
||||
$(Q) "$(MAKE)" clean_residual_files
|
||||
$(Q) $(MAKE) clean_residual_files
|
||||
|
||||
clean_elixir:
|
||||
$(Q) rm -f lib/*/ebin/Elixir.*.beam
|
||||
@@ -173,54 +167,47 @@ clean_residual_files:
|
||||
rm -rf lib/mix/test/fixtures/git_rebar/
|
||||
rm -rf lib/mix/test/fixtures/git_repo/
|
||||
rm -rf lib/mix/test/fixtures/git_sparse_repo/
|
||||
rm -rf lib/mix/test/fixtures/archive/ebin/
|
||||
rm -f erl_crash.dump
|
||||
$(Q) "$(MAKE)" clean_man
|
||||
$(Q) $(MAKE) clean_man
|
||||
|
||||
#==> 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}")
|
||||
DOCS_COMPILE = CANONICAL=$(CANONICAL) 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)
|
||||
DOCS_CONFIG = bin/elixir lib/elixir/scripts/docs_config.exs "$(1)"
|
||||
SOURCE_REF = $(shell tag="$(call GIT_TAG)" revision="$(call GIT_REVISION)"; echo "$${tag:-$$revision}\c")
|
||||
DOCS_FORMAT = html
|
||||
COMPILE_DOCS = bin/elixir ../ex_doc/bin/ex_doc "$(1)" "$(VERSION)" "lib/$(2)/ebin" -m "$(3)" -u "https://github.com/elixir-lang/elixir" --source-ref "$(call SOURCE_REF)" $(call LOGO_PATH) -o doc/$(2) -n https://hexdocs.pm/$(2)/$(CANONICAL) -p https://elixir-lang.org/docs.html -f "$(DOCS_FORMAT)" $(4)
|
||||
|
||||
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 DOCS_COMPILE,Elixir,elixir,Kernel,--config "lib/elixir/scripts/elixir_docs.exs")
|
||||
$(call DOCS_CONFIG,elixir)
|
||||
$(call COMPILE_DOCS,Elixir,elixir,Kernel,-c lib/elixir/docs.exs)
|
||||
|
||||
docs_eex: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (eex)"
|
||||
$(Q) rm -rf doc/eex
|
||||
$(call DOCS_COMPILE,EEx,eex,EEx,--config "lib/elixir/scripts/mix_docs.exs")
|
||||
$(call DOCS_CONFIG,eex)
|
||||
$(call COMPILE_DOCS,EEx,eex,EEx)
|
||||
|
||||
docs_mix: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (mix)"
|
||||
$(Q) rm -rf doc/mix
|
||||
$(call DOCS_COMPILE,Mix,mix,Mix,--config "lib/elixir/scripts/mix_docs.exs")
|
||||
$(call DOCS_CONFIG,mix)
|
||||
$(call COMPILE_DOCS,Mix,mix,Mix)
|
||||
|
||||
docs_iex: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (iex)"
|
||||
$(Q) rm -rf doc/iex
|
||||
$(call DOCS_COMPILE,IEx,iex,IEx,--config "lib/elixir/scripts/mix_docs.exs")
|
||||
$(call DOCS_CONFIG,iex)
|
||||
$(call COMPILE_DOCS,IEx,iex,IEx)
|
||||
|
||||
docs_ex_unit: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (ex_unit)"
|
||||
$(Q) rm -rf doc/ex_unit
|
||||
$(call DOCS_COMPILE,ExUnit,ex_unit,ExUnit,--config "lib/elixir/scripts/mix_docs.exs")
|
||||
$(call DOCS_CONFIG,ex_unit)
|
||||
$(call COMPILE_DOCS,ExUnit,ex_unit,ExUnit)
|
||||
|
||||
docs_logger: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (logger)"
|
||||
$(Q) rm -rf doc/logger
|
||||
$(call DOCS_COMPILE,Logger,logger,Logger,--config "lib/elixir/scripts/mix_docs.exs")
|
||||
$(call DOCS_CONFIG,logger)
|
||||
$(call COMPILE_DOCS,Logger,logger,Logger)
|
||||
|
||||
../ex_doc/bin/ex_doc:
|
||||
@ echo "ex_doc is not found in ../ex_doc as expected. See README for more information."
|
||||
@@ -229,18 +216,27 @@ docs_logger: compile ../ex_doc/bin/ex_doc
|
||||
#==> Zip tasks
|
||||
|
||||
Docs.zip: docs
|
||||
rm -f Docs.zip
|
||||
zip -9 -r Docs.zip CHANGELOG.md doc NOTICE LICENSE README.md
|
||||
@ echo "Docs file created $(CURDIR)/Docs.zip"
|
||||
rm -f Docs-v$(VERSION).zip
|
||||
zip -9 -r Docs-v$(VERSION).zip CHANGELOG.md doc NOTICE LICENSE README.md
|
||||
@ echo "Docs file created $(CURDIR)/Docs-v$(VERSION).zip"
|
||||
|
||||
Precompiled.zip: build_man compile
|
||||
rm -f Precompiled.zip
|
||||
zip -9 -r Precompiled.zip bin CHANGELOG.md lib/*/ebin lib/*/lib LICENSE Makefile man NOTICE README.md VERSION
|
||||
@ echo "Precompiled file created $(CURDIR)/Precompiled.zip"
|
||||
rm -f Precompiled-v$(VERSION).zip
|
||||
zip -9 -r Precompiled-v$(VERSION).zip bin CHANGELOG.md lib/*/ebin lib/*/lib LICENSE man NOTICE README.md VERSION
|
||||
@ echo "Precompiled file created $(CURDIR)/Precompiled-v$(VERSION).zip"
|
||||
|
||||
zips: Precompiled.zip Docs.zip
|
||||
@ echo ""
|
||||
@ echo "### Checksums"
|
||||
@ echo ""
|
||||
@ shasum -a 1 < Precompiled-v$(VERSION).zip | sed -e "s/-//" | xargs echo " * Precompiled.zip SHA1:"
|
||||
@ shasum -a 512 < Precompiled-v$(VERSION).zip | sed -e "s/-//" | xargs echo " * Precompiled.zip SHA512:"
|
||||
@ shasum -a 1 < Docs-v$(VERSION).zip | sed -e "s/-//" | xargs echo " * Docs.zip SHA1:"
|
||||
@ shasum -a 512 < Docs-v$(VERSION).zip | sed -e "s/-//" | xargs echo " * Docs.zip SHA512:"
|
||||
@ echo ""
|
||||
|
||||
#==> Test tasks
|
||||
|
||||
# If you modify this task, please update .cirrus.yml accordingly
|
||||
test: test_formatted test_erlang test_elixir
|
||||
|
||||
test_windows: test test_taskkill
|
||||
@@ -253,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)"
|
||||
@@ -276,15 +261,15 @@ $(TEST_EBIN)/%.beam: $(TEST_ERL)/%.erl
|
||||
$(Q) mkdir -p $(TEST_EBIN)
|
||||
$(Q) $(ERLC) -o $(TEST_EBIN) $<
|
||||
|
||||
test_elixir: test_stdlib test_ex_unit test_logger test_eex test_iex test_mix
|
||||
test_elixir: test_stdlib test_ex_unit test_logger test_mix test_eex test_iex
|
||||
|
||||
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
|
||||
@@ -294,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 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)
|
||||
@@ -333,4 +318,4 @@ install_man: build_man
|
||||
$(Q) $(INSTALL_DATA) man/elixirc.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(Q) $(INSTALL_DATA) man/iex.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(Q) $(INSTALL_DATA) man/mix.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
"$(MAKE)" clean_man
|
||||
$(MAKE) clean_man
|
||||
|
||||
@@ -22,7 +22,6 @@ limitations under the License.
|
||||
== All other files
|
||||
|
||||
Copyright 2012 Plataformatec
|
||||
Copyright 2021 The Elixir Team
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<img src="https://github.com/elixir-lang/elixir-lang.github.com/raw/main/images/logo/logo.png#gh-light-mode-only" width="200" alt="Elixir">
|
||||
<img src="https://github.com/elixir-lang/elixir-lang.github.com/raw/main/images/logo/logo-dark.png#gh-dark-mode-only" width="200" alt="Elixir">
|
||||
|
||||
[](https://github.com/elixir-lang/elixir/actions?query=branch%3Amain+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.
|
||||
@@ -12,14 +13,11 @@ For more about Elixir, installation and documentation,
|
||||
## Policies
|
||||
|
||||
New releases are announced in the [announcement mailing list][8].
|
||||
You can subscribe by sending an email to elixir-lang-ann+subscribe@googlegroups.com
|
||||
and replying to the confirmation email.
|
||||
You can subscribe by sending an email to elixir-lang-ann+subscribe@googlegroups.com and replying to the confirmation email.
|
||||
|
||||
All security releases [will be tagged with `[security]`][10]. For more
|
||||
information, please read our [Security Policy][9].
|
||||
All security releases [will be tagged with `[security]`][10]. For more information, please read our [Security Policy][9].
|
||||
|
||||
All interactions in our official communication channels follow our
|
||||
[Code of Conduct][1].
|
||||
All interactions in our official communication channels follow our [Code of Conduct][1].
|
||||
|
||||
## Bug reports
|
||||
|
||||
@@ -27,56 +25,13 @@ For reporting bugs, [visit our issue tracker][2] and follow the steps
|
||||
for reporting a new issue. **Please disclose security vulnerabilities
|
||||
privately at elixir-security@googlegroups.com**.
|
||||
|
||||
## Issues tracker management
|
||||
|
||||
All currently open bugs related to the Elixir repository are listed
|
||||
in the issues tracker. The Elixir team uses the issues tracker to focus
|
||||
on *actionable items*, including planned enhancements in the short- and
|
||||
medium-term. We also do our best to label entries for clarity and to ease
|
||||
collaboration.
|
||||
|
||||
Our *actionable item policy* has some important consequences, such as:
|
||||
|
||||
* Proposing new features as well as request for support, help, and
|
||||
guidance must be done in their own spaces, detailed next.
|
||||
|
||||
* Issues where we have identified to be outside of Elixir scope,
|
||||
such as a bug upstream, will be closed (and requested to be moved
|
||||
elsewhere if appropriate).
|
||||
|
||||
* We actively close unrelated and non-actionable issues to keep the
|
||||
issues tracker tidy. However, we may get things wrong from time to
|
||||
time, so we are glad to revisit issues and reopen if necessary.
|
||||
|
||||
Keep the tone positive and be kind! For more information, see the
|
||||
[Code of Conduct][1].
|
||||
|
||||
### Proposing new features
|
||||
|
||||
For proposing new features, please start a discussion in the
|
||||
[Elixir Core mailing list][3]. Keep in mind that it is your responsibility
|
||||
to argue and explain why a feature is useful and how it will impact the
|
||||
codebase and the community.
|
||||
|
||||
Once a proposal is accepted, it will be added to [the issue tracker][2].
|
||||
Features and bug fixes that have already been merged and will be included
|
||||
in the next release are then "closed" and added to the [changelog][7].
|
||||
|
||||
### Discussions, support, and help
|
||||
|
||||
For general discussions, support, and help, please use many of the community
|
||||
spaces [listed on the sidebar of the Elixir website](https://elixir-lang.org/),
|
||||
such as forums, chat platforms, etc, where the wider community will be available
|
||||
to help you.
|
||||
|
||||
## Compiling from source
|
||||
|
||||
For the many different ways to install Elixir,
|
||||
[see our installation instructions on the website](https://elixir-lang.org/install.html).
|
||||
However, if you want to contribute to Elixir, you will need to compile from source.
|
||||
To compile from source, you can follow the steps below.
|
||||
|
||||
First, [install Erlang](https://elixir-lang.org/install.html#installing-erlang).
|
||||
After that, clone this repository to your machine, compile and test it:
|
||||
First, [install Erlang](https://elixir-lang.org/install.html#installing-erlang). Then clone this repository to your machine, compile and test it:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/elixir-lang/elixir.git
|
||||
@@ -88,13 +43,37 @@ make clean test
|
||||
[this article includes important notes for compiling Elixir from source
|
||||
on Windows](https://github.com/elixir-lang/elixir/wiki/Windows).
|
||||
|
||||
In case you want to use this Elixir version as your system version,
|
||||
you need to add the `bin` directory to [your PATH environment variable](https://elixir-lang.org/install.html#setting-path-environment-variable).
|
||||
|
||||
If Elixir fails to build (specifically when pulling in a new version via
|
||||
`git`), be sure to remove any previous build artifacts by running
|
||||
`make clean`, then `make test`.
|
||||
|
||||
If tests pass, you 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 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 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.
|
||||
|
||||
## Proposing new features
|
||||
|
||||
For proposing new features, please start a discussion in the
|
||||
[Elixir Core mailing list][3]. Keep in mind that it is your responsibility
|
||||
to argue and explain why a feature is useful and how it will impact the
|
||||
codebase and the community.
|
||||
|
||||
Once a proposal is accepted, it will be added to [the issue tracker][2].
|
||||
The issue tracker focuses on *actionable items* and it holds a list of
|
||||
upcoming enhancements and pending bugs. All entries in the tracker are
|
||||
tagged for clarity and to ease collaboration.
|
||||
|
||||
Features and bug fixes that have already been merged and will be included
|
||||
in the next release are marked as "closed" in the issue tracker and are
|
||||
added to the [changelog][7].
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome everyone to contribute to Elixir. To do so, there are a few
|
||||
@@ -115,7 +94,7 @@ in applications inside the `lib` folder:
|
||||
|
||||
You can run all tests in the root directory with `make test` and you can
|
||||
also run tests for a specific framework `make test_#{APPLICATION}`, for example,
|
||||
`make test_ex_unit`. If you just changed something in Elixir's standard
|
||||
`make test_ex_unit`. If you just changed something in the Elixir's standard
|
||||
library, you can run only that portion through `make test_stdlib`.
|
||||
|
||||
If you are changing just one file, you can choose to compile and run tests only
|
||||
@@ -127,19 +106,13 @@ bin/elixirc lib/elixir/lib/string.ex -o lib/elixir/ebin
|
||||
bin/elixir lib/elixir/test/elixir/string_test.exs
|
||||
```
|
||||
|
||||
You can also use the `LINE` env var to run a single test:
|
||||
|
||||
```sh
|
||||
LINE=123 bin/elixir lib/elixir/test/elixir/string_test.exs
|
||||
````
|
||||
|
||||
To recompile (including Erlang modules):
|
||||
|
||||
```sh
|
||||
make compile
|
||||
```
|
||||
|
||||
After your changes are done, please remember to run `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`.
|
||||
|
||||
@@ -152,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](https://github.com/elixir-lang/elixir/actions/workflows/ci.yml).
|
||||
[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
|
||||
@@ -160,9 +133,9 @@ With tests running and passing, you are ready to contribute to Elixir and
|
||||
We have saved some excellent pull requests we have received in the past in
|
||||
case you are looking for some examples:
|
||||
|
||||
* [Implement Enum.member? - Pull request](https://github.com/elixir-lang/elixir/pull/992)
|
||||
* [Add String.valid? - Pull request](https://github.com/elixir-lang/elixir/pull/1058)
|
||||
* [Implement capture_io for ExUnit - Pull request](https://github.com/elixir-lang/elixir/pull/1059)
|
||||
* [Implement Enum.member? - Pull Request](https://github.com/elixir-lang/elixir/pull/992)
|
||||
* [Add String.valid? - Pull Request](https://github.com/elixir-lang/elixir/pull/1058)
|
||||
* [Implement capture_io for ExUnit - Pull Request](https://github.com/elixir-lang/elixir/pull/1059)
|
||||
|
||||
### Reviewing changes
|
||||
|
||||
@@ -171,12 +144,12 @@ We outline our process below to clarify the roles of everyone involved.
|
||||
|
||||
All pull requests must be approved by two committers before being merged into
|
||||
the repository. If any changes are necessary, the team will leave appropriate
|
||||
comments requesting changes to the code. Unfortunately, we cannot guarantee a
|
||||
comments requesting changes to the code. Unfortunately we cannot guarantee a
|
||||
pull request will be merged, even when modifications are requested, as the Elixir
|
||||
team will re-evaluate the contribution as it changes.
|
||||
|
||||
Committers may also push style changes directly to your branch. If you would
|
||||
rather manage all changes yourself, you can disable the "Allow edits from maintainers"
|
||||
rather manage all changes yourself, you can disable "Allow edits from maintainers"
|
||||
feature when submitting your pull request.
|
||||
|
||||
The Elixir team may optionally assign someone to review a pull request.
|
||||
@@ -195,8 +168,8 @@ to be installed and built alongside Elixir:
|
||||
|
||||
```sh
|
||||
# After cloning and compiling Elixir, in its parent directory:
|
||||
git clone https://github.com/elixir-lang/ex_doc.git
|
||||
cd ex_doc && ../elixir/bin/mix do deps.get + compile
|
||||
git clone git://github.com/elixir-lang/ex_doc.git
|
||||
cd ex_doc && ../elixir/bin/mix do deps.get, compile
|
||||
```
|
||||
|
||||
Now go back to Elixir's root directory and run:
|
||||
@@ -206,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
|
||||
@@ -219,13 +192,13 @@ and `mix` under the `doc` directory. If you are planning to contribute documenta
|
||||
* [Issue tracker][2]
|
||||
* [Changelog][7]
|
||||
* [Security Policy][9]
|
||||
* **[#elixir][4]** on [Libera.Chat][5] IRC
|
||||
* **[#elixir-lang][4]** on [Freenode][5] IRC
|
||||
|
||||
[1]: CODE_OF_CONDUCT.md
|
||||
[2]: https://github.com/elixir-lang/elixir/issues
|
||||
[3]: https://groups.google.com/group/elixir-lang-core
|
||||
[4]: https://web.libera.chat/#elixir
|
||||
[5]: https://libera.chat
|
||||
[4]: https://webchat.freenode.net/?channels=#elixir-lang
|
||||
[5]: https://www.freenode.net
|
||||
[6]: https://elixir-lang.org/docs.html
|
||||
[7]: CHANGELOG.md
|
||||
[8]: https://groups.google.com/group/elixir-lang-ann
|
||||
@@ -234,7 +207,7 @@ and `mix` under the `doc` directory. If you are planning to contribute documenta
|
||||
|
||||
## License
|
||||
|
||||
"Elixir" and the Elixir logo are registered trademarks of The Elixir Team.
|
||||
"Elixir" and the Elixir logo are copyright (c) 2012 Plataformatec.
|
||||
|
||||
Elixir source code is released under Apache License 2.0.
|
||||
|
||||
|
||||
+15
-19
@@ -4,19 +4,25 @@
|
||||
|
||||
1. Ensure you are running on the oldest supported Erlang version
|
||||
|
||||
2. Update version in /VERSION, bin/elixir and bin/elixir.bat
|
||||
2. Update version in /VERSION
|
||||
|
||||
3. Ensure /CHANGELOG.md is updated, versioned and add the current date
|
||||
|
||||
4. Update "Compatibility and Deprecations" if a new OTP version is supported
|
||||
|
||||
5. Commit changes above with title "Release vVERSION", generate a new tag, and push it
|
||||
5. Commit changes above with title "Release vVERSION" and generate a new tag
|
||||
|
||||
6. Wait until GitHub Actions publish artifacts to the draft release and the CI is green
|
||||
6. Run `make clean test` to ensure all tests pass from scratch and the CI is green
|
||||
|
||||
7. Copy the relevant bits from /CHANGELOG.md to the GitHub release and publish it
|
||||
7. Recompile an existing project (for example, Ecto) to ensure manifests can be upgraded
|
||||
|
||||
8. Add the release to `elixir.csv` with the minimum supported OTP version (all releases), update `erlang.csv` to the latest supported OTP version, and `_data/elixir-versions.yml` (except for RCs) files in `elixir-lang/elixir-lang.github.com`
|
||||
8. Push branch and the new tag
|
||||
|
||||
9. Publish new zips with `make zips`, upload `Precompiled.zip` and `Docs.zip` to GitHub Releases, and include SHAs+CHANGELOG
|
||||
|
||||
10. Add the release to `elixir.csv` (all releases) and `_data/elixir-versions.yml` (except for RCs) files in `elixir-lang/elixir-lang.github.com`
|
||||
|
||||
11. Send an e-mail to elixir-lang-ann@googlegroups.com with title "Elixir vVERSION released". The body should be a link to the Release page on GitHub and the checksums. If it is a security release, prefix the title with the `[security]` tag
|
||||
|
||||
## Creating a new vMAJOR.MINOR branch
|
||||
|
||||
@@ -26,24 +32,14 @@
|
||||
|
||||
2. Update tables in /SECURITY.md and "Compatibility and Deprecations"
|
||||
|
||||
3. Commit "Branch out vMAJOR.MINOR"
|
||||
3. Commit "Prepare vMAJOR.MINOR for release"
|
||||
|
||||
### Back in main
|
||||
### Back in master
|
||||
|
||||
1. Bump /VERSION file, bin/elixir and bin/elixir.bat
|
||||
1. Bump /VERSION file
|
||||
|
||||
2. Start new /CHANGELOG.md
|
||||
|
||||
3. Update tables in /SECURITY.md and in "Compatibility and Deprecations"
|
||||
3. Update tables in "Compatibility and Deprecations"
|
||||
|
||||
4. Commit "Start vMAJOR.MINOR+1"
|
||||
|
||||
## Changing supported Erlang/OTP versions
|
||||
|
||||
1. Update the table in Compatibility and Deprecations
|
||||
|
||||
2. Update `otp_release` checks in /Makefile and `/lib/elixir/src/elixir.erl`
|
||||
|
||||
3. Update CI workflows in `/.cirrus.yml`, `/.github/workflows/ci.yml`, and `/.github/workflows/releases.yml`
|
||||
|
||||
4. Remove `otp_release` version checks that are no longer needed
|
||||
|
||||
+8
-8
@@ -4,19 +4,19 @@
|
||||
|
||||
Elixir applies bug fixes only to the latest minor branch. Security patches are available for the last 5 minor branches:
|
||||
|
||||
Elixir version | Support
|
||||
:------------- | :-----------------------------
|
||||
1.14 | Bug fixes and security patches
|
||||
1.13 | Security patches only
|
||||
1.12 | Security patches only
|
||||
1.11 | Security patches only
|
||||
1.10 | Security patches only
|
||||
| Elixir version | Support
|
||||
| -------------- | ------------------------------
|
||||
| 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
|
||||
|
||||
New releases are announced in the read-only [announcements mailing list](https://groups.google.com/group/elixir-lang-ann). You can subscribe by sending an email to elixir-lang-ann+subscribe@googlegroups.com and replying to the confirmation email.
|
||||
|
||||
Security notifications [will be tagged with `[security]`](https://groups.google.com/forum/#!searchin/elixir-lang-ann/%5Bsecurity%5D%7Csort:date).
|
||||
All security releases [will be tagged with `[security]`](https://groups.google.com/forum/#!searchin/elixir-lang-ann/%5Bsecurity%5D%7Csort:date).
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
|
||||
+49
-69
@@ -1,30 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
ELIXIR_VERSION=1.14.5
|
||||
|
||||
if [ $# -eq 0 ] || { [ $# -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; }; then
|
||||
cat <<USAGE >&2
|
||||
Usage: $(basename "$0") [options] [.exs file] [data]
|
||||
if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
echo "Usage: $(basename "$0") [options] [.exs file] [data]
|
||||
|
||||
## General options
|
||||
|
||||
-e "COMMAND" Evaluates the given command (*)
|
||||
-h, --help Prints this message (standalone)
|
||||
-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 (*)
|
||||
-v, --version Prints Erlang/OTP and Elixir versions (standalone)
|
||||
-e \"COMMAND\" Evaluates the given command (*)
|
||||
-h, --help Prints this message and exits
|
||||
-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 (*)
|
||||
-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
|
||||
--short-version Prints Elixir version (standalone)
|
||||
--werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
|
||||
Options given after the .exs file or -- are passed down to the executed code.
|
||||
@@ -37,26 +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.
|
||||
** Standalone options can't be combined with other options.
|
||||
USAGE
|
||||
** Options marked with (*) can be given more than once." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -70,16 +64,11 @@ readlink_f () {
|
||||
fi
|
||||
}
|
||||
|
||||
if [ $# -eq 1 ] && [ "$1" = "--short-version" ]; then
|
||||
echo "$ELIXIR_VERSION"
|
||||
exit 0
|
||||
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)
|
||||
erl_set () {
|
||||
erl () {
|
||||
eval "E${E}=\$1"
|
||||
E=$((E + 1))
|
||||
}
|
||||
@@ -100,29 +89,32 @@ LENGTH=$#
|
||||
set -- "$@" -extra
|
||||
|
||||
while [ $I -le $LENGTH ]; do
|
||||
# S counts to be shifted, C counts to be copied
|
||||
S=0
|
||||
C=0
|
||||
S=1
|
||||
case "$1" in
|
||||
+iex)
|
||||
C=1
|
||||
set -- "$@" "$1"
|
||||
MODE="iex"
|
||||
;;
|
||||
+elixirc)
|
||||
C=1
|
||||
set -- "$@" "$1"
|
||||
MODE="elixirc"
|
||||
;;
|
||||
-v|--no-halt|--no-pry)
|
||||
C=1
|
||||
-v|--no-halt)
|
||||
set -- "$@" "$1"
|
||||
;;
|
||||
-e|-r|-pr|-pa|-pz|--app|--eval|--remsh|--dot-iex)
|
||||
C=2
|
||||
S=2
|
||||
set -- "$@" "$1" "$2"
|
||||
;;
|
||||
--rpc-eval)
|
||||
C=3
|
||||
S=3
|
||||
set -- "$@" "$1" "$2" "$3"
|
||||
;;
|
||||
--detached)
|
||||
echo "warning: the --detached option is deprecated" >&2
|
||||
ERL="$ERL -detached"
|
||||
;;
|
||||
--hidden)
|
||||
S=1
|
||||
ERL="$ERL -hidden"
|
||||
;;
|
||||
--logger-otp-reports)
|
||||
@@ -143,34 +135,34 @@ while [ $I -le $LENGTH ]; do
|
||||
;;
|
||||
--cookie)
|
||||
S=2
|
||||
erl_set "-setcookie"
|
||||
erl_set "$2"
|
||||
erl "-setcookie"
|
||||
erl "$2"
|
||||
;;
|
||||
--sname|--name)
|
||||
S=2
|
||||
erl_set "$(echo "$1" | cut -c 2-)"
|
||||
erl_set "$2"
|
||||
erl "$(echo "$1" | cut -c 2-)"
|
||||
erl "$2"
|
||||
;;
|
||||
--erl-config)
|
||||
S=2
|
||||
erl_set "-config"
|
||||
erl_set "$2"
|
||||
erl "-config"
|
||||
erl "$2"
|
||||
;;
|
||||
--vm-args)
|
||||
S=2
|
||||
erl_set "-args_file"
|
||||
erl_set "$2"
|
||||
erl "-args_file"
|
||||
erl "$2"
|
||||
;;
|
||||
--boot)
|
||||
S=2
|
||||
erl_set "-boot"
|
||||
erl_set "$2"
|
||||
erl "-boot"
|
||||
erl "$2"
|
||||
;;
|
||||
--boot-var)
|
||||
S=3
|
||||
erl_set "-boot_var"
|
||||
erl_set "$2"
|
||||
erl_set "$3"
|
||||
erl "-boot_var"
|
||||
erl "$2"
|
||||
erl "$3"
|
||||
;;
|
||||
--pipe-to)
|
||||
S=3
|
||||
@@ -183,7 +175,6 @@ while [ $I -le $LENGTH ]; do
|
||||
fi
|
||||
;;
|
||||
--werl)
|
||||
S=1
|
||||
if [ "$OS" = "Windows_NT" ]; then ERL_EXEC="werl"; fi
|
||||
;;
|
||||
*)
|
||||
@@ -196,13 +187,6 @@ while [ $I -le $LENGTH ]; do
|
||||
;;
|
||||
esac
|
||||
|
||||
while [ $I -le $LENGTH ] && [ $C -gt 0 ]; do
|
||||
C=$((C - 1))
|
||||
I=$((I + 1))
|
||||
set -- "$@" "$1"
|
||||
shift
|
||||
done
|
||||
|
||||
I=$((I + S))
|
||||
shift $S
|
||||
done
|
||||
@@ -220,15 +204,11 @@ 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
|
||||
|
||||
# One MAY change ERTS_BIN= but you MUST NOT change
|
||||
# ERTS_BIN=$ERTS_BIN as it is handled by Elixir releases.
|
||||
ERTS_BIN=
|
||||
ERTS_BIN="$ERTS_BIN"
|
||||
|
||||
set -- "$ERTS_BIN$ERL_EXEC" -pa "$SCRIPT_PATH"/../lib/*/ebin $ELIXIR_ERL_OPTIONS $ERL "$@"
|
||||
|
||||
if [ -n "$RUN_ERL_PIPE" ]; then
|
||||
@@ -246,4 +226,4 @@ if [ -n "$ELIXIR_CLI_DRY_RUN" ]; then
|
||||
echo "$@"
|
||||
else
|
||||
exec "$@"
|
||||
fi
|
||||
fi
|
||||
+11
-40
@@ -1,14 +1,10 @@
|
||||
@if defined ELIXIR_CLI_ECHO (@echo on) else (@echo off)
|
||||
|
||||
set ELIXIR_VERSION=1.14.5
|
||||
|
||||
setlocal enabledelayedexpansion
|
||||
if ""%1""=="""" if ""%2""=="""" goto documentation
|
||||
if /I ""%1""==""--help"" if ""%2""=="""" goto documentation
|
||||
if /I ""%1""==""-h"" if ""%2""=="""" goto documentation
|
||||
if /I ""%1""==""/h"" if ""%2""=="""" goto documentation
|
||||
if ""%1""==""/?"" if ""%2""=="""" goto documentation
|
||||
if /I ""%1""==""--short-version"" if ""%2""=="""" goto shortversion
|
||||
if ""%1""=="""" goto documentation
|
||||
if /I ""%1""==""--help"" goto documentation
|
||||
if /I ""%1""==""-h"" goto documentation
|
||||
if /I ""%1""==""/h"" goto documentation
|
||||
if ""%1""==""/?"" goto documentation
|
||||
goto parseopts
|
||||
|
||||
:documentation
|
||||
@@ -17,13 +13,13 @@ echo.
|
||||
echo ## General options
|
||||
echo.
|
||||
echo -e "COMMAND" Evaluates the given command (*)
|
||||
echo -h, --help Prints this message (standalone)
|
||||
echo -h, --help Prints this message and exits
|
||||
echo -r "FILE" Requires the given files/patterns (*)
|
||||
echo -S SCRIPT Finds and executes the given script in $PATH
|
||||
echo -pr "FILE" Requires the given files/patterns in parallel (*)
|
||||
echo -pa "PATH" Prepends the given path to Erlang code path (*)
|
||||
echo -pz "PATH" Appends the given path to Erlang code path (*)
|
||||
echo -v, --version Prints Erlang/OTP and Elixir versions (standalone)
|
||||
echo -v, --version Prints Elixir version and exits
|
||||
echo.
|
||||
echo --app APP Starts the given app and its dependencies (*)
|
||||
echo --erl "SWITCHES" Switches to be passed down to Erlang (*)
|
||||
@@ -31,7 +27,6 @@ echo --eval "COMMAND" Evaluates the given command, same as -e (*)
|
||||
echo --logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
echo --logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
echo --no-halt Does not halt the Erlang VM after execution
|
||||
echo --short-version Prints Elixir version (standalone)
|
||||
echo --werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
echo.
|
||||
echo Options given after the .exs file or -- are passed down to the executed code.
|
||||
@@ -59,11 +54,6 @@ echo.
|
||||
echo --pipe-to is not supported on Windows. If set, Elixir won't boot.
|
||||
echo.
|
||||
echo ** Options marked with (*) can be given more than once.
|
||||
echo ** Standalone options can't be combined with other options.
|
||||
goto end
|
||||
|
||||
:shortversion
|
||||
echo !ELIXIR_VERSION!
|
||||
goto end
|
||||
|
||||
:parseopts
|
||||
@@ -88,7 +78,6 @@ set SCRIPT_PATH=%~dp0
|
||||
|
||||
rem Designates the path to the ERTS system
|
||||
set ERTS_BIN=
|
||||
set ERTS_BIN=!ERTS_BIN!
|
||||
|
||||
rem Recursive loop called for each parameter that parses the cmd line parameters
|
||||
:startloop
|
||||
@@ -110,21 +99,18 @@ if !par!=="+elixirc" (set parsElixir=!parsElixir! +elixirc && set runMode="elixi
|
||||
rem ******* EVAL PARAMETERS ************************
|
||||
if ""==!par:-e=! (
|
||||
set "VAR=%~1"
|
||||
if not defined VAR (set VAR= )
|
||||
set parsElixir=!parsElixir! -e "!VAR:"=\"!"
|
||||
shift
|
||||
goto startloop
|
||||
)
|
||||
if ""==!par:--eval=! (
|
||||
set "VAR=%~1"
|
||||
if not defined VAR (set VAR= )
|
||||
set parsElixir=!parsElixir! --eval "!VAR:"=\"!"
|
||||
shift
|
||||
goto startloop
|
||||
)
|
||||
if ""==!par:--rpc-eval=! (
|
||||
set "VAR=%~2"
|
||||
if not defined VAR (set VAR= )
|
||||
set parsElixir=!parsElixir! --rpc-eval %1 "!VAR:"=\"!"
|
||||
shift
|
||||
shift
|
||||
@@ -136,12 +122,10 @@ if ""==!par:-pr=! (set "parsElixir=!parsElixir! -pr %1" && shift && goto
|
||||
if ""==!par:-pa=! (set "parsElixir=!parsElixir! -pa %1" && shift && goto startloop)
|
||||
if ""==!par:-pz=! (set "parsElixir=!parsElixir! -pz %1" && shift && goto startloop)
|
||||
if ""==!par:-v=! (set "parsElixir=!parsElixir! -v" && goto startloop)
|
||||
if ""==!par:--version=! (set "parsElixir=!parsElixir! --version" && goto startloop)
|
||||
if ""==!par:--app=! (set "parsElixir=!parsElixir! --app %1" && shift && goto startloop)
|
||||
if ""==!par:--no-halt=! (set "parsElixir=!parsElixir! --no-halt" && goto startloop)
|
||||
if ""==!par:--remsh=! (set "parsElixir=!parsElixir! --remsh %1" && shift && goto startloop)
|
||||
if ""==!par:--dot-iex=! (set "parsElixir=!parsElixir! --dot-iex %1" && shift && goto startloop)
|
||||
if ""==!par:--no-pry=! (set "parsElixir=!parsElixir! --no-pry" && goto startloop)
|
||||
rem ******* ERLANG PARAMETERS **********************
|
||||
if ""==!par:--boot=! (set "parsErlang=!parsErlang! -boot %1" && shift && goto startloop)
|
||||
if ""==!par:--boot-var=! (set "parsErlang=!parsErlang! -boot_var %1 %2" && shift && shift && goto startloop)
|
||||
@@ -168,26 +152,13 @@ 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!
|
||||
)
|
||||
if defined ELIXIR_CLI_DRY_RUN (
|
||||
if defined useWerl (
|
||||
echo start "" "!ERTS_BIN!werl.exe" !ext_libs! !ELIXIR_ERL_OPTIONS! !parsErlang! !beforeExtra! -extra !parsElixir!
|
||||
) else (
|
||||
echo "!ERTS_BIN!erl.exe" !ext_libs! !ELIXIR_ERL_OPTIONS! !parsErlang! !beforeExtra! -extra !parsElixir!
|
||||
)
|
||||
if defined useWerl (
|
||||
start "" "!ERTS_BIN!werl.exe" !ext_libs! !ELIXIR_ERL_OPTIONS! !parsErlang! !beforeExtra! -extra !parsElixir!
|
||||
) else (
|
||||
if defined useWerl (
|
||||
start "" "!ERTS_BIN!werl.exe" !ext_libs! !ELIXIR_ERL_OPTIONS! !parsErlang! !beforeExtra! -extra !parsElixir!
|
||||
) else (
|
||||
"!ERTS_BIN!erl.exe" !ext_libs! !ELIXIR_ERL_OPTIONS! !parsErlang! !beforeExtra! -extra !parsElixir!
|
||||
)
|
||||
"!ERTS_BIN!erl.exe" !ext_libs! !ELIXIR_ERL_OPTIONS! !parsErlang! !beforeExtra! -extra !parsElixir!
|
||||
)
|
||||
exit /B %ERRORLEVEL%
|
||||
:end
|
||||
endlocal
|
||||
endlocal
|
||||
+4
-7
@@ -2,24 +2,21 @@
|
||||
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
|
||||
-v, --version Prints Elixir version and exits (standalone)
|
||||
-v, --version Prints Elixir version and exits
|
||||
|
||||
--ignore-module-conflict Does not emit warnings if a module was previously defined
|
||||
--no-debug-info Does not attach debug info to compiled modules
|
||||
--no-docs Does not attach documentation to compiled modules
|
||||
--profile time Profile the time to compile modules
|
||||
--verbose Prints compilation status
|
||||
--warnings-as-errors Treats warnings as errors and return non-zero exit status
|
||||
--warnings-as-errors Treats warnings as errors and return non-zero exit code
|
||||
|
||||
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
|
||||
|
||||
|
||||
+3
-4
@@ -14,16 +14,15 @@ goto run
|
||||
:documentation
|
||||
echo Usage: %~nx0 [elixir switches] [compiler switches] [.ex files]
|
||||
echo.
|
||||
echo -h, --help Prints this message and exits
|
||||
echo -o The directory to output compiled files
|
||||
echo -v, --version Prints Elixir version and exits (standalone)
|
||||
echo.
|
||||
echo --help, -h Prints this message and exits
|
||||
echo --ignore-module-conflict Does not emit warnings if a module was previously defined
|
||||
echo --no-debug-info Does not attach debug info to compiled modules
|
||||
echo --no-docs Does not attach documentation to compiled modules
|
||||
echo --profile time Profile the time to compile modules
|
||||
echo --verbose Prints compilation status
|
||||
echo --warnings-as-errors Treats warnings as errors and returns non-zero exit status
|
||||
echo --version, -v Prints Elixir version and exits
|
||||
echo --warnings-as-errors Treats warnings as errors and returns non-zero exit code
|
||||
echo.
|
||||
echo ** Options given after -- are passed down to the executed code
|
||||
echo ** Options can be passed to the Erlang runtime using ELIXIR_ERL_OPTIONS
|
||||
|
||||
@@ -2,19 +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 "FILE" Evaluates FILE, line by line, to set up IEx' environment.
|
||||
Defaults to evaluating .iex.exs or ~/.iex.exs, if any exists.
|
||||
If FILE is empty, then no file will be loaded.
|
||||
--remsh NAME Connects to a node using a remote shell.
|
||||
--no-pry Doesn't start pry sessions when dbg/2 is called.
|
||||
--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
|
||||
|
||||
|
||||
+3
-5
@@ -11,19 +11,17 @@ echo Usage: %~nx0 [options] [.exs file] [data]
|
||||
echo.
|
||||
echo The following options are exclusive to IEx:
|
||||
echo.
|
||||
echo --dot-iex "FILE" Evaluates FILE, line by line, to set up IEx' environment.
|
||||
echo Defaults to evaluating .iex.exs or ~/.iex.exs, if any exists.
|
||||
echo If FILE is empty, then no file will be loaded.
|
||||
echo --dot-iex "PATH" Overrides default .iex.exs file and uses path instead;
|
||||
echo path can be empty, then no file will be loaded
|
||||
echo --remsh NAME Connects to a node using a remote shell
|
||||
echo --werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
echo --no-pry Doesn't start pry sessions when dbg/2 is called.
|
||||
echo.
|
||||
echo Set the IEX_WITH_WERL environment variable to always use werl.
|
||||
echo It accepts all other options listed by "elixir --help".
|
||||
goto end
|
||||
|
||||
:run
|
||||
if defined IEX_WITH_WERL (set __ELIXIR_IEX_FLAGS=--werl) else (set __ELIXIR_IEX_FLAGS=)
|
||||
if defined IEX_WITH_WERL (@set __ELIXIR_IEX_FLAGS=--werl) else (set __ELIXIR_IEX_FLAGS=)
|
||||
call "%~dp0\elixir.bat" --no-halt --erl "-noshell -user Elixir.IEx.CLI" +iex %__ELIXIR_IEX_FLAGS% %*
|
||||
:end
|
||||
endlocal
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/usr/bin/env elixir
|
||||
Mix.start()
|
||||
Mix.CLI.main()
|
||||
Mix.start
|
||||
Mix.CLI.main
|
||||
|
||||
+66
-183
@@ -1,81 +1,50 @@
|
||||
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
|
||||
|
||||
defmodule EEx do
|
||||
@moduledoc ~S"""
|
||||
EEx stands for Embedded Elixir.
|
||||
|
||||
Embedded Elixir allows you to embed Elixir code inside a string
|
||||
in a robust way.
|
||||
EEx stands for Embedded Elixir. It allows you to embed
|
||||
Elixir code inside a string in a robust way.
|
||||
|
||||
iex> EEx.eval_string("foo <%= bar %>", bar: "baz")
|
||||
"foo baz"
|
||||
|
||||
This module provides three main APIs for you to use:
|
||||
## API
|
||||
|
||||
1. Evaluate a string (`eval_string/3`) or a file (`eval_file/3`)
|
||||
This module provides 3 main APIs for you to use:
|
||||
|
||||
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 at runtime and not precompiled.
|
||||
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.
|
||||
|
||||
The APIs above support several options, documented below. You may
|
||||
also pass an engine which customizes how the EEx code is compiled.
|
||||
|
||||
## Options
|
||||
|
||||
All functions in this module, unless otherwise noted, accept EEx-related
|
||||
options. They are:
|
||||
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`.
|
||||
|
||||
file the template is read from or to "nofile" when compiling from a string.
|
||||
* `:engine` - the EEx engine to be used for compilation.
|
||||
|
||||
* `:trim` - if `true`, trims whitespace left and right of quotation as
|
||||
long as at least one newline is present. All subsequent newlines and
|
||||
spaces are removed but one newline is retained. Defaults to `false`.
|
||||
|
||||
* `:parser_options` - (since: 1.13.0) allow customizing the parsed code
|
||||
that is generated. See `Code.string_to_quoted/2` for available options.
|
||||
Note that the options `:file`, `:line` and `:column` are ignored if
|
||||
passed in. Defaults to `Code.get_compiler_option(:parser_options)`
|
||||
(which defaults to `[]` if not set).
|
||||
|
||||
## Tags
|
||||
|
||||
EEx supports multiple tags, declared below:
|
||||
|
||||
<% Elixir expression: executes code but discards output %>
|
||||
<%= Elixir expression: executes code and prints result %>
|
||||
<%% EEx quotation: returns the contents inside the tag as is %>
|
||||
<%!-- Comments: they are discarded from source --%>
|
||||
|
||||
EEx supports additional tags, that may be used by some engines,
|
||||
but they do not have a meaning by default:
|
||||
|
||||
<%| ... %>
|
||||
<%/ ... %>
|
||||
* `: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
|
||||
|
||||
@@ -85,10 +54,36 @@ defmodule EEx do
|
||||
By default, `EEx` uses the `EEx.SmartEngine` that provides some
|
||||
conveniences on top of the simple `EEx.Engine`.
|
||||
|
||||
### `EEx.SmartEngine`
|
||||
### Tags
|
||||
|
||||
The smart engine uses EEx default rules and adds the `@` construct
|
||||
for reading template assigns:
|
||||
`EEx.SmartEngine` supports the following tags:
|
||||
|
||||
<% Elixir expression - inline with output %>
|
||||
<%= Elixir expression - replace with result %>
|
||||
<%% EEx quotation - returns the contents inside %>
|
||||
<%# Comments - they are discarded from source %>
|
||||
|
||||
All expressions that output something to the template
|
||||
**must** use the equals sign (`=`). Since everything in
|
||||
Elixir is an expression, there are no exceptions for this rule.
|
||||
For example, while some template languages would special-case
|
||||
`if/2` clauses, they are treated the same in EEx and
|
||||
also require `=` in order to have their result printed:
|
||||
|
||||
<%= if true do %>
|
||||
It is obviously true
|
||||
<% else %>
|
||||
This will never appear
|
||||
<% end %>
|
||||
|
||||
Notice that different engines may have different rules
|
||||
for each tag. Other tags may be added in future versions.
|
||||
|
||||
### Macros
|
||||
|
||||
`EEx.SmartEngine` also adds some macros to your template.
|
||||
An example is the `@` macro which allows easy data access
|
||||
in a template:
|
||||
|
||||
iex> EEx.eval_string("<%= @foo %>", assigns: [foo: 1])
|
||||
"1"
|
||||
@@ -101,26 +96,11 @@ defmodule EEx do
|
||||
required by the template is not specified at compilation time.
|
||||
"""
|
||||
|
||||
@type line :: non_neg_integer
|
||||
@type column :: non_neg_integer
|
||||
@type marker :: '=' | '/' | '|' | ''
|
||||
@type metadata :: %{column: column, line: line}
|
||||
@type token ::
|
||||
{:comment, charlist, metadata}
|
||||
| {:text, charlist, metadata}
|
||||
| {:expr | :start_expr | :middle_expr | :end_expr, marker, charlist, metadata}
|
||||
| {:eof, metadata}
|
||||
|
||||
@doc """
|
||||
Generates a function definition from the given string.
|
||||
Generates a function definition from the string.
|
||||
|
||||
The first argument is the kind of the generated function (`:def` or `:defp`).
|
||||
The `name` argument is the name that the generated function will have.
|
||||
`template` is the string containing the EEx template. `args` is a list of arguments
|
||||
that the generated function will accept. They will be available inside the EEx
|
||||
template.
|
||||
|
||||
The supported `options` are described [in the module docs](#module-options).
|
||||
The kind (`:def` or `:defp`) must be given, the
|
||||
function name, its arguments and the compilation options.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -132,11 +112,11 @@ defmodule EEx do
|
||||
"3"
|
||||
|
||||
"""
|
||||
defmacro function_from_string(kind, name, template, args \\ [], options \\ []) do
|
||||
defmacro function_from_string(kind, name, source, args \\ [], options \\ []) do
|
||||
quote bind_quoted: binding() do
|
||||
info = Keyword.merge([file: __ENV__.file, line: __ENV__.line], options)
|
||||
args = Enum.map(args, fn arg -> {arg, [line: info[:line]], nil} end)
|
||||
compiled = EEx.compile_string(template, info)
|
||||
compiled = EEx.compile_string(source, info)
|
||||
|
||||
case kind do
|
||||
:def -> def unquote(name)(unquote_splicing(args)), do: unquote(compiled)
|
||||
@@ -148,17 +128,12 @@ defmodule EEx do
|
||||
@doc """
|
||||
Generates a function definition from the file contents.
|
||||
|
||||
The first argument is the kind of the generated function (`:def` or `:defp`).
|
||||
The `name` argument is the name that the generated function will have.
|
||||
`file` is the path to the EEx template file. `args` is a list of arguments
|
||||
that the generated function will accept. They will be available inside the EEx
|
||||
template.
|
||||
The kind (`:def` or `:defp`) must be given, the
|
||||
function name, its arguments and the compilation options.
|
||||
|
||||
This function is useful in case you have templates but
|
||||
you want to precompile inside a module for speed.
|
||||
|
||||
The supported `options` are described [in the module docs](#module-options).
|
||||
|
||||
## Examples
|
||||
|
||||
# sample.eex
|
||||
@@ -177,7 +152,7 @@ defmodule EEx do
|
||||
"""
|
||||
defmacro function_from_file(kind, name, file, args \\ [], options \\ []) do
|
||||
quote bind_quoted: binding() do
|
||||
info = Keyword.merge([file: IO.chardata_to_string(file), line: 1], options)
|
||||
info = Keyword.merge(options, file: file, line: 1)
|
||||
args = Enum.map(args, fn arg -> {arg, [line: 1], nil} end)
|
||||
compiled = EEx.compile_file(file, info)
|
||||
|
||||
@@ -191,86 +166,34 @@ defmodule EEx do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a string `source` and generates a quoted expression
|
||||
Gets a string `source` and generate a quoted expression
|
||||
that can be evaluated by Elixir or compiled to a function.
|
||||
|
||||
This is useful if you want to compile a EEx template into code and inject
|
||||
that code somewhere or evaluate it at runtime.
|
||||
|
||||
The generated quoted code will use variables defined in the template that
|
||||
will be taken from the context where the code is evaluated. If you
|
||||
have a template such as `<%= a + b %>`, then the returned quoted code
|
||||
will use the `a` and `b` variables in the context where it's evaluated. See
|
||||
examples below.
|
||||
|
||||
The supported `options` are described [in the module docs](#module-options).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> quoted = EEx.compile_string("<%= a + b %>")
|
||||
iex> {result, _bindings} = Code.eval_quoted(quoted, a: 1, b: 2)
|
||||
iex> result
|
||||
"3"
|
||||
|
||||
"""
|
||||
@spec compile_string(String.t(), keyword) :: Macro.t()
|
||||
def compile_string(source, options \\ []) when is_binary(source) and is_list(options) do
|
||||
case tokenize(source, options) do
|
||||
{:ok, tokens} ->
|
||||
EEx.Compiler.compile(tokens, options)
|
||||
|
||||
{:error, message, %{column: column, line: line}} ->
|
||||
file = options[:file] || "nofile"
|
||||
raise EEx.SyntaxError, file: file, line: line, column: column, message: message
|
||||
end
|
||||
EEx.Compiler.compile(source, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a `filename` and generates a quoted expression
|
||||
Gets a `filename` and generate a quoted expression
|
||||
that can be evaluated by Elixir or compiled to a function.
|
||||
|
||||
This is useful if you want to compile a EEx template into code and inject
|
||||
that code somewhere or evaluate it at runtime.
|
||||
|
||||
The generated quoted code will use variables defined in the template that
|
||||
will be taken from the context where the code is evaluated. If you
|
||||
have a template such as `<%= a + b %>`, then the returned quoted code
|
||||
will use the `a` and `b` variables in the context where it's evaluated. See
|
||||
examples below.
|
||||
|
||||
The supported `options` are described [in the module docs](#module-options).
|
||||
|
||||
## Examples
|
||||
|
||||
# sample.eex
|
||||
<%= a + b %>
|
||||
|
||||
# In code:
|
||||
quoted = EEx.compile_file("sample.eex")
|
||||
{result, _bindings} = Code.eval_quoted(quoted, a: 1, b: 2)
|
||||
result
|
||||
#=> "3"
|
||||
|
||||
"""
|
||||
@spec compile_file(Path.t(), keyword) :: Macro.t()
|
||||
def compile_file(filename, options \\ []) when is_list(options) do
|
||||
filename = IO.chardata_to_string(filename)
|
||||
options = Keyword.merge([file: filename, line: 1], options)
|
||||
@spec compile_file(String.t(), keyword) :: Macro.t()
|
||||
def compile_file(filename, options \\ []) when is_binary(filename) and is_list(options) do
|
||||
options = Keyword.merge(options, file: filename, line: 1)
|
||||
compile_string(File.read!(filename), options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a string `source` and evaluate the values using the `bindings`.
|
||||
|
||||
The supported `options` are described [in the module docs](#module-options).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> EEx.eval_string("foo <%= bar %>", bar: "baz")
|
||||
"foo baz"
|
||||
|
||||
"""
|
||||
@spec eval_string(String.t(), keyword, keyword) :: String.t()
|
||||
@spec eval_string(String.t(), keyword, keyword) :: any
|
||||
def eval_string(source, bindings \\ [], options \\ [])
|
||||
when is_binary(source) and is_list(bindings) and is_list(options) do
|
||||
compiled = compile_string(source, options)
|
||||
@@ -280,64 +203,24 @@ defmodule EEx do
|
||||
@doc """
|
||||
Gets a `filename` and evaluate the values using the `bindings`.
|
||||
|
||||
The supported `options` are described [in the module docs](#module-options).
|
||||
|
||||
## Examples
|
||||
|
||||
# sample.eex
|
||||
foo <%= bar %>
|
||||
|
||||
# IEx
|
||||
# iex
|
||||
EEx.eval_file("sample.eex", bar: "baz")
|
||||
#=> "foo baz"
|
||||
|
||||
"""
|
||||
@spec eval_file(Path.t(), keyword, keyword) :: String.t()
|
||||
@spec eval_file(String.t(), keyword, keyword) :: any
|
||||
def eval_file(filename, bindings \\ [], options \\ [])
|
||||
when is_list(bindings) and is_list(options) do
|
||||
filename = IO.chardata_to_string(filename)
|
||||
options = Keyword.put_new(options, :file, filename)
|
||||
when is_binary(filename) and is_list(bindings) and is_list(options) do
|
||||
options = Keyword.put(options, :file, filename)
|
||||
compiled = compile_file(filename, options)
|
||||
do_eval(compiled, bindings, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Tokenize the given contents according to the given options.
|
||||
|
||||
## Options
|
||||
|
||||
* `:line` - An integer to start as line. Default is 1.
|
||||
* `:column` - An integer to start as column. Default is 1.
|
||||
* `:indentation` - An integer that indicates the indentation. Default is 0.
|
||||
* `:trim` - Tells the tokenizer to either trim the content or not. Default is false.
|
||||
* `:file` - Can be either a file or a string "nofile".
|
||||
|
||||
## Examples
|
||||
|
||||
iex> EEx.tokenize('foo', line: 1, column: 1)
|
||||
{:ok, [{:text, 'foo', %{column: 1, line: 1}}, {:eof, %{column: 4, line: 1}}]}
|
||||
|
||||
## Result
|
||||
|
||||
It returns `{:ok, [token]}` where a token is one of:
|
||||
|
||||
* `{:text, content, %{column: column, line: line}}`
|
||||
* `{:expr, marker, content, %{column: column, line: line}}`
|
||||
* `{:start_expr, marker, content, %{column: column, line: line}}`
|
||||
* `{:middle_expr, marker, content, %{column: column, line: line}}`
|
||||
* `{:end_expr, marker, content, %{column: column, line: line}}`
|
||||
* `{:eof, %{column: column, line: line}}`
|
||||
|
||||
Or `{:error, message, %{column: column, line: line}}` in case of errors.
|
||||
Note new tokens may be added in the future.
|
||||
"""
|
||||
@doc since: "1.14.0"
|
||||
@spec tokenize(IO.chardata(), opts :: keyword) ::
|
||||
{:ok, [token()]} | {:error, String.t(), metadata()}
|
||||
def tokenize(contents, opts \\ []) do
|
||||
EEx.Compiler.tokenize(contents, opts)
|
||||
end
|
||||
|
||||
### Helpers
|
||||
|
||||
defp do_eval(compiled, bindings, options) do
|
||||
|
||||
+82
-363
@@ -3,358 +3,59 @@ defmodule EEx.Compiler do
|
||||
|
||||
# When changing this setting, don't forget to update the docs for EEx
|
||||
@default_engine EEx.SmartEngine
|
||||
@h_spaces [?\s, ?\t]
|
||||
@all_spaces [?\s, ?\t, ?\n, ?\r]
|
||||
|
||||
@doc """
|
||||
Tokenize EEx contents.
|
||||
"""
|
||||
def tokenize(contents, opts) when is_binary(contents) do
|
||||
tokenize(String.to_charlist(contents), opts)
|
||||
end
|
||||
|
||||
def tokenize(contents, opts) when is_list(contents) do
|
||||
file = opts[:file] || "nofile"
|
||||
line = opts[:line] || 1
|
||||
trim = opts[:trim] || false
|
||||
indentation = opts[:indentation] || 0
|
||||
column = indentation + (opts[:column] || 1)
|
||||
|
||||
state = %{trim: trim, indentation: indentation, file: file}
|
||||
|
||||
{contents, line, column} =
|
||||
(trim && trim_init(contents, line, column, state)) || {contents, line, column}
|
||||
|
||||
tokenize(contents, line, column, state, [{line, column}], [])
|
||||
end
|
||||
|
||||
defp tokenize('<%%' ++ t, line, column, state, buffer, acc) do
|
||||
tokenize(t, line, column + 3, state, [?%, ?< | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize('<%!--' ++ t, line, column, state, buffer, acc) do
|
||||
case comment(t, line, column + 5, state, []) do
|
||||
{:error, line, column, message} ->
|
||||
{:error, message, %{line: line, column: column}}
|
||||
|
||||
{:ok, new_line, new_column, rest, comments} ->
|
||||
token = {:comment, Enum.reverse(comments), %{line: line, column: column}}
|
||||
trim_and_tokenize(rest, new_line, new_column, state, buffer, acc, &[token | &1])
|
||||
end
|
||||
end
|
||||
|
||||
# TODO: Deprecate this on Elixir v1.18
|
||||
defp tokenize('<%#' ++ t, line, column, state, buffer, acc) do
|
||||
case expr(t, line, column + 3, state, []) do
|
||||
{:error, line, column, message} ->
|
||||
{:error, message, %{line: line, column: column}}
|
||||
|
||||
{:ok, _, new_line, new_column, rest} ->
|
||||
trim_and_tokenize(rest, new_line, new_column, state, buffer, acc, & &1)
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('<%' ++ t, line, column, state, buffer, acc) do
|
||||
{marker, t} = retrieve_marker(t)
|
||||
|
||||
case expr(t, line, column + 2 + length(marker), state, []) do
|
||||
{:error, line, column, message} ->
|
||||
{:error, message, %{line: line, column: column}}
|
||||
|
||||
{:ok, expr, new_line, new_column, rest} ->
|
||||
{key, expr} =
|
||||
case :elixir_tokenizer.tokenize(expr, 1, file: "eex", check_terminators: false) do
|
||||
{:ok, _line, _column, warnings, tokens} ->
|
||||
Enum.each(Enum.reverse(warnings), fn {location, file, msg} ->
|
||||
:elixir_errors.erl_warn(location, file, msg)
|
||||
end)
|
||||
|
||||
token_key(tokens, expr)
|
||||
|
||||
{:error, _, _, _, _} ->
|
||||
{:expr, expr}
|
||||
end
|
||||
|
||||
marker =
|
||||
if key in [:middle_expr, :end_expr] and marker != '' do
|
||||
message =
|
||||
"unexpected beginning of EEx tag \"<%#{marker}\" on \"<%#{marker}#{expr}%>\", " <>
|
||||
"please remove \"#{marker}\""
|
||||
|
||||
:elixir_errors.erl_warn({line, column}, state.file, message)
|
||||
''
|
||||
else
|
||||
marker
|
||||
end
|
||||
|
||||
token = {key, marker, expr, %{line: line, column: column}}
|
||||
trim_and_tokenize(rest, new_line, new_column, state, buffer, acc, &[token | &1])
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('\n' ++ t, line, _column, state, buffer, acc) do
|
||||
tokenize(t, line + 1, state.indentation + 1, state, [?\n | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize([h | t], line, column, state, buffer, acc) do
|
||||
tokenize(t, line, column + 1, state, [h | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize([], line, column, _state, buffer, acc) do
|
||||
eof = {:eof, %{line: line, column: column}}
|
||||
{:ok, Enum.reverse([eof | tokenize_text(buffer, acc)])}
|
||||
end
|
||||
|
||||
defp trim_and_tokenize(rest, line, column, state, buffer, acc, fun) do
|
||||
{rest, line, column, buffer} = trim_if_needed(rest, line, column, state, buffer)
|
||||
|
||||
acc = tokenize_text(buffer, acc)
|
||||
tokenize(rest, line, column, state, [{line, column}], fun.(acc))
|
||||
end
|
||||
|
||||
# Retrieve marker for <%
|
||||
|
||||
defp retrieve_marker([marker | t]) when marker in [?=, ?/, ?|] do
|
||||
{[marker], t}
|
||||
end
|
||||
|
||||
defp retrieve_marker(t) do
|
||||
{'', t}
|
||||
end
|
||||
|
||||
# Tokenize a multi-line comment until we find --%>
|
||||
|
||||
defp comment([?-, ?-, ?%, ?> | t], line, column, _state, buffer) do
|
||||
{:ok, line, column + 4, t, buffer}
|
||||
end
|
||||
|
||||
defp comment('\n' ++ t, line, _column, state, buffer) do
|
||||
comment(t, line + 1, state.indentation + 1, state, '\n' ++ buffer)
|
||||
end
|
||||
|
||||
defp comment([head | t], line, column, state, buffer) do
|
||||
comment(t, line, column + 1, state, [head | buffer])
|
||||
end
|
||||
|
||||
defp comment([], line, column, _state, _buffer) do
|
||||
{:error, line, column, "missing token '--%>'"}
|
||||
end
|
||||
|
||||
# Tokenize an expression until we find %>
|
||||
|
||||
defp expr([?%, ?> | t], line, column, _state, buffer) do
|
||||
{:ok, Enum.reverse(buffer), line, column + 2, t}
|
||||
end
|
||||
|
||||
defp expr('\n' ++ t, line, _column, state, buffer) do
|
||||
expr(t, line + 1, state.indentation + 1, state, [?\n | buffer])
|
||||
end
|
||||
|
||||
defp expr([h | t], line, column, state, buffer) do
|
||||
expr(t, line, column + 1, state, [h | buffer])
|
||||
end
|
||||
|
||||
defp expr([], line, column, _state, _buffer) do
|
||||
{:error, line, column, "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, tokens |> Enum.reverse() |> drop_eol()} do
|
||||
{[{:end, _} | _], [{:do, _} | _]} ->
|
||||
{:middle_expr, expr}
|
||||
|
||||
{_, [{:do, _} | _]} ->
|
||||
{:start_expr, maybe_append_space(expr)}
|
||||
|
||||
{_, [{: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
|
||||
end
|
||||
end
|
||||
|
||||
defp drop_eol([{:eol, _} | rest]), do: drop_eol(rest)
|
||||
defp drop_eol(rest), do: rest
|
||||
|
||||
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 closing_bracket?({closing, _}) when closing in ~w"( [ {"a, do: true
|
||||
defp closing_bracket?(_), do: false
|
||||
|
||||
# Tokenize the buffered text by appending
|
||||
# it to the given accumulator.
|
||||
|
||||
defp tokenize_text([{_line, _column}], acc) do
|
||||
acc
|
||||
end
|
||||
|
||||
defp tokenize_text(buffer, acc) do
|
||||
[{line, column} | buffer] = Enum.reverse(buffer)
|
||||
[{:text, buffer, %{line: line, column: column}} | acc]
|
||||
end
|
||||
|
||||
## Trim
|
||||
|
||||
defp trim_if_needed(rest, line, column, state, buffer) do
|
||||
if state.trim do
|
||||
buffer = trim_left(buffer, 0)
|
||||
{rest, line, column} = trim_right(rest, line, column, 0, state)
|
||||
{rest, line, column, buffer}
|
||||
else
|
||||
{rest, line, column, buffer}
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_init([h | t], line, column, state) when h in @h_spaces,
|
||||
do: trim_init(t, line, column + 1, state)
|
||||
|
||||
defp trim_init([?\r, ?\n | t], line, _column, state),
|
||||
do: trim_init(t, line + 1, state.indentation + 1, state)
|
||||
|
||||
defp trim_init([?\n | t], line, _column, state),
|
||||
do: trim_init(t, line + 1, state.indentation + 1, state)
|
||||
|
||||
defp trim_init([?<, ?% | _] = rest, line, column, _state),
|
||||
do: {rest, line, column}
|
||||
|
||||
defp trim_init(_, _, _, _), do: false
|
||||
|
||||
defp trim_left(buffer, count) do
|
||||
case trim_whitespace(buffer, 0) do
|
||||
{[?\n, ?\r | rest], _} -> trim_left(rest, count + 1)
|
||||
{[?\n | rest], _} -> trim_left(rest, count + 1)
|
||||
_ when count > 0 -> [?\n | buffer]
|
||||
_ -> buffer
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_right(rest, line, column, last_column, state) do
|
||||
case trim_whitespace(rest, column) do
|
||||
{[?\r, ?\n | rest], column} ->
|
||||
trim_right(rest, line + 1, state.indentation + 1, column + 1, state)
|
||||
|
||||
{[?\n | rest], column} ->
|
||||
trim_right(rest, line + 1, state.indentation + 1, column, state)
|
||||
|
||||
{[], column} ->
|
||||
{[], line, column}
|
||||
|
||||
_ when last_column > 0 ->
|
||||
{[?\n | rest], line - 1, last_column}
|
||||
|
||||
_ ->
|
||||
{rest, line, column}
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_whitespace([h | t], column) when h in @h_spaces, do: trim_whitespace(t, column + 1)
|
||||
defp trim_whitespace(list, column), do: {list, column}
|
||||
|
||||
@doc """
|
||||
This is the compilation entry point. It glues the tokenizer
|
||||
and the engine together by handling the tokens and invoking
|
||||
the engine every time a full expression or text is received.
|
||||
"""
|
||||
@spec compile([EEx.token()], keyword) :: Macro.t()
|
||||
def compile(tokens, opts) do
|
||||
@spec compile(String.t(), keyword) :: Macro.t()
|
||||
def compile(source, opts) when is_binary(source) and is_list(opts) do
|
||||
file = opts[:file] || "nofile"
|
||||
line = opts[:line] || 1
|
||||
parser_options = opts[:parser_options] || Code.get_compiler_option(:parser_options)
|
||||
engine = opts[:engine] || @default_engine
|
||||
trim = opts[:trim] || false
|
||||
|
||||
state = %{
|
||||
engine: engine,
|
||||
file: file,
|
||||
line: line,
|
||||
quoted: [],
|
||||
start_line: nil,
|
||||
start_column: nil,
|
||||
parser_options: parser_options
|
||||
}
|
||||
case EEx.Tokenizer.tokenize(source, line, trim: trim) do
|
||||
{:ok, tokens} ->
|
||||
state = %{
|
||||
engine: opts[:engine] || @default_engine,
|
||||
file: file,
|
||||
line: line,
|
||||
quoted: [],
|
||||
start_line: nil
|
||||
}
|
||||
|
||||
init = state.engine.init(opts)
|
||||
generate_buffer(tokens, init, [], state)
|
||||
end
|
||||
init = state.engine.init(opts)
|
||||
generate_buffer(tokens, init, [], state)
|
||||
|
||||
# Ignore tokens related to comment.
|
||||
defp generate_buffer([{:comment, _chars, _meta} | rest], buffer, scope, state) do
|
||||
generate_buffer(rest, buffer, scope, state)
|
||||
{:error, line, message} ->
|
||||
raise EEx.SyntaxError, line: line, file: file, message: message
|
||||
end
|
||||
end
|
||||
|
||||
# Generates the buffers by handling each expression from the tokenizer.
|
||||
# It returns Macro.t/0 or it raises.
|
||||
|
||||
defp generate_buffer([{:text, chars, meta} | rest], buffer, scope, state) do
|
||||
buffer =
|
||||
if function_exported?(state.engine, :handle_text, 3) do
|
||||
meta = [line: meta.line, column: meta.column]
|
||||
state.engine.handle_text(buffer, meta, IO.chardata_to_string(chars))
|
||||
else
|
||||
# TODO: Deprecate this branch on Elixir v1.18.
|
||||
# We should most likely move this check to init to emit the deprecation once.
|
||||
state.engine.handle_text(buffer, IO.chardata_to_string(chars))
|
||||
end
|
||||
|
||||
defp generate_buffer([{:text, chars} | rest], buffer, scope, state) do
|
||||
buffer = state.engine.handle_text(buffer, IO.chardata_to_string(chars))
|
||||
generate_buffer(rest, buffer, scope, state)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:expr, mark, chars, meta} | rest], buffer, scope, state) do
|
||||
options =
|
||||
[file: state.file, line: meta.line, column: column(meta.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, mark, chars, meta} | rest],
|
||||
buffer,
|
||||
scope,
|
||||
state
|
||||
) do
|
||||
if mark == '' do
|
||||
message =
|
||||
"the contents of this expression won't be output unless the EEx block starts with \"<%=\""
|
||||
|
||||
:elixir_errors.erl_warn({meta.line, meta.column}, state.file, message)
|
||||
end
|
||||
|
||||
{rest, line, contents} = look_ahead_middle(rest, meta.line, chars) || {rest, meta.line, chars}
|
||||
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} =
|
||||
generate_buffer(
|
||||
rest,
|
||||
state.engine.handle_begin(buffer),
|
||||
[contents | scope],
|
||||
%{
|
||||
state
|
||||
| quoted: [],
|
||||
line: line,
|
||||
start_line: meta.line,
|
||||
start_column: column(meta.column, mark)
|
||||
}
|
||||
%{state | quoted: [], line: line, start_line: start_line}
|
||||
)
|
||||
|
||||
buffer = state.engine.handle_expr(buffer, IO.chardata_to_string(mark), contents)
|
||||
@@ -362,56 +63,78 @@ defmodule EEx.Compiler do
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:middle_expr, '', chars, meta} | rest],
|
||||
[{:middle_expr, line, '', chars, _} | rest],
|
||||
buffer,
|
||||
[current | scope],
|
||||
state
|
||||
) do
|
||||
{wrapped, state} = wrap_expr(current, meta.line, buffer, chars, state)
|
||||
state = %{state | line: meta.line}
|
||||
{wrapped, state} = wrap_expr(current, line, buffer, chars, state)
|
||||
state = %{state | line: line}
|
||||
generate_buffer(rest, state.engine.handle_begin(buffer), [wrapped | scope], state)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:middle_expr, _, chars, meta} | _], _buffer, [], state) do
|
||||
defp generate_buffer(
|
||||
[{:middle_expr, line, modifier, chars, trimmed?} | t],
|
||||
buffer,
|
||||
[_ | _] = scope,
|
||||
state
|
||||
) do
|
||||
message =
|
||||
"unexpected beginning of EEx tag \"<%#{modifier}\" on \"<%#{modifier}#{chars}%>\", " <>
|
||||
"please remove \"#{modifier}\" accordingly"
|
||||
|
||||
:elixir_errors.erl_warn(line, state.file, message)
|
||||
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, _, chars, _} | _], _buffer, [], state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected middle of expression <%#{chars}%>",
|
||||
file: state.file,
|
||||
line: meta.line,
|
||||
column: meta.column
|
||||
line: line
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:end_expr, '', chars, meta} | rest],
|
||||
buffer,
|
||||
[current | _],
|
||||
state
|
||||
) do
|
||||
{wrapped, state} = wrap_expr(current, meta.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)
|
||||
defp generate_buffer([{:end_expr, line, '', chars, _} | rest], buffer, [current | _], state) do
|
||||
{wrapped, state} = wrap_expr(current, line, buffer, chars, state)
|
||||
tuples = Code.string_to_quoted!(wrapped, line: state.start_line, file: state.file)
|
||||
buffer = insert_quoted(tuples, state.quoted)
|
||||
{buffer, rest}
|
||||
end
|
||||
|
||||
defp generate_buffer([{:end_expr, _, chars, meta} | _], _buffer, [], state) do
|
||||
defp generate_buffer(
|
||||
[{:end_expr, line, modifier, chars, trimmed?} | t],
|
||||
buffer,
|
||||
[_ | _] = scope,
|
||||
state
|
||||
) do
|
||||
message =
|
||||
"unexpected beginning of EEx tag \"<%#{modifier}\" on end of " <>
|
||||
"expression \"<%#{modifier}#{chars}%>\", please remove \"#{modifier}\" accordingly"
|
||||
|
||||
:elixir_errors.erl_warn(line, state.file, message)
|
||||
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
|
||||
end
|
||||
|
||||
defp generate_buffer([{:end_expr, line, _, chars, _} | _], _buffer, [], state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected end of expression <%#{chars}%>",
|
||||
file: state.file,
|
||||
line: meta.line,
|
||||
column: meta.column
|
||||
line: line
|
||||
end
|
||||
|
||||
defp generate_buffer([{:eof, _meta}], buffer, [], state) do
|
||||
defp generate_buffer([], buffer, [], state) do
|
||||
state.engine.handle_body(buffer)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:eof, meta}], _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: meta.line,
|
||||
column: meta.column
|
||||
line: state.line
|
||||
end
|
||||
|
||||
# Creates a placeholder and wrap it inside the expression block
|
||||
@@ -426,29 +149,30 @@ 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([{:comment, _comment, _meta} | rest], start, contents),
|
||||
do: look_ahead_middle(rest, start, contents)
|
||||
|
||||
defp look_ahead_middle([{:text, text, _meta} | rest], start, contents) do
|
||||
defp look_ahead_middle(
|
||||
[{:text, text}, {:middle_expr, line, _, chars, _} | rest] = tokens,
|
||||
start,
|
||||
contents
|
||||
) do
|
||||
if only_spaces?(text) do
|
||||
look_ahead_middle(rest, start, contents ++ text)
|
||||
{contents ++ text ++ chars, line, rest}
|
||||
else
|
||||
nil
|
||||
{contents, start, tokens}
|
||||
end
|
||||
end
|
||||
|
||||
defp look_ahead_middle([{:middle_expr, _, chars, meta} | rest], _start, contents) do
|
||||
{rest, meta.line, contents ++ chars}
|
||||
defp look_ahead_middle([{:middle_expr, line, _, chars, _} | rest], _start, contents) do
|
||||
{contents ++ chars, line, rest}
|
||||
end
|
||||
|
||||
defp look_ahead_middle(_tokens, _start, _contents) do
|
||||
nil
|
||||
defp look_ahead_middle(tokens, start, contents) do
|
||||
{contents, start, tokens}
|
||||
end
|
||||
|
||||
defp only_spaces?(chars) do
|
||||
Enum.all?(chars, &(&1 in @all_spaces))
|
||||
Enum.all?(chars, &(&1 in [?\s, ?\t, ?\r, ?\n]))
|
||||
end
|
||||
|
||||
# Changes placeholder to real expression
|
||||
@@ -473,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
|
||||
|
||||
+13
-15
@@ -4,8 +4,10 @@ defmodule EEx.Engine do
|
||||
|
||||
An engine needs to implement all callbacks below.
|
||||
|
||||
This module also ships with a default engine implementation
|
||||
you can delegate to. See `EEx.SmartEngine` as an example.
|
||||
An engine may also `use EEx.Engine` to get the default behaviour
|
||||
but this is not advised. In such cases, if any of the callbacks
|
||||
are overridden, they must call `super()` to delegate to the
|
||||
underlying `EEx.Engine`.
|
||||
"""
|
||||
|
||||
@type state :: term
|
||||
@@ -29,8 +31,7 @@ defmodule EEx.Engine do
|
||||
|
||||
It must return the updated state.
|
||||
"""
|
||||
@callback handle_text(state, [line: pos_integer, column: pos_integer], text :: String.t()) ::
|
||||
state
|
||||
@callback handle_text(state, text :: String.t()) :: state
|
||||
|
||||
@doc """
|
||||
Called for the dynamic/code parts of a template.
|
||||
@@ -68,7 +69,6 @@ defmodule EEx.Engine do
|
||||
@callback handle_end(state) :: Macro.t()
|
||||
|
||||
@doc false
|
||||
@deprecated "Use explicit delegation to EEx.Engine instead"
|
||||
defmacro __using__(_) do
|
||||
quote do
|
||||
@behaviour EEx.Engine
|
||||
@@ -90,7 +90,7 @@ defmodule EEx.Engine do
|
||||
end
|
||||
|
||||
def handle_text(state, text) do
|
||||
EEx.Engine.handle_text(state, [], text)
|
||||
EEx.Engine.handle_text(state, text)
|
||||
end
|
||||
|
||||
def handle_expr(state, marker, expr) do
|
||||
@@ -147,7 +147,7 @@ defmodule EEx.Engine do
|
||||
end
|
||||
end
|
||||
|
||||
@doc "Default implementation for `c:init/1`."
|
||||
@doc false
|
||||
def init(_opts) do
|
||||
%{
|
||||
binary: [],
|
||||
@@ -156,18 +156,18 @@ defmodule EEx.Engine do
|
||||
}
|
||||
end
|
||||
|
||||
@doc "Default implementation for `c:handle_begin/1`."
|
||||
@doc false
|
||||
def handle_begin(state) do
|
||||
check_state!(state)
|
||||
%{state | binary: [], dynamic: []}
|
||||
end
|
||||
|
||||
@doc "Default implementation for `c:handle_end/1`."
|
||||
@doc false
|
||||
def handle_end(quoted) do
|
||||
handle_body(quoted)
|
||||
end
|
||||
|
||||
@doc "Default implementation for `c:handle_body/1`."
|
||||
@doc false
|
||||
def handle_body(state) do
|
||||
check_state!(state)
|
||||
%{binary: binary, dynamic: dynamic} = state
|
||||
@@ -176,16 +176,14 @@ defmodule EEx.Engine do
|
||||
{:__block__, [], Enum.reverse(dynamic)}
|
||||
end
|
||||
|
||||
@doc "Default implementation for `c:handle_text/3`."
|
||||
def handle_text(state, _meta, text) do
|
||||
check_state!(state)
|
||||
@doc false
|
||||
def handle_text(state, text) do
|
||||
%{binary: binary} = state
|
||||
%{state | binary: [text | binary]}
|
||||
end
|
||||
|
||||
@doc "Default implementation for `c:handle_expr/3`."
|
||||
@doc false
|
||||
def handle_expr(state, "=", ast) do
|
||||
check_state!(state)
|
||||
%{binary: binary, dynamic: dynamic, vars_count: vars_count} = state
|
||||
var = Macro.var(:"arg#{vars_count}", __MODULE__)
|
||||
|
||||
|
||||
@@ -33,26 +33,10 @@ defmodule EEx.SmartEngine do
|
||||
|
||||
"""
|
||||
|
||||
@behaviour EEx.Engine
|
||||
use EEx.Engine
|
||||
|
||||
@impl true
|
||||
defdelegate init(opts), to: EEx.Engine
|
||||
|
||||
@impl true
|
||||
defdelegate handle_body(state), to: EEx.Engine
|
||||
|
||||
@impl true
|
||||
defdelegate handle_begin(state), to: EEx.Engine
|
||||
|
||||
@impl true
|
||||
defdelegate handle_end(state), to: EEx.Engine
|
||||
|
||||
@impl true
|
||||
defdelegate handle_text(state, meta, text), to: EEx.Engine
|
||||
|
||||
@impl true
|
||||
def handle_expr(state, marker, expr) do
|
||||
def handle_expr(buffer, mark, expr) do
|
||||
expr = Macro.prewalk(expr, &EEx.Engine.handle_assign/1)
|
||||
EEx.Engine.handle_expr(state, marker, expr)
|
||||
super(buffer, mark, expr)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
defmodule EEx.Tokenizer do
|
||||
@moduledoc false
|
||||
|
||||
@type content :: IO.chardata()
|
||||
@type line :: non_neg_integer
|
||||
@type marker :: '=' | '/' | '|' | ''
|
||||
@type trimmed? :: boolean
|
||||
@type token ::
|
||||
{:text, content}
|
||||
| {:expr | :start_expr | :middle_expr | :end_expr, line, marker, content, trimmed?}
|
||||
|
||||
@spaces [?\s, ?\t]
|
||||
@closing_brackets ')]}'
|
||||
|
||||
@doc """
|
||||
Tokenizes the given charlist or binary.
|
||||
|
||||
It returns {:ok, list} with the following tokens:
|
||||
|
||||
* `{:text, content}`
|
||||
* `{: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, error}` in case of errors.
|
||||
"""
|
||||
@spec tokenize(binary | charlist, line, keyword) :: {:ok, [token]} | {:error, line, String.t()}
|
||||
def tokenize(bin, line, 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, 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, opts, buffer, acc) do
|
||||
tokenize(t, line, opts, [?%, ?< | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize('<%#' ++ t, line, opts, buffer, acc) do
|
||||
case expr(t, line, []) do
|
||||
{:error, _, _} = error ->
|
||||
error
|
||||
|
||||
{:ok, _, new_line, rest} ->
|
||||
{_, rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
|
||||
tokenize(rest, new_line, opts, buffer, acc)
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('<%' ++ t, line, opts, buffer, acc) do
|
||||
{marker, t} = retrieve_marker(t)
|
||||
|
||||
case expr(t, line, []) do
|
||||
{:error, _, _} = error ->
|
||||
error
|
||||
|
||||
{:ok, expr, new_line, rest} ->
|
||||
token = token_name(expr)
|
||||
{trimmed?, rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
|
||||
acc = tokenize_text(buffer, acc)
|
||||
final = {token, line, marker, Enum.reverse(expr), trimmed?}
|
||||
tokenize(rest, new_line, opts, [], [final | acc])
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('\n' ++ t, line, opts, buffer, acc) do
|
||||
tokenize(t, line + 1, opts, [?\n | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize([h | t], line, opts, buffer, acc) do
|
||||
tokenize(t, line, opts, [h | buffer], acc)
|
||||
end
|
||||
|
||||
defp tokenize([], _line, _opts, buffer, acc) do
|
||||
{:ok, Enum.reverse(tokenize_text(buffer, acc))}
|
||||
end
|
||||
|
||||
# Retrieve marker for <%
|
||||
|
||||
defp retrieve_marker([marker | t]) when marker in [?=, ?/, ?|] do
|
||||
{[marker], t}
|
||||
end
|
||||
|
||||
defp retrieve_marker(t) do
|
||||
{'', t}
|
||||
end
|
||||
|
||||
# Tokenize an expression until we find %>
|
||||
|
||||
defp expr([?%, ?> | t], line, buffer) do
|
||||
{:ok, buffer, line, t}
|
||||
end
|
||||
|
||||
defp expr('\n' ++ t, line, buffer) do
|
||||
expr(t, line + 1, [?\n | buffer])
|
||||
end
|
||||
|
||||
defp expr([h | t], line, buffer) do
|
||||
expr(t, line, [h | buffer])
|
||||
end
|
||||
|
||||
defp expr([], line, _buffer) do
|
||||
{:error, line, "missing token '%>'"}
|
||||
end
|
||||
|
||||
# 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 "}".
|
||||
|
||||
defp token_name([h | t]) when h in @spaces do
|
||||
token_name(t)
|
||||
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 token_name('>-' ++ rest) do
|
||||
case tokenize_rest(rest) do
|
||||
{:ok, [{:end, _} | _]} ->
|
||||
:middle_expr
|
||||
|
||||
# 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.
|
||||
|
||||
defp tokenize_text([], acc) do
|
||||
acc
|
||||
end
|
||||
|
||||
defp tokenize_text(buffer, acc) do
|
||||
[{:text, Enum.reverse(buffer)} | acc]
|
||||
end
|
||||
|
||||
# If trim mode is enabled and the token is on a line with
|
||||
# only itself and whitespace, trim the whitespace around it,
|
||||
# including the line break following it if there is one.
|
||||
defp trim_if_needed(rest, line, opts, buffer, acc) do
|
||||
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
|
||||
_ -> {false, rest, line, buffer}
|
||||
end
|
||||
end
|
||||
|
||||
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) do
|
||||
case trim_whitespace(rest) do
|
||||
[?\r, ?\n | trimmed_rest] -> {true, trimmed_rest, line + 1}
|
||||
[?\n | trimmed_rest] -> {true, trimmed_rest, line + 1}
|
||||
[] -> {true, [], line}
|
||||
_ -> {false, rest, line}
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_whitespace([h | t]) when h 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")
|
||||
@@ -43,15 +44,6 @@ defmodule EEx.SmartEngineTest do
|
||||
assert_received :found
|
||||
end
|
||||
|
||||
test "error with unused \"do\" block without \"<%=\" modifier" do
|
||||
stderr =
|
||||
ExUnit.CaptureIO.capture_io(:stderr, fn ->
|
||||
assert_eval("", "<% if true do %>I'm invisible!<% end %>", assigns: %{})
|
||||
end)
|
||||
|
||||
assert stderr =~ "the contents of this expression won't be output"
|
||||
end
|
||||
|
||||
defp assert_eval(expected, actual, binding \\ []) do
|
||||
result = EEx.eval_string(actual, binding, file: __ENV__.file, engine: EEx.SmartEngine)
|
||||
assert result == expected
|
||||
|
||||
@@ -2,67 +2,39 @@ Code.require_file("../test_helper.exs", __DIR__)
|
||||
|
||||
defmodule EEx.TokenizerTest do
|
||||
use ExUnit.Case, async: true
|
||||
|
||||
@opts [indentation: 0, trim: false]
|
||||
require EEx.Tokenizer, as: T
|
||||
|
||||
test "simple chars lists" do
|
||||
assert EEx.tokenize('foo', @opts) ==
|
||||
{:ok, [{:text, 'foo', %{column: 1, line: 1}}, {:eof, %{column: 4, line: 1}}]}
|
||||
assert T.tokenize('foo', 1) == {:ok, [{:text, 'foo'}]}
|
||||
end
|
||||
|
||||
test "simple strings" do
|
||||
assert EEx.tokenize("foo", @opts) ==
|
||||
{:ok, [{:text, 'foo', %{column: 1, line: 1}}, {:eof, %{column: 4, line: 1}}]}
|
||||
assert T.tokenize("foo", 1) == {:ok, [{:text, 'foo'}]}
|
||||
end
|
||||
|
||||
test "strings with embedded code" do
|
||||
assert EEx.tokenize('foo <% bar %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:expr, '', ' bar ', %{column: 5, line: 1}},
|
||||
{:eof, %{column: 14, line: 1}}
|
||||
]}
|
||||
assert T.tokenize('foo <% bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with embedded equals code" do
|
||||
assert EEx.tokenize('foo <%= bar %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:expr, '=', ' bar ', %{column: 5, line: 1}},
|
||||
{:eof, %{column: 15, line: 1}}
|
||||
]}
|
||||
assert T.tokenize('foo <%= bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '=', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with embedded slash code" do
|
||||
assert EEx.tokenize('foo <%/ bar %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:expr, '/', ' bar ', %{column: 5, line: 1}},
|
||||
{:eof, %{column: 15, line: 1}}
|
||||
]}
|
||||
assert T.tokenize('foo <%/ bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '/', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with embedded pipe code" do
|
||||
assert EEx.tokenize('foo <%| bar %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:expr, '|', ' bar ', %{column: 5, line: 1}},
|
||||
{:eof, %{column: 15, line: 1}}
|
||||
]}
|
||||
assert T.tokenize('foo <%| bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '|', ' bar ', false}]}
|
||||
end
|
||||
|
||||
test "strings with more than one line" do
|
||||
assert EEx.tokenize('foo\n<%= bar %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo\n', %{column: 1, line: 1}},
|
||||
{:expr, '=', ' bar ', %{column: 1, line: 2}},
|
||||
{:eof, %{column: 11, line: 2}}
|
||||
]}
|
||||
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
|
||||
@@ -74,298 +46,168 @@ defmodule EEx.TokenizerTest do
|
||||
'''
|
||||
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:expr, '=', ' bar\n\nbaz ', %{column: 5, line: 1}},
|
||||
{:text, '\n', %{column: 7, line: 3}},
|
||||
{:expr, '', ' foo ', %{column: 1, line: 4}},
|
||||
{:text, '\n', %{column: 10, line: 4}},
|
||||
{:eof, %{column: 1, line: 5}}
|
||||
{:text, 'foo '},
|
||||
{:expr, 1, '=', ' bar\n\nbaz ', false},
|
||||
{:text, '\n'},
|
||||
{:expr, 4, '', ' foo ', false},
|
||||
{:text, '\n'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize(string, @opts) == {:ok, exprs}
|
||||
assert T.tokenize(string, 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "quotation" do
|
||||
assert EEx.tokenize('foo <%% true %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo <% true %>', %{column: 1, line: 1}},
|
||||
{:eof, %{column: 16, line: 1}}
|
||||
]}
|
||||
assert T.tokenize('foo <%% true %>', 1) == {:ok, [{:text, 'foo <% true %>'}]}
|
||||
end
|
||||
|
||||
test "quotation with do-end" do
|
||||
assert EEx.tokenize('foo <%% true do %>bar<%% end %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:text, 'foo <% true do %>bar<% end %>', %{column: 1, line: 1}},
|
||||
{:eof, %{column: 32, line: 1}}
|
||||
]}
|
||||
test "quotation with do/end" do
|
||||
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 ', %{column: 1, line: 1}},
|
||||
{:expr, '=', ' c ', %{column: 9, line: 1}},
|
||||
{:text, ' ', %{column: 17, line: 1}},
|
||||
{:expr, '=', ' d ', %{column: 18, line: 1}},
|
||||
{:text, ' e %> f', %{column: 26, line: 1}},
|
||||
{:eof, %{column: 33, line: 1}}
|
||||
{:text, 'a <% b '},
|
||||
{:expr, 1, '=', ' c ', false},
|
||||
{:text, ' '},
|
||||
{:expr, 1, '=', ' d ', false},
|
||||
{:text, ' e %> f'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('a <%% b <%= c %> <%= d %> e %> f', @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 %>', %{column: 1, line: 1}},
|
||||
{:eof, %{column: 22, line: 1}}
|
||||
{:text, '<%% a <%= b %> c %>'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<%%% a <%%= b %> c %>', @opts) == {:ok, exprs}
|
||||
assert T.tokenize('<%%% a <%%= b %> c %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "EEx comments" do
|
||||
test "comments" do
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:eof, %{column: 16, line: 1}}
|
||||
{:text, 'foo '}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <%# true %>', @opts) == {:ok, exprs}
|
||||
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:eof, %{column: 8, line: 2}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <%#\ntrue %>', @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 ', %{column: 1, line: 1}},
|
||||
{:text, 'bar', %{column: 19, line: 1}},
|
||||
{:eof, %{column: 32, line: 1}}
|
||||
{:text, 'foo bar'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <%# true do %>bar<%# end %>', @opts) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "EEx comments inside do-end" do
|
||||
exprs = [
|
||||
{:start_expr, '', ' if true do ', %{column: 1, line: 1}},
|
||||
{:text, 'bar', %{column: 31, line: 1}},
|
||||
{:end_expr, [], ' end ', %{column: 34, line: 1}},
|
||||
{:eof, %{column: 43, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<% if true do %><%# comment %>bar<% end %>', @opts) == {:ok, exprs}
|
||||
|
||||
exprs = [
|
||||
{:start_expr, [], ' case true do ', %{column: 1, line: 1}},
|
||||
{:middle_expr, '', ' true -> ', %{column: 33, line: 1}},
|
||||
{:text, 'bar', %{column: 46, line: 1}},
|
||||
{:end_expr, [], ' end ', %{column: 49, line: 1}},
|
||||
{:eof, %{column: 58, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<% case true do %><%# comment %><% true -> %>bar<% end %>', @opts) ==
|
||||
{:ok, exprs}
|
||||
end
|
||||
|
||||
test "EEx multi-line comments" do
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:comment, ' true ', %{column: 5, line: 1}},
|
||||
{:text, ' bar', %{column: 20, line: 1}},
|
||||
{:eof, %{column: 24, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <%!-- true --%> bar', @opts) == {:ok, exprs}
|
||||
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:comment, ' \ntrue\n ', %{column: 5, line: 1}},
|
||||
{:text, ' bar', %{column: 6, line: 3}},
|
||||
{:eof, %{column: 10, line: 3}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <%!-- \ntrue\n --%> bar', @opts) == {:ok, exprs}
|
||||
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:comment, ' <%= true %> ', %{column: 5, line: 1}},
|
||||
{:text, ' bar', %{column: 27, line: 1}},
|
||||
{:eof, %{column: 31, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <%!-- <%= true %> --%> bar', @opts) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "Elixir comments" do
|
||||
exprs = [
|
||||
{:text, 'foo ', %{column: 1, line: 1}},
|
||||
{:expr, [], ' true # this is a boolean ', %{column: 5, line: 1}},
|
||||
{:eof, %{column: 35, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <% true # this is a boolean %>', @opts) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "Elixir comments with do-end" do
|
||||
exprs = [
|
||||
{:start_expr, [], ' if true do # startif ', %{column: 1, line: 1}},
|
||||
{:text, 'text', %{column: 27, line: 1}},
|
||||
{:end_expr, [], ' end # closeif ', %{column: 31, line: 1}},
|
||||
{:eof, %{column: 50, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<% if true do # startif %>text<% end # closeif %>', @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 ', %{column: 1, line: 1}},
|
||||
{:start_expr, '', ' if true do ', %{column: 5, line: 1}},
|
||||
{:text, 'bar', %{column: 21, line: 1}},
|
||||
{:end_expr, '', ' end ', %{column: 24, line: 1}},
|
||||
{:eof, %{column: 33, line: 1}}
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, '', ' if true do ', false},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <% if true do %>bar<% end %>', @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 ', %{column: 1, line: 1}},
|
||||
{:start_expr, '', ' cond do ', %{column: 5, line: 1}},
|
||||
{:middle_expr, '', ' false -> ', %{column: 18, line: 1}},
|
||||
{:text, 'bar', %{column: 32, line: 1}},
|
||||
{:middle_expr, '', ' true -> ', %{column: 35, line: 1}},
|
||||
{:text, 'baz', %{column: 48, line: 1}},
|
||||
{:end_expr, '', ' end ', %{column: 51, line: 1}},
|
||||
{:eof, %{column: 60, line: 1}}
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, '', ' cond do ', false},
|
||||
{:middle_expr, 1, '', ' false -> ', false},
|
||||
{:text, 'bar'},
|
||||
{:middle_expr, 1, '', ' true -> ', false},
|
||||
{:text, 'baz'},
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', @opts) ==
|
||||
assert T.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', 1) ==
|
||||
{:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with fn-end with newline" do
|
||||
test "strings with multiple callbacks" do
|
||||
exprs = [
|
||||
{:start_expr, '=', ' a fn ->\n', %{column: 1, line: 1}},
|
||||
{:text, 'foo', %{column: 3, line: 2}},
|
||||
{:end_expr, [], ' end ', %{column: 6, line: 2}},
|
||||
{:eof, %{column: 15, line: 2}}
|
||||
{:start_expr, 1, '=', ' a fn -> ', false},
|
||||
{:text, 'foo'},
|
||||
{:middle_expr, 1, '', ' end, fn -> ', false},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<%= a fn ->\n%>foo<% end %>', @opts) ==
|
||||
{:ok, exprs}
|
||||
assert T.tokenize('<%= a fn -> %>foo<% end, fn -> %>bar<% end %>', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with multiple fn-end" do
|
||||
test "strings with callback followed by do block" do
|
||||
exprs = [
|
||||
{:start_expr, '=', ' a fn -> ', %{column: 1, line: 1}},
|
||||
{:text, 'foo', %{column: 15, line: 1}},
|
||||
{:middle_expr, '', ' end, fn -> ', %{column: 18, line: 1}},
|
||||
{:text, 'bar', %{column: 34, line: 1}},
|
||||
{:end_expr, '', ' end ', %{column: 37, line: 1}},
|
||||
{:eof, %{column: 46, line: 1}}
|
||||
{:start_expr, 1, '=', ' a fn -> ', false},
|
||||
{:text, 'foo'},
|
||||
{:middle_expr, 1, '', ' end do ', false},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<%= a fn -> %>foo<% end, fn -> %>bar<% end %>', @opts) ==
|
||||
{:ok, exprs}
|
||||
end
|
||||
|
||||
test "strings with fn-end followed by do block" do
|
||||
exprs = [
|
||||
{:start_expr, '=', ' a fn -> ', %{column: 1, line: 1}},
|
||||
{:text, 'foo', %{column: 15, line: 1}},
|
||||
{:middle_expr, '', ' end do ', %{column: 18, line: 1}},
|
||||
{:text, 'bar', %{column: 30, line: 1}},
|
||||
{:end_expr, '', ' end ', %{column: 33, line: 1}},
|
||||
{:eof, %{column: 42, line: 1}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('<%= a fn -> %>foo<% end do %>bar<% end %>', @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 ', %{column: 1, line: 1}},
|
||||
{:start_expr, '', ' if true do ', %{column: 5, line: 1}},
|
||||
{:text, 'bar', %{column: 21, line: 1}},
|
||||
{:middle_expr, '', ' else ', %{column: 24, line: 1}},
|
||||
{:text, 'baz', %{column: 34, line: 1}},
|
||||
{:end_expr, '', ' end ', %{column: 37, line: 1}},
|
||||
{:eof, %{column: 46, line: 1}}
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, '', ' if true do ', false},
|
||||
{:text, 'bar'},
|
||||
{:middle_expr, 1, '', ' else ', false},
|
||||
{:text, 'baz'},
|
||||
{:end_expr, 1, '', ' end ', false}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('foo <% if true do %>bar<% else %>baz<% end %>', @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, '=', ' if true do ', %{column: 2, line: 1}},
|
||||
{:text, '\n TRUE \n', %{column: 20, line: 1}},
|
||||
{:middle_expr, '', ' else ', %{column: 3, line: 3}},
|
||||
{:text, '\n FALSE \n', %{column: 13, line: 3}},
|
||||
{:end_expr, '', ' end ', %{column: 3, line: 5}},
|
||||
{:eof, %{column: 3, line: 7}}
|
||||
{:start_expr, 1, '=', ' if true do ', true},
|
||||
{:text, ' TRUE \n'},
|
||||
{:middle_expr, 3, '', ' else ', true},
|
||||
{:text, ' FALSE \n'},
|
||||
{:end_expr, 5, '', ' end ', true}
|
||||
]
|
||||
|
||||
assert EEx.tokenize(template, [trim: true] ++ @opts) == {:ok, exprs}
|
||||
assert T.tokenize(template, 1, trim: true) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode with comment" do
|
||||
exprs = [
|
||||
{:text, '\n123', %{column: 19, line: 1}},
|
||||
{:eof, %{column: 4, line: 2}}
|
||||
{:text, '123'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize(' <%# comment %> \n123', [trim: true] ++ @opts) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode with multi-line comment" do
|
||||
exprs = [
|
||||
{:comment, ' comment ', %{column: 3, line: 1}},
|
||||
{:text, '\n123', %{column: 23, line: 1}},
|
||||
{:eof, %{column: 4, line: 2}}
|
||||
]
|
||||
|
||||
assert EEx.tokenize(' <%!-- comment --%> \n123', [trim: true] ++ @opts) == {:ok, exprs}
|
||||
assert T.tokenize(' <%# comment %> \n123', 1, trim: true) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "trim mode with CRLF" do
|
||||
exprs = [
|
||||
{:text, '0\n', %{column: 1, line: 1}},
|
||||
{:expr, '=', ' 12 ', %{column: 3, line: 2}},
|
||||
{:text, '\n34', %{column: 15, line: 2}},
|
||||
{:eof, %{column: 3, line: 3}}
|
||||
{:text, '0\r\n'},
|
||||
{:expr, 2, '=', ' 12 ', true},
|
||||
{:text, '34'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize('0\r\n <%= 12 %> \r\n34', [trim: true] ++ @opts) == {: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, ' ', %{column: 1, line: 1}},
|
||||
{:expr, '=', ' 12 ', %{column: 2, line: 1}},
|
||||
{:text, ' \n', %{column: 11, line: 1}},
|
||||
{:eof, %{column: 1, line: 2}}
|
||||
{:text, ' '},
|
||||
{:expr, 1, '=', ' 12 ', false},
|
||||
{:text, ' \n'}
|
||||
]
|
||||
|
||||
assert EEx.tokenize(' <%= 12 %> \n', [trim: false] ++ @opts) == {: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 EEx.tokenize(x, [trim: false] ++ @opts) == EEx.tokenize(x, @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')
|
||||
@@ -373,23 +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 EEx.tokenize('foo <% :bar', @opts) ==
|
||||
{:error, "missing token '%>'", %{column: 12, line: 1}}
|
||||
|
||||
assert EEx.tokenize('<%# true ', @opts) ==
|
||||
{:error, "missing token '%>'", %{column: 10, line: 1}}
|
||||
|
||||
assert EEx.tokenize('<%!-- foo ', @opts) ==
|
||||
{:error, "missing token '--%>'", %{column: 11, line: 1}}
|
||||
end
|
||||
|
||||
test "marks invalid expressions as regular expressions" do
|
||||
assert EEx.tokenize('<% 1 $ 2 %>', @opts) ==
|
||||
{:ok,
|
||||
[
|
||||
{:expr, [], ' 1 $ 2 ', %{column: 1, line: 1}},
|
||||
{:eof, %{column: 12, line: 1}}
|
||||
]}
|
||||
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
|
||||
|
||||
+34
-169
@@ -64,43 +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\n456\n\n <%= 789 %>"
|
||||
expected = "123\n456\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
|
||||
string = "<%= 123 %> \n \n456\n \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
|
||||
|
||||
@@ -114,7 +80,7 @@ defmodule EExTest do
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
expected = "\n that\n"
|
||||
expected = " that\n"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
|
||||
@@ -126,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
|
||||
|
||||
@@ -171,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 %>")
|
||||
@@ -198,24 +139,6 @@ defmodule EExTest do
|
||||
assert_eval("foo baz", "foo <%= if false do %>bar<% else %>baz<% end %>")
|
||||
end
|
||||
|
||||
test "embedded code with comments in do end" do
|
||||
assert_eval("foo bar", "foo <%= case true do %><%# comment %><% true -> %>bar<% end %>")
|
||||
|
||||
assert_eval(
|
||||
"foo\n\nbar\n",
|
||||
"foo\n<%= case true do %>\n<%# comment %>\n<% true -> %>\nbar\n<% end %>"
|
||||
)
|
||||
end
|
||||
|
||||
test "embedded code with multi-line comments in do end" do
|
||||
assert_eval("foo bar", "foo <%= case true do %><%!-- comment --%><% true -> %>bar<% end %>")
|
||||
|
||||
assert_eval(
|
||||
"foo\n\nbar\n",
|
||||
"foo\n<%= case true do %>\n<%!-- comment --%>\n<% true -> %>\nbar\n<% end %>"
|
||||
)
|
||||
end
|
||||
|
||||
test "embedded code with nested do end" do
|
||||
assert_eval("foo bar", "foo <%= if true do %><%= if true do %>bar<% end %><% end %>")
|
||||
end
|
||||
@@ -233,11 +156,6 @@ defmodule EExTest do
|
||||
"<%= Enum.map([1, 2, 3], fn x -> %> <%= 100 + x %> <% end) %>"
|
||||
)
|
||||
|
||||
assert_eval(
|
||||
" 101 102 103 ",
|
||||
"<%= Enum.map([1, 2, 3], fn x ->\n%> <%= 100 + x %> <% end) %>"
|
||||
)
|
||||
|
||||
assert_eval(
|
||||
" 101 102 103 ",
|
||||
"<%= apply Enum, :map, [[1, 2, 3], fn x -> %> <%= 100 + x %> <% end] %>"
|
||||
@@ -274,36 +192,34 @@ 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:18: 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 %>")
|
||||
EEx.compile_string("foo\n<% if true do %>")
|
||||
end
|
||||
end
|
||||
|
||||
test "when nested end expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1:31: unexpected end of expression <% end %>", fn ->
|
||||
EEx.compile_string("foo <%= if true do %><% end %><% end %>")
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected end of expression <% end %>", fn ->
|
||||
EEx.compile_string("foo <% if true do %><% end %><% end %>")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -317,7 +233,7 @@ defmodule EExTest do
|
||||
assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
|
||||
EEx.compile_string("foo <%= if true do %>true<% else %>false<%= end %>")
|
||||
end) =~
|
||||
~s[unexpected beginning of EEx tag \"<%=\" on \"<%= end %>\"]
|
||||
~s[unexpected beginning of EEx tag \"<%=\" on end of expression \"<%= end %>\"]
|
||||
end
|
||||
|
||||
test "when trying to use marker '/' without implementation" do
|
||||
@@ -341,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
|
||||
@@ -551,51 +467,28 @@ defmodule EExTest do
|
||||
<% "a" in y -> %>
|
||||
Good
|
||||
<% true -> %>
|
||||
<%= if true do %>true<% else %>false<% end %>
|
||||
<% if true do %>true<% else %>false<% end %>
|
||||
Bad
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
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
|
||||
test "unused buffers are kept out" do
|
||||
string = """
|
||||
<%= 123 %>
|
||||
<% if true do %>
|
||||
<%= 456 %>
|
||||
<% end %>
|
||||
<%= 789 %>
|
||||
"""
|
||||
|
||||
assert_eval("123\n\n789\n", string)
|
||||
end
|
||||
|
||||
test "inside comprehensions" do
|
||||
string = """
|
||||
<%= for _name <- packages || [] do %>
|
||||
@@ -633,24 +526,6 @@ defmodule EExTest do
|
||||
assert EExTest.Compiled.__info__(:attributes)[:external_resource] ==
|
||||
[Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")]
|
||||
end
|
||||
|
||||
test "supports t:Path.t() paths" do
|
||||
filename = to_charlist(Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex"))
|
||||
result = EEx.eval_file(filename, bar: 1)
|
||||
assert_normalized_newline_equal("foo 1\n", result)
|
||||
end
|
||||
|
||||
assert_raise EEx.SyntaxError, "my_file.eex:1:12: missing token '%>'", fn ->
|
||||
EEx.compile_string("foo <%= bar", file: "my_file.eex")
|
||||
end
|
||||
|
||||
test "supports overriding file and line through options" do
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template_with_syntax_error.eex")
|
||||
|
||||
assert_raise EEx.SyntaxError, "my_file.eex:11:1: missing token '%>'", fn ->
|
||||
EEx.eval_file(filename, _bindings = [], file: "my_file.eex", line: 10)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "precompiled" do
|
||||
@@ -696,8 +571,8 @@ defmodule EExTest do
|
||||
buffer <> ":END"
|
||||
end
|
||||
|
||||
def handle_text(buffer, meta, text) do
|
||||
buffer <> ":TEXT-#{meta[:line]}-#{meta[:column]}(#{String.trim(text)})"
|
||||
def handle_text(buffer, text) do
|
||||
buffer <> ":TEXT(#{String.trim(text)})"
|
||||
end
|
||||
|
||||
def handle_expr(buffer, "/", expr) do
|
||||
@@ -715,16 +590,16 @@ defmodule EExTest do
|
||||
|
||||
describe "custom engines" do
|
||||
test "text" do
|
||||
assert_eval("BODY(INIT:TEXT-1-1(foo))", "foo", [], engine: TestEngine)
|
||||
assert_eval("BODY(INIT:TEXT(foo))", "foo", [], engine: TestEngine)
|
||||
end
|
||||
|
||||
test "custom marker" do
|
||||
assert_eval("BODY(INIT:TEXT-1-1(foo):DIV(:bar))", "foo <%/ :bar %>", [], engine: TestEngine)
|
||||
assert_eval("BODY(INIT:TEXT(foo):DIV(:bar))", "foo <%/ :bar %>", [], engine: TestEngine)
|
||||
end
|
||||
|
||||
test "begin/end" do
|
||||
assert_eval(
|
||||
~s[BODY(INIT:TEXT-1-1(foo):EQUAL(if do\n "BEGIN:TEXT-1-17(this):END"\nelse\n "BEGIN:TEXT-1-31(that):END"\nend))],
|
||||
~s[BODY(INIT:TEXT(foo):EQUAL(if do\n "BEGIN:TEXT(this):END"\nelse\n "BEGIN:TEXT(that):END"\nend))],
|
||||
"foo <%= if do %>this<% else %>that<% end %>",
|
||||
[],
|
||||
engine: TestEngine
|
||||
@@ -741,16 +616,6 @@ defmodule EExTest do
|
||||
end
|
||||
end
|
||||
|
||||
describe "parser options" do
|
||||
test "customizes parsed code" do
|
||||
atoms_encoder = fn "not_jose", _ -> {:ok, :jose} end
|
||||
|
||||
assert_eval("valid", "<%= not_jose %>", [jose: "valid"],
|
||||
parser_options: [static_atoms_encoder: atoms_encoder]
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
defp assert_eval(expected, actual, binding \\ [], opts \\ []) do
|
||||
opts = Keyword.merge([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
|
||||
result = EEx.eval_string(actual, binding, opts)
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
foo <%= bar
|
||||
@@ -1,8 +1 @@
|
||||
{line_exclude, line_include} =
|
||||
if line = System.get_env("LINE"), do: {[:test], [line: line]}, else: {[], []}
|
||||
|
||||
ExUnit.start(
|
||||
trace: !!System.get_env("TRACE"),
|
||||
include: line_include,
|
||||
exclude: line_exclude
|
||||
)
|
||||
ExUnit.start(trace: "--trace" in System.argv())
|
||||
|
||||
@@ -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
|
||||
@@ -1,20 +1,10 @@
|
||||
# Returns config for Elixir docs
|
||||
|
||||
canonical = System.fetch_env!("CANONICAL")
|
||||
|
||||
[
|
||||
extras: Path.wildcard("lib/elixir/pages/*.md") ++ ["CHANGELOG.md"],
|
||||
deps: [
|
||||
eex: "https://hexdocs.pm/eex/#{canonical}",
|
||||
ex_unit: "https://hexdocs.pm/ex_unit/#{canonical}",
|
||||
iex: "https://hexdocs.pm/iex/#{canonical}",
|
||||
logger: "https://hexdocs.pm/logger/#{canonical}",
|
||||
mix: "https://hexdocs.pm/mix/#{canonical}"
|
||||
],
|
||||
extras: Path.wildcard("lib/elixir/pages/*.md"),
|
||||
groups_for_functions: [
|
||||
Guards: &(&1[:guard] == true)
|
||||
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],
|
||||
|
||||
@@ -63,7 +53,7 @@ canonical = System.fetch_env!("CANONICAL")
|
||||
StringIO,
|
||||
System
|
||||
],
|
||||
Calendar: [
|
||||
"Calendar": [
|
||||
Calendar,
|
||||
Calendar.ISO,
|
||||
Calendar.TimeZoneDatabase,
|
||||
@@ -78,7 +68,6 @@ canonical = System.fetch_env!("CANONICAL")
|
||||
DynamicSupervisor,
|
||||
GenServer,
|
||||
Node,
|
||||
PartitionSupervisor,
|
||||
Process,
|
||||
Registry,
|
||||
Supervisor,
|
||||
@@ -97,22 +86,18 @@ canonical = System.fetch_env!("CANONICAL")
|
||||
],
|
||||
"Code & Macros": [
|
||||
Code,
|
||||
Code.Fragment,
|
||||
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]).
|
||||
|
||||
+51
-225
@@ -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 return `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]
|
||||
@@ -47,11 +47,12 @@ defmodule Access do
|
||||
> `map[key]`, if your map is made of predefined atom keys,
|
||||
> you should prefer to access those atom keys with `map.key`
|
||||
> instead of `map[key]`, as `map.key` will raise if the key
|
||||
> is missing (which is not supposed to happen if the keys are
|
||||
> predefined). Similarly, since structs are maps and structs
|
||||
> have predefined keys, they only allow the `struct.key`
|
||||
> syntax and they do not allow the `struct[key]` access syntax.
|
||||
> See the `Map` module for more information.
|
||||
> is missing. This is important because, if a map has a predefined
|
||||
> set of keys and a key is missing, it is most likely a bug
|
||||
> in your software or a typo on the key name. For this reason,
|
||||
> because structs are predefined in nature, they only allow
|
||||
> the `struct.key` syntax and they do not allow the `struct[key]`
|
||||
> access syntax. See the `Map` module for more information.
|
||||
|
||||
## Nested data structures
|
||||
|
||||
@@ -94,19 +95,21 @@ defmodule Access do
|
||||
|
||||
@type container :: keyword | struct | map
|
||||
@type nil_container :: nil
|
||||
@type t :: container | nil_container | any
|
||||
@type any_container :: any
|
||||
@type t :: container | nil_container | any_container
|
||||
@type key :: any
|
||||
@type value :: any
|
||||
|
||||
@type get_fun(data) ::
|
||||
(:get, data, (term -> term) -> new_data :: container)
|
||||
@type get_fun(data, get_value) ::
|
||||
(:get, data, (term -> term) ->
|
||||
{get_value, new_data :: container})
|
||||
|
||||
@type get_and_update_fun(data, current_value) ::
|
||||
@type get_and_update_fun(data, get_value) ::
|
||||
(:get_and_update, data, (term -> term) ->
|
||||
{current_value, new_data :: container} | :pop)
|
||||
{get_value, new_data :: container} | :pop)
|
||||
|
||||
@type access_fun(data, current_value) ::
|
||||
get_fun(data) | get_and_update_fun(data, current_value)
|
||||
@type access_fun(data, get_value) ::
|
||||
get_fun(data, get_value) | get_and_update_fun(data, get_value)
|
||||
|
||||
@doc """
|
||||
Invoked in order to access the value stored under `key` in the given term `term`.
|
||||
@@ -132,16 +135,16 @@ defmodule Access do
|
||||
|
||||
The implementation of this callback should invoke `fun` with the value under
|
||||
`key` in the passed structure `data`, or with `nil` if `key` is not present in it.
|
||||
This function must return either `{current_value, new_value}` or `:pop`.
|
||||
This function must return either `{get_value, update_value}` or `:pop`.
|
||||
|
||||
If the passed function returns `{current_value, new_value}`,
|
||||
the return value of this callback should be `{current_value, new_data}`, where:
|
||||
If the passed function returns `{get_value, update_value}`,
|
||||
the return value of this callback should be `{get_value, new_data}`, where:
|
||||
|
||||
* `current_value` is the retrieved value (which can be operated on before being returned)
|
||||
* `get_value` is the retrieved value (which can be operated on before being returned)
|
||||
|
||||
* `new_value` is the new value to be stored under `key`
|
||||
* `update_value` is the new value to be stored under `key`
|
||||
|
||||
* `new_data` is `data` after updating the value of `key` with `new_value`.
|
||||
* `new_data` is `data` after updating the value of `key` with `update_value`.
|
||||
|
||||
If the passed function returns `:pop`, the return value of this callback
|
||||
must be `{value, new_data}` where `value` is the value under `key`
|
||||
@@ -150,9 +153,8 @@ defmodule Access do
|
||||
See the implementations of `Map.get_and_update/3` or `Keyword.get_and_update/3`
|
||||
for more examples.
|
||||
"""
|
||||
@callback get_and_update(data, key, (value | nil -> {current_value, new_value :: value} | :pop)) ::
|
||||
{current_value, new_data :: data}
|
||||
when current_value: value, data: container
|
||||
@callback get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
|
||||
when get_value: var, data: container | any_container
|
||||
|
||||
@doc """
|
||||
Invoked to "pop" the value under `key` out of the given data structure.
|
||||
@@ -166,18 +168,14 @@ defmodule Access do
|
||||
|
||||
See the implementations for `Map.pop/3` or `Keyword.pop/3` for more examples.
|
||||
"""
|
||||
@callback pop(data, key) :: {value, data} when data: container
|
||||
@callback pop(data, key) :: {value, data} when data: container | any_container
|
||||
|
||||
defmacrop raise_undefined_behaviour(exception, module, top) do
|
||||
quote do
|
||||
exception =
|
||||
case __STACKTRACE__ do
|
||||
[unquote(top) | _] ->
|
||||
reason =
|
||||
"#{inspect(unquote(module))} does not implement the Access behaviour. " <>
|
||||
"If you are using get_in/put_in/update_in, you can specify the field " <>
|
||||
"to be accessed using Access.key!/1"
|
||||
|
||||
reason = "#{inspect(unquote(module))} does not implement the Access behaviour"
|
||||
%{unquote(exception) | reason: reason}
|
||||
|
||||
_ ->
|
||||
@@ -238,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).
|
||||
@@ -323,26 +302,17 @@ defmodule Access do
|
||||
a struct that implements the `Access` behaviour).
|
||||
|
||||
The `fun` argument receives the value of `key` (or `nil` if `key` is not
|
||||
present in `container`) and must return a two-element tuple `{current_value, new_value}`:
|
||||
the "get" value `current_value` (the retrieved value, which can be operated on before
|
||||
being returned) and the new value to be stored under `key` (`new_value`).
|
||||
present in `container`) and must return a two-element tuple `{get_value, update_value}`:
|
||||
the "get" value `get_value` (the retrieved value, which can be operated on before
|
||||
being returned) and the new value to be stored under `key` (`update_value`).
|
||||
`fun` may also return `:pop`, which means the current value
|
||||
should be removed from the container and returned.
|
||||
|
||||
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 | nil -> {current_value, new_value :: value} | :pop)) ::
|
||||
{current_value, new_data :: data}
|
||||
when current_value: var, data: container
|
||||
@spec get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
|
||||
when get_value: var, data: container
|
||||
def get_and_update(container, key, fun)
|
||||
|
||||
def get_and_update(%module{} = container, key, fun) do
|
||||
@@ -425,7 +395,7 @@ defmodule Access do
|
||||
The returned function uses the default value if the key does not exist.
|
||||
This can be used to specify defaults and safely traverse missing keys:
|
||||
|
||||
iex> get_in(%{}, [Access.key(:user, %{}), Access.key(:name, "meg")])
|
||||
iex> get_in(%{}, [Access.key(:user, %{name: "meg"}), Access.key(:name)])
|
||||
"meg"
|
||||
|
||||
Such is also useful when using update functions, allowing us to introduce
|
||||
@@ -448,11 +418,14 @@ defmodule Access do
|
||||
|
||||
An error is raised if the accessed structure is not a map or a struct:
|
||||
|
||||
iex> get_in(nil, [Access.key(:foo)])
|
||||
** (BadMapError) expected a map, got: nil
|
||||
|
||||
iex> get_in([], [Access.key(:foo)])
|
||||
** (BadMapError) expected a map, got: []
|
||||
|
||||
"""
|
||||
@spec key(key, term) :: access_fun(data :: struct | map, current_value :: term)
|
||||
@spec key(key, term) :: access_fun(data :: struct | map, get_value :: term)
|
||||
def key(key, default \\ nil) do
|
||||
fn
|
||||
:get, data, next ->
|
||||
@@ -496,7 +469,7 @@ defmodule Access do
|
||||
** (RuntimeError) Access.key!/1 expected a map/struct, got: []
|
||||
|
||||
"""
|
||||
@spec key!(key) :: access_fun(data :: struct | map, current_value :: term)
|
||||
@spec key!(key) :: access_fun(data :: struct | map, get_value :: term)
|
||||
def key!(key) do
|
||||
fn
|
||||
:get, %{} = data, next ->
|
||||
@@ -544,7 +517,7 @@ defmodule Access do
|
||||
** (RuntimeError) Access.elem/1 expected a tuple, got: %{}
|
||||
|
||||
"""
|
||||
@spec elem(non_neg_integer) :: access_fun(data :: tuple, current_value :: term)
|
||||
@spec elem(non_neg_integer) :: access_fun(data :: tuple, get_value :: term)
|
||||
def elem(index) when is_integer(index) and index >= 0 do
|
||||
pos = index + 1
|
||||
|
||||
@@ -598,7 +571,7 @@ defmodule Access do
|
||||
** (RuntimeError) Access.all/0 expected a list, got: %{}
|
||||
|
||||
"""
|
||||
@spec all() :: access_fun(data :: list, current_value :: list)
|
||||
@spec all() :: access_fun(data :: list, get_value :: list)
|
||||
def all() do
|
||||
&all/3
|
||||
end
|
||||
@@ -673,7 +646,7 @@ defmodule Access do
|
||||
** (RuntimeError) Access.at/1 expected a list, got: %{}
|
||||
|
||||
"""
|
||||
@spec at(integer) :: access_fun(data :: list, current_value :: term)
|
||||
@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
|
||||
@@ -683,69 +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
|
||||
|
||||
"""
|
||||
@doc since: "1.11.0"
|
||||
@spec at!(integer) :: access_fun(data :: list, current_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"""
|
||||
@@ -795,7 +735,7 @@ defmodule Access do
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec filter((term -> boolean)) :: access_fun(data :: list, current_value :: list)
|
||||
@spec filter((term -> boolean)) :: access_fun(data :: list, get_value :: list)
|
||||
def filter(func) when is_function(func) do
|
||||
fn op, data, next -> filter(op, data, func, next) end
|
||||
end
|
||||
@@ -829,118 +769,4 @@ defmodule Access do
|
||||
defp get_and_update_filter([], _func, _next, updates, gets) do
|
||||
{:lists.reverse(gets), :lists.reverse(updates)}
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Returns a function that accesses all items of a list that are within the provided range.
|
||||
|
||||
The range will be normalized following the same rules from `Enum.slice/2`.
|
||||
|
||||
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
|
||||
`Kernel.get_and_update_in/3`, and friends.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}, %{name: "vitor", salary: 25}]
|
||||
iex> get_in(list, [Access.slice(1..2), :name])
|
||||
["francine", "vitor"]
|
||||
iex> get_and_update_in(list, [Access.slice(1..3//2), :name], fn prev ->
|
||||
...> {prev, String.upcase(prev)}
|
||||
...> end)
|
||||
{["francine"], [%{name: "john", salary: 10}, %{name: "FRANCINE", salary: 30}, %{name: "vitor", salary: 25}]}
|
||||
|
||||
`slice/1` can also be used to pop elements out of a list or
|
||||
a key inside of a list:
|
||||
|
||||
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}, %{name: "vitor", salary: 25}]
|
||||
iex> pop_in(list, [Access.slice(-2..-1)])
|
||||
{[%{name: "francine", salary: 30}, %{name: "vitor", salary: 25}], [%{name: "john", salary: 10}]}
|
||||
iex> pop_in(list, [Access.slice(-2..-1), :name])
|
||||
{["francine", "vitor"], [%{name: "john", salary: 10}, %{salary: 30}, %{salary: 25}]}
|
||||
|
||||
When no match is found, an empty list is returned and the update function is never called
|
||||
|
||||
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}, %{name: "vitor", salary: 25}]
|
||||
iex> get_in(list, [Access.slice(5..10//2), :name])
|
||||
[]
|
||||
iex> get_and_update_in(list, [Access.slice(5..10//2), :name], fn prev ->
|
||||
...> {prev, String.upcase(prev)}
|
||||
...> end)
|
||||
{[], [%{name: "john", salary: 10}, %{name: "francine", salary: 30}, %{name: "vitor", salary: 25}]}
|
||||
|
||||
An error is raised if the accessed structure is not a list:
|
||||
|
||||
iex> get_in(%{}, [Access.slice(2..10//3)])
|
||||
** (ArgumentError) Access.slice/1 expected a list, got: %{}
|
||||
|
||||
An error is raised if the step of the range is negative:
|
||||
|
||||
iex> get_in([], [Access.slice(2..10//-1)])
|
||||
** (ArgumentError) Access.slice/1 does not accept ranges with negative steps, got: 2..10//-1
|
||||
|
||||
"""
|
||||
@doc since: "1.14"
|
||||
@spec slice(Range.t()) :: access_fun(data :: list, current_value :: list)
|
||||
def slice(%Range{} = range) do
|
||||
if range.step > 0 do
|
||||
fn op, data, next -> slice(op, data, range, next) end
|
||||
else
|
||||
raise ArgumentError,
|
||||
"Access.slice/1 does not accept ranges with negative steps, got: #{inspect(range)}"
|
||||
end
|
||||
end
|
||||
|
||||
defp slice(:get, data, %Range{} = range, next) when is_list(data) do
|
||||
data
|
||||
|> Enum.slice(range)
|
||||
|> Enum.map(next)
|
||||
end
|
||||
|
||||
defp slice(:get_and_update, data, range, next) when is_list(data) do
|
||||
range = normalize_range(range, data)
|
||||
|
||||
if range.first > range.last do
|
||||
{[], data}
|
||||
else
|
||||
get_and_update_slice(data, range, next, [], [], 0)
|
||||
end
|
||||
end
|
||||
|
||||
defp slice(_op, data, _range, _next) do
|
||||
raise ArgumentError, "Access.slice/1 expected a list, got: #{inspect(data)}"
|
||||
end
|
||||
|
||||
defp normalize_range(%Range{first: first, last: last, step: step}, list)
|
||||
when first < 0 or last < 0 do
|
||||
count = length(list)
|
||||
first = if first >= 0, do: first, else: Kernel.max(first + count, 0)
|
||||
last = if last >= 0, do: last, else: last + count
|
||||
Range.new(first, last, step)
|
||||
end
|
||||
|
||||
defp normalize_range(range, _list), do: range
|
||||
|
||||
defp get_and_update_slice([head | rest], range, next, updates, gets, index) do
|
||||
if index in range do
|
||||
case next.(head) do
|
||||
:pop ->
|
||||
get_and_update_slice(rest, range, next, updates, [head | gets], index + 1)
|
||||
|
||||
{get, update} ->
|
||||
get_and_update_slice(
|
||||
rest,
|
||||
range,
|
||||
next,
|
||||
[update | updates],
|
||||
[get | gets],
|
||||
index + 1
|
||||
)
|
||||
end
|
||||
else
|
||||
get_and_update_slice(rest, range, next, [head | updates], gets, index + 1)
|
||||
end
|
||||
end
|
||||
|
||||
defp get_and_update_slice([], _range, _next, updates, gets, _index) do
|
||||
{:lists.reverse(gets), :lists.reverse(updates)}
|
||||
end
|
||||
end
|
||||
|
||||
+2
-29
@@ -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.
|
||||
|
||||
@@ -241,7 +241,7 @@ defmodule Agent do
|
||||
and the start function will return `{:error, :timeout}`.
|
||||
|
||||
If the `:debug` option is present, the corresponding function in the
|
||||
[`:sys` module](`:sys`) will be invoked.
|
||||
[`:sys` module](http://www.erlang.org/doc/man/sys.html) will be invoked.
|
||||
|
||||
If the `:spawn_opt` option is present, its value will be passed as options
|
||||
to the underlying process as in `Process.spawn/4`.
|
||||
@@ -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
|
||||
|
||||
+121
-376
@@ -7,147 +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` and `config/runtime.exs` files. The
|
||||
former is loaded at build-time, before your code compiles, and the latter at
|
||||
runtime, just before your app starts. 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:
|
||||
|
||||
See the "Configuration" section in the `Mix` module for more information.
|
||||
You can also change the application environment dynamically by using functions
|
||||
such as `put_env/3` and `delete_env/2`.
|
||||
config :APP_NAME, redis_host: "redis.local"
|
||||
|
||||
> Note: The config files `config/config.exs` and `config/runtime.exs`
|
||||
> are rarely used by libraries. Libraries typically define their environment
|
||||
> in the `def application` function of their `mix.exs`. Configuration files
|
||||
> are rather used by applications to configure their libraries.
|
||||
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.
|
||||
|
||||
> Note: Each application is responsible for its own environment. Do not
|
||||
> use the functions in this module for directly accessing or modifying
|
||||
> the environment of other applications. Whenever you change the application
|
||||
> environment, Elixir's build tool will only recompile the files that
|
||||
> belong to that application. So if you read the application environment
|
||||
> of another application, there is a chance you will be depending on
|
||||
> outdated configuration, as your file won't be recompiled as it changes.
|
||||
|
||||
## Compile-time environment
|
||||
|
||||
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. However, if you try to access
|
||||
`Application.fetch_env!/2` outside of a function:
|
||||
|
||||
defmodule MyApp.DBClient do
|
||||
@db_host Application.fetch_env!(:my_app, :db_host)
|
||||
|
||||
def start_link() do
|
||||
SomeLib.DBClient.start_link(host: @db_host)
|
||||
end
|
||||
end
|
||||
|
||||
You might see warnings and errors:
|
||||
|
||||
warning: Application.fetch_env!/2 is discouraged in the module body,
|
||||
use Application.compile_env/3 instead
|
||||
iex:3: MyApp.DBClient
|
||||
|
||||
** (ArgumentError) could not fetch application environment :db_host
|
||||
for application :my_app because the application was not loaded nor
|
||||
configured
|
||||
|
||||
This happens because, when defining modules, the application environment
|
||||
is not yet available. Luckily, the warning tells us how to solve this
|
||||
issue, by using `Application.compile_env/3` instead:
|
||||
|
||||
defmodule MyApp.DBClient do
|
||||
@db_host Application.compile_env(:my_app, :db_host, "db.local")
|
||||
|
||||
def start_link() do
|
||||
SomeLib.DBClient.start_link(host: @db_host)
|
||||
end
|
||||
end
|
||||
|
||||
The difference here is that `compile_env` expects the default value to be
|
||||
given as an argument, instead of using the `def application` function of
|
||||
your `mix.exs`. Furthermore, 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.
|
||||
|
||||
In any case, compile-time environments should be avoided. Whenever possible,
|
||||
reading the application environment at runtime should be the first choice.
|
||||
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:
|
||||
@@ -184,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*](https://www.erlang.org/doc/man/application.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
|
||||
|
||||
@@ -207,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.
|
||||
|
||||
@@ -228,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.
|
||||
|
||||
@@ -252,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
|
||||
@@ -274,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
|
||||
@@ -293,10 +223,11 @@ defmodule Application do
|
||||
## Further information
|
||||
|
||||
For further details on applications please check the documentation of the
|
||||
[`:application` Erlang module](`:application`), and the
|
||||
[Applications](https://www.erlang.org/doc/design_principles/applications.html)
|
||||
[`application`](http://www.erlang.org/doc/man/application.html) Erlang module,
|
||||
and the
|
||||
[Applications](http://www.erlang.org/doc/design_principles/applications.html)
|
||||
section of the [OTP Design Principles User's
|
||||
Guide](https://www.erlang.org/doc/design_principles/users_guide.html).
|
||||
Guide](http://erlang.org/doc/design_principles/users_guide.html).
|
||||
"""
|
||||
|
||||
@doc """
|
||||
@@ -322,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`
|
||||
@@ -411,7 +342,6 @@ defmodule Application do
|
||||
:maxT,
|
||||
:registered,
|
||||
:included_applications,
|
||||
:optional_applications,
|
||||
:applications,
|
||||
:mod,
|
||||
:start_phases
|
||||
@@ -483,163 +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.
|
||||
"""
|
||||
@doc since: "1.10.0"
|
||||
@spec compile_env(app, key | list, value) :: value
|
||||
defmacro compile_env(app, key_or_path, default \\ nil) do
|
||||
if __CALLER__.function do
|
||||
raise "Application.compile_env/3 cannot be called inside functions, only in the module body"
|
||||
end
|
||||
|
||||
key_or_path = Macro.expand_literals(key_or_path, %{__CALLER__ | function: {:__info__, 1}})
|
||||
|
||||
quote do
|
||||
Application.compile_env(__ENV__, unquote(app), unquote(key_or_path), unquote(default))
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads the application environment at compilation time from a macro.
|
||||
|
||||
Typically, developers will use `compile_env/3`. This function must
|
||||
only be invoked from macros which aim to read the compilation environment
|
||||
dynamically.
|
||||
|
||||
It expects a `Macro.Env` as first argument, where the `Macro.Env` is
|
||||
typically the `__CALLER__` in a macro. It raises if `Macro.Env` comes
|
||||
from a function.
|
||||
"""
|
||||
@doc since: "1.14.0"
|
||||
@spec compile_env(Macro.Env.t(), app, key | list, value) :: value
|
||||
def compile_env(%Macro.Env{} = env, app, key_or_path, default) 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) do
|
||||
if __CALLER__.function do
|
||||
raise "Application.compile_env!/2 cannot be called inside functions, only in the module body"
|
||||
end
|
||||
|
||||
key_or_path = Macro.expand_literals(key_or_path, %{__CALLER__ | function: {:__info__, 1}})
|
||||
|
||||
quote do
|
||||
Application.compile_env!(__ENV__, unquote(app), unquote(key_or_path))
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads the application environment at compilation time from a macro
|
||||
or raises.
|
||||
|
||||
Typically, developers will use `compile_env!/2`. This function must
|
||||
only be invoked from macros which aim to read the compilation environment
|
||||
dynamically.
|
||||
|
||||
It expects a `Macro.Env` as first argument, where the `Macro.Env` is
|
||||
typically the `__CALLER__` in a macro. It raises if `Macro.Env` comes
|
||||
from a function.
|
||||
"""
|
||||
@doc since: "1.14.0"
|
||||
@spec compile_env!(Macro.Env.t(), app, key | list) :: value
|
||||
def compile_env!(%Macro.Env{} = env, app, key_or_path) 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)
|
||||
end
|
||||
|
||||
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:** you must use this function to read only your own application
|
||||
> environment. Do not read the environment of other applications.
|
||||
|
||||
> **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.
|
||||
@@ -665,22 +444,18 @@ defmodule Application do
|
||||
|
||||
Our database engine used by `:my_app` needs to know what databases exist, and
|
||||
what the database configurations are. The database engine can make a call to
|
||||
`Application.get_env(:my_app, :my_app_databases, [])` to retrieve the list of
|
||||
databases (specified by module names).
|
||||
|
||||
The engine can then traverse each repository in the list and call
|
||||
`Application.get_env(:my_app, Databases.RepoOne)` and so forth to retrieve the
|
||||
configuration of each one. In this case, each configuration will be a keyword
|
||||
list, so you can use the functions in the `Keyword` module or even the `Access`
|
||||
module to traverse it, for example:
|
||||
|
||||
config = Application.get_env(:my_app, Databases.RepoOne)
|
||||
config[:ip]
|
||||
`get_env(:my_app, :my_app_databases)` to retrieve the list of databases (specified
|
||||
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
|
||||
|
||||
@@ -688,19 +463,9 @@ defmodule Application do
|
||||
Returns the value for `key` in `app`'s environment in a tuple.
|
||||
|
||||
If the configuration parameter does not exist, the function returns `:error`.
|
||||
|
||||
> **Important:** you must use this function to read only your own application
|
||||
> environment. Do not read the environment of other applications.
|
||||
|
||||
> **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).
|
||||
"""
|
||||
@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
|
||||
@@ -711,14 +476,6 @@ defmodule Application do
|
||||
Returns the value for `key` in `app`'s environment.
|
||||
|
||||
If the configuration parameter does not exist, raises `ArgumentError`.
|
||||
|
||||
> **Important:** you must use this function to read only your own application
|
||||
> environment. Do not read the environment of other applications.
|
||||
|
||||
> **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).
|
||||
"""
|
||||
@spec fetch_env!(app, key) :: value
|
||||
def fetch_env!(app, key) when is_atom(app) do
|
||||
@@ -727,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
|
||||
|
||||
@@ -764,7 +523,6 @@ 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
|
||||
|
||||
@@ -776,14 +534,27 @@ defmodule Application do
|
||||
* have the same application listed more than once
|
||||
* have the same key inside the same application listed more than once
|
||||
|
||||
If those conditions are not met, it will raise.
|
||||
If those conditions are not met, the behaviour is undefined
|
||||
(on Erlang/OTP 21 and earlier) or will raise (on Erlang/OTP 22
|
||||
and later).
|
||||
|
||||
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
|
||||
:application.set_env(config, opts)
|
||||
# TODO: Remove function exported? check when we require Erlang/OTP 22+
|
||||
if function_exported?(:application, :set_env, 2) do
|
||||
:application.set_env(config, opts)
|
||||
else
|
||||
for app_keyword <- config,
|
||||
{app, keyword} = app_keyword,
|
||||
key_value <- keyword,
|
||||
{key, value} = key_value do
|
||||
:application.set_env(app, key, value, opts)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -793,19 +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
|
||||
|
||||
# TODO: Remove this deprecation warning on 2.0+ and allow list lookups as in compile_env.
|
||||
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.
|
||||
|
||||
@@ -821,22 +582,6 @@ defmodule Application do
|
||||
:application.ensure_started(app, type)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Ensures the given `app` is loaded.
|
||||
|
||||
Same as `load/1` 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.
|
||||
|
||||
@@ -945,7 +690,7 @@ defmodule Application do
|
||||
#=> "bar-123"
|
||||
|
||||
For more information on code paths, check the `Code` module in
|
||||
Elixir and also Erlang's [`:code` module](`:code`).
|
||||
Elixir and also Erlang's [`:code` module](http://www.erlang.org/doc/man/code.html).
|
||||
"""
|
||||
@spec app_dir(app) :: String.t()
|
||||
def app_dir(app) when is_atom(app) do
|
||||
|
||||
+3
-41
@@ -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 """
|
||||
@@ -56,7 +18,7 @@ defmodule Atom do
|
||||
"""
|
||||
@spec to_string(atom) :: String.t()
|
||||
def to_string(atom) do
|
||||
:erlang.atom_to_binary(atom)
|
||||
:erlang.atom_to_binary(atom, :utf8)
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
+740
-666
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ defmodule Behaviour do
|
||||
|
||||
This module is deprecated. Instead of `defcallback/1` and
|
||||
`defmacrocallback/1`, the `@callback` and `@macrocallback`
|
||||
module attributes can be used respectively. See the
|
||||
module attributes can be used (respectively). See the
|
||||
documentation for `Module` for more information on these
|
||||
attributes.
|
||||
|
||||
@@ -17,7 +17,6 @@ defmodule Behaviour do
|
||||
@doc """
|
||||
Defines a function callback according to the given type specification.
|
||||
"""
|
||||
@deprecated "Use the @callback module attribute instead"
|
||||
defmacro defcallback(spec) do
|
||||
do_defcallback(:def, split_spec(spec, quote(do: term)))
|
||||
end
|
||||
@@ -25,7 +24,6 @@ defmodule Behaviour do
|
||||
@doc """
|
||||
Defines a macro callback according to the given type specification.
|
||||
"""
|
||||
@deprecated "Use the @macrocallback module attribute instead"
|
||||
defmacro defmacrocallback(spec) do
|
||||
do_defcallback(:defmacro, split_spec(spec, quote(do: Macro.t())))
|
||||
end
|
||||
@@ -113,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
|
||||
|
||||
+74
-113
@@ -1,28 +1,44 @@
|
||||
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 `band/2`,
|
||||
`bor/2`, `bsl/2`, and `bsr/2` also have operators,
|
||||
respectively: `&&&/2`, `|||/2`, `<<</2`, and `>>>/2`.
|
||||
The macros in this module come in two flavors: named or
|
||||
operators. For example:
|
||||
|
||||
## Guards
|
||||
iex> use Bitwise
|
||||
iex> bnot(1) # named
|
||||
-2
|
||||
iex> 1 &&& 1 # operator
|
||||
1
|
||||
|
||||
All bitwise functions can be used in guards:
|
||||
If you prefer to use only operators or skip them, you can
|
||||
pass the following options:
|
||||
|
||||
* `:only_operators` - includes only operators
|
||||
* `:skip_operators` - skips operators
|
||||
|
||||
For example:
|
||||
|
||||
iex> use Bitwise, only_operators: true
|
||||
iex> 1 &&& 1
|
||||
1
|
||||
|
||||
When invoked with no options, `use Bitwise` is equivalent
|
||||
to `import Bitwise`.
|
||||
|
||||
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
|
||||
@deprecated "import Bitwise instead"
|
||||
defmacro __using__(options) do
|
||||
except =
|
||||
cond do
|
||||
@@ -30,7 +46,7 @@ defmodule Bitwise do
|
||||
[bnot: 1, band: 2, bor: 2, bxor: 2, bsl: 2, bsr: 2]
|
||||
|
||||
Keyword.get(options, :skip_operators) ->
|
||||
["~~~": 1, &&&: 2, |||: 2, "^^^": 2, <<<: 2, >>>: 2]
|
||||
[~~~: 1, &&&: 2, |||: 2, ^^^: 2, <<<: 2, >>>: 2]
|
||||
|
||||
true ->
|
||||
[]
|
||||
@@ -42,229 +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 false
|
||||
def unquote(:"~~~")(expr) do
|
||||
:erlang.bnot(expr)
|
||||
@doc """
|
||||
Prefix (unary) operator; calculates the bitwise NOT of its argument.
|
||||
|
||||
iex> ~~~2
|
||||
-3
|
||||
iex> ~~~2 &&& 3
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
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 false
|
||||
def unquote(:"^^^")(left, right) do
|
||||
:erlang.bxor(left, right)
|
||||
@doc """
|
||||
Infix operator; calculates the bitwise XOR of its arguments.
|
||||
|
||||
iex> 9 ^^^ 3
|
||||
10
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
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
|
||||
|
||||
+12
-585
@@ -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 :: {value :: non_neg_integer, precision :: 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`.
|
||||
@@ -189,12 +170,12 @@ defmodule Calendar do
|
||||
@doc """
|
||||
Calculates the year and era from the given `year`.
|
||||
"""
|
||||
@callback year_of_era(year, month, day) :: {year, era}
|
||||
@callback year_of_era(year) :: {year, era}
|
||||
|
||||
@doc """
|
||||
Calculates the day and era from the given `year`, `month`, and `day`.
|
||||
"""
|
||||
@callback day_of_era(year, month, day) :: 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 """
|
||||
@@ -365,7 +305,7 @@ defmodule Calendar do
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec put_time_zone_database(time_zone_database()) :: :ok
|
||||
def put_time_zone_database(database) when is_atom(database) do
|
||||
def put_time_zone_database(database) do
|
||||
Application.put_env(:elixir, :time_zone_database, database)
|
||||
end
|
||||
|
||||
@@ -375,519 +315,6 @@ defmodule Calendar do
|
||||
@doc since: "1.8.0"
|
||||
@spec get_time_zone_database() :: time_zone_database()
|
||||
def get_time_zone_database() do
|
||||
Application.fetch_env!(:elixir, :time_zone_database)
|
||||
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, 31
|
||||
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[2020-04-02 13:52:06.0Z], "%B %-d, %Y")
|
||||
"April 2, 2020"
|
||||
|
||||
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, nil, nil, parser_data) do
|
||||
parse_modifiers(rest, nil, ?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
|
||||
{sign, year} =
|
||||
if datetime.year < 0 do
|
||||
{?-, -datetime.year}
|
||||
else
|
||||
{[], datetime.year}
|
||||
end
|
||||
|
||||
result = [sign | 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)
|
||||
Application.get_env(:elixir, :time_zone_database, Calendar.UTCOnlyTimeZoneDatabase)
|
||||
end
|
||||
end
|
||||
|
||||
+57
-321
@@ -4,7 +4,7 @@ defmodule Date do
|
||||
|
||||
The Date struct contains the fields year, month, day and calendar.
|
||||
New dates can be built with the `new/3` function or using the
|
||||
`~D` (see `sigil_D/2`) sigil:
|
||||
`~D` (see `Kernel.sigil_D/2`) sigil:
|
||||
|
||||
iex> ~D[2000-01-01]
|
||||
~D[2000-01-01]
|
||||
@@ -31,12 +31,7 @@ defmodule Date do
|
||||
|
||||
Comparisons in Elixir using `==/2`, `>/2`, `</2` and similar are structural
|
||||
and based on the `Date` struct fields. For proper comparison between
|
||||
dates, use the `compare/2` function. The existence of the `compare/2`
|
||||
function in this module also allows using `Enum.min/2` and `Enum.max/2`
|
||||
functions to get the minimum and maximum date of an `Enum`. For example:
|
||||
|
||||
iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]], Date)
|
||||
~D[2017-03-31]
|
||||
dates, use the `compare/2` function.
|
||||
|
||||
## Using epochs
|
||||
|
||||
@@ -77,83 +72,39 @@ defmodule Date do
|
||||
## Examples
|
||||
|
||||
iex> Date.range(~D[1999-01-01], ~D[2000-01-01])
|
||||
Date.range(~D[1999-01-01], ~D[2000-01-01])
|
||||
#DateRange<~D[1999-01-01], ~D[2000-01-01]>
|
||||
|
||||
A range of dates implements the `Enumerable` protocol, which means
|
||||
functions in the `Enum` module can be used to work with
|
||||
ranges:
|
||||
|
||||
iex> range = Date.range(~D[2001-01-01], ~D[2002-01-01])
|
||||
iex> range
|
||||
Date.range(~D[2001-01-01], ~D[2002-01-01])
|
||||
iex> Enum.count(range)
|
||||
366
|
||||
iex> ~D[2001-02-01] in range
|
||||
iex> Enum.member?(range, ~D[2001-02-01])
|
||||
true
|
||||
iex> Enum.take(range, 3)
|
||||
[~D[2001-01-01], ~D[2001-01-02], ~D[2001-01-03]]
|
||||
iex> Enum.reduce(range, 0, fn _date, acc -> acc - 1 end)
|
||||
-366
|
||||
|
||||
"""
|
||||
@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)
|
||||
# TODO: Deprecate inferring a range with a step of -1 on Elixir v1.16
|
||||
step = if first_days <= last_days, do: 1, else: -1
|
||||
range(first, first_days, last, last_days, calendar, step)
|
||||
end
|
||||
|
||||
def range(%{calendar: _, year: _, month: _, day: _}, %{calendar: _, year: _, month: _, day: _}) do
|
||||
raise ArgumentError, "both dates must have matching calendars"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a range of dates with a step.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> range = Date.range(~D[2001-01-01], ~D[2002-01-01], 2)
|
||||
iex> range
|
||||
Date.range(~D[2001-01-01], ~D[2002-01-01], 2)
|
||||
iex> Enum.count(range)
|
||||
183
|
||||
iex> ~D[2001-01-03] in range
|
||||
true
|
||||
iex> Enum.take(range, 3)
|
||||
[~D[2001-01-01], ~D[2001-01-03], ~D[2001-01-05]]
|
||||
|
||||
"""
|
||||
@doc since: "1.12.0"
|
||||
@spec range(Calendar.date(), Calendar.date(), step :: pos_integer | neg_integer) ::
|
||||
Date.Range.t()
|
||||
def range(%{calendar: calendar} = first, %{calendar: calendar} = last, step)
|
||||
when is_integer(step) and step != 0 do
|
||||
{first_days, _} = to_iso_days(first)
|
||||
{last_days, _} = to_iso_days(last)
|
||||
range(first, first_days, last, last_days, calendar, step)
|
||||
end
|
||||
|
||||
def range(
|
||||
%{calendar: _, year: _, month: _, day: _} = first,
|
||||
%{calendar: _, year: _, month: _, day: _} = last,
|
||||
step
|
||||
) do
|
||||
raise ArgumentError,
|
||||
"both dates must have matching calendar and the step must be a " <>
|
||||
"non-zero integer, got: #{inspect(first)}, #{inspect(last)}, #{step}"
|
||||
end
|
||||
|
||||
defp range(first, first_days, last, last_days, calendar, step) do
|
||||
%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,
|
||||
step: step
|
||||
last_in_iso_days: last_days
|
||||
}
|
||||
end
|
||||
|
||||
def range(%Date{}, %Date{}) do
|
||||
raise ArgumentError, "both dates must have matching calendars"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the current date in UTC.
|
||||
|
||||
@@ -273,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.
|
||||
|
||||
@@ -322,7 +246,7 @@ defmodule Date do
|
||||
|
||||
@doc """
|
||||
Parses the extended "Dates" format described by
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
The year parsed by this function is limited to four digits.
|
||||
|
||||
@@ -339,15 +263,36 @@ 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
|
||||
|
||||
@doc """
|
||||
Parses the extended "Dates" format described by
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Raises if the format is invalid.
|
||||
|
||||
@@ -372,7 +317,7 @@ defmodule Date do
|
||||
|
||||
@doc """
|
||||
Converts the given `date` to
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
By default, `Date.to_iso8601/2` returns dates formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through passing the `:basic` option.
|
||||
@@ -474,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.
|
||||
|
||||
@@ -549,8 +455,8 @@ defmodule Date do
|
||||
end
|
||||
end
|
||||
|
||||
def compare(%{calendar: calendar1} = date1, %{calendar: calendar2} = date2) do
|
||||
if Calendar.compatible_calendars?(calendar1, calendar2) do
|
||||
def compare(date1, date2) do
|
||||
if Calendar.compatible_calendars?(date1.calendar, date2.calendar) do
|
||||
case {to_iso_days(date1), to_iso_days(date2)} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
@@ -708,12 +614,11 @@ defmodule Date do
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def to_iso_days(%{calendar: Calendar.ISO, year: year, month: month, day: day}) do
|
||||
defp to_iso_days(%{calendar: Calendar.ISO, year: year, month: month, day: day}) do
|
||||
{Calendar.ISO.date_to_iso_days(year, month, day), {0, 86_400_000_000}}
|
||||
end
|
||||
|
||||
def to_iso_days(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
defp to_iso_days(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.naive_datetime_to_iso_days(year, month, day, 0, 0, 0, {0, 0})
|
||||
end
|
||||
|
||||
@@ -734,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])
|
||||
@@ -750,129 +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], :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 """
|
||||
@@ -948,14 +732,8 @@ defmodule Date do
|
||||
@spec year_of_era(Calendar.date()) :: {Calendar.year(), non_neg_integer()}
|
||||
def year_of_era(date)
|
||||
|
||||
def year_of_era(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
# TODO: Remove me on 1.17
|
||||
# The behaviour implementation already warns on missing callback.
|
||||
if function_exported?(calendar, :year_of_era, 3) do
|
||||
calendar.year_of_era(year, month, day)
|
||||
else
|
||||
calendar.year_of_era(year)
|
||||
end
|
||||
def year_of_era(%{calendar: calendar, year: year}) do
|
||||
calendar.year_of_era(year)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -982,49 +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(date)
|
||||
|
||||
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(date)
|
||||
|
||||
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
|
||||
@@ -1034,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
|
||||
|
||||
@@ -2,13 +2,12 @@ defmodule Date.Range do
|
||||
@moduledoc """
|
||||
Returns an inclusive range between dates.
|
||||
|
||||
Ranges must be created with the `Date.range/2` or `Date.range/3` function.
|
||||
Ranges must be created with the `Date.range/2` function.
|
||||
|
||||
The following fields are public:
|
||||
|
||||
* `:first` - the initial date on the range
|
||||
* `:last` - the last date on the range
|
||||
* `:step` - (since v1.12.0) the step
|
||||
|
||||
The remaining fields are private and should not be accessed.
|
||||
"""
|
||||
@@ -16,134 +15,99 @@ defmodule Date.Range do
|
||||
@type t :: %__MODULE__{
|
||||
first: Date.t(),
|
||||
last: Date.t(),
|
||||
first_in_iso_days: days(),
|
||||
last_in_iso_days: days(),
|
||||
step: pos_integer | neg_integer
|
||||
first_in_iso_days: iso_days(),
|
||||
last_in_iso_days: iso_days()
|
||||
}
|
||||
|
||||
@typep days() :: integer()
|
||||
@typep iso_days() :: Calendar.iso_days()
|
||||
|
||||
@enforce_keys [:first, :last, :first_in_iso_days, :last_in_iso_days, :step]
|
||||
defstruct [:first, :last, :first_in_iso_days, :last_in_iso_days, :step]
|
||||
defstruct [:first, :last, :first_in_iso_days, :last_in_iso_days]
|
||||
|
||||
defimpl Enumerable do
|
||||
def member?(
|
||||
%Date.Range{
|
||||
first: %{calendar: calendar},
|
||||
first_in_iso_days: first_days,
|
||||
last_in_iso_days: last_days,
|
||||
step: step
|
||||
} = range,
|
||||
%Date{calendar: calendar} = date
|
||||
) do
|
||||
{days, _} = Date.to_iso_days(date)
|
||||
def member?(%{first: %{calendar: calendar}} = range, %Date{calendar: calendar} = date) do
|
||||
%{
|
||||
first: first,
|
||||
last: last,
|
||||
first_in_iso_days: first_in_iso_days,
|
||||
last_in_iso_days: last_in_iso_days
|
||||
} = range
|
||||
|
||||
cond do
|
||||
empty?(range) ->
|
||||
{:ok, false}
|
||||
%{year: first_year, month: first_month, day: first_day} = first
|
||||
%{year: last_year, month: last_month, day: last_day} = last
|
||||
%{year: year, month: month, day: day} = date
|
||||
first = {first_year, first_month, first_day}
|
||||
last = {last_year, last_month, last_day}
|
||||
date = {year, month, day}
|
||||
|
||||
first_days <= last_days ->
|
||||
{:ok, first_days <= days and days <= last_days and rem(days - first_days, step) == 0}
|
||||
|
||||
true ->
|
||||
{:ok, last_days <= days and days <= first_days and rem(days - first_days, step) == 0}
|
||||
if first_in_iso_days <= last_in_iso_days do
|
||||
{:ok, date >= first and date <= last}
|
||||
else
|
||||
{:ok, date >= last and date <= first}
|
||||
end
|
||||
end
|
||||
|
||||
def member?(%Date.Range{step: _}, _) do
|
||||
def member?(_, _) do
|
||||
{:ok, false}
|
||||
end
|
||||
|
||||
# TODO: Remove me on v2.0
|
||||
def member?(
|
||||
%{__struct__: Date.Range, first_in_iso_days: first_days, last_in_iso_days: last_days} =
|
||||
date_range,
|
||||
date
|
||||
) do
|
||||
step = if first_days <= last_days, do: 1, else: -1
|
||||
member?(Map.put(date_range, :step, step), date)
|
||||
def count(%{first_in_iso_days: first, last_in_iso_days: last}) do
|
||||
{:ok, abs(first - last) + 1}
|
||||
end
|
||||
|
||||
def count(range) do
|
||||
{:ok, size(range)}
|
||||
def slice(range) do
|
||||
%{
|
||||
first_in_iso_days: first,
|
||||
last_in_iso_days: last,
|
||||
first: %{calendar: calendar}
|
||||
} = range
|
||||
|
||||
if first <= last do
|
||||
{:ok, last - first + 1, &slice_asc(first + &1, &2, calendar)}
|
||||
else
|
||||
{:ok, first - last + 1, &slice_desc(first - &1, &2, calendar)}
|
||||
end
|
||||
end
|
||||
|
||||
def slice(
|
||||
%Date.Range{
|
||||
first_in_iso_days: first,
|
||||
first: %{calendar: calendar},
|
||||
step: step
|
||||
} = range
|
||||
) do
|
||||
{:ok, size(range), &slice(first + &1 * step, step + &3 - 1, &2, calendar)}
|
||||
defp slice_asc(current, 1, calendar), do: [date_from_iso_days(current, calendar)]
|
||||
|
||||
defp slice_asc(current, remaining, calendar) do
|
||||
[date_from_iso_days(current, calendar) | slice_asc(current + 1, remaining - 1, calendar)]
|
||||
end
|
||||
|
||||
# TODO: Remove me on v2.0
|
||||
def slice(
|
||||
%{__struct__: Date.Range, first_in_iso_days: first_days, last_in_iso_days: last_days} =
|
||||
date_range
|
||||
) do
|
||||
step = if first_days <= last_days, do: 1, else: -1
|
||||
slice(Map.put(date_range, :step, step))
|
||||
defp slice_desc(current, 1, calendar), do: [date_from_iso_days(current, calendar)]
|
||||
|
||||
defp slice_desc(current, remaining, calendar) do
|
||||
[date_from_iso_days(current, calendar) | slice_desc(current - 1, remaining - 1, calendar)]
|
||||
end
|
||||
|
||||
defp slice(current, _step, 1, calendar) do
|
||||
[date_from_iso_days(current, calendar)]
|
||||
def reduce(range, acc, fun) do
|
||||
%{
|
||||
first_in_iso_days: first_in_iso_days,
|
||||
last_in_iso_days: last_in_iso_days,
|
||||
first: %{calendar: calendar}
|
||||
} = range
|
||||
|
||||
up? = first_in_iso_days <= last_in_iso_days
|
||||
reduce(first_in_iso_days, last_in_iso_days, acc, fun, calendar, up?)
|
||||
end
|
||||
|
||||
defp slice(current, step, remaining, calendar) do
|
||||
[
|
||||
date_from_iso_days(current, calendar)
|
||||
| slice(current + step, step, remaining - 1, calendar)
|
||||
]
|
||||
end
|
||||
|
||||
def reduce(
|
||||
%Date.Range{
|
||||
first_in_iso_days: first_days,
|
||||
last_in_iso_days: last_days,
|
||||
first: %{calendar: calendar},
|
||||
step: step
|
||||
},
|
||||
acc,
|
||||
fun
|
||||
) do
|
||||
reduce(first_days, last_days, acc, fun, step, calendar)
|
||||
end
|
||||
|
||||
# TODO: Remove me on v2.0
|
||||
def reduce(
|
||||
%{__struct__: Date.Range, first_in_iso_days: first_days, last_in_iso_days: last_days} =
|
||||
date_range,
|
||||
acc,
|
||||
fun
|
||||
) do
|
||||
step = if first_days <= last_days, do: 1, else: -1
|
||||
reduce(Map.put(date_range, :step, step), acc, fun)
|
||||
end
|
||||
|
||||
defp reduce(_first_days, _last_days, {:halt, acc}, _fun, _step, _calendar) do
|
||||
defp reduce(_x, _y, {:halt, acc}, _fun, _calendar, _up?) do
|
||||
{:halted, acc}
|
||||
end
|
||||
|
||||
defp reduce(first_days, last_days, {:suspend, acc}, fun, step, calendar) do
|
||||
{:suspended, acc, &reduce(first_days, last_days, &1, fun, step, calendar)}
|
||||
defp reduce(x, y, {:suspend, acc}, fun, calendar, up?) do
|
||||
{:suspended, acc, &reduce(x, y, &1, fun, calendar, up?)}
|
||||
end
|
||||
|
||||
defp reduce(first_days, last_days, {:cont, acc}, fun, step, calendar)
|
||||
when step > 0 and first_days <= last_days
|
||||
when step < 0 and first_days >= last_days do
|
||||
reduce(
|
||||
first_days + step,
|
||||
last_days,
|
||||
fun.(date_from_iso_days(first_days, calendar), acc),
|
||||
fun,
|
||||
step,
|
||||
calendar
|
||||
)
|
||||
defp reduce(x, y, {:cont, acc}, fun, calendar, up? = true) when x <= y do
|
||||
reduce(x + 1, y, fun.(date_from_iso_days(x, calendar), acc), fun, calendar, up?)
|
||||
end
|
||||
|
||||
defp reduce(_, _, {:cont, acc}, _fun, _step, _calendar) do
|
||||
defp reduce(x, y, {:cont, acc}, fun, calendar, up? = false) when x >= y do
|
||||
reduce(x - 1, y, fun.(date_from_iso_days(x, calendar), acc), fun, calendar, up?)
|
||||
end
|
||||
|
||||
defp reduce(_, _, {:cont, acc}, _fun, _calendar, _up) do
|
||||
{:done, acc}
|
||||
end
|
||||
|
||||
@@ -158,70 +122,11 @@ defmodule Date.Range do
|
||||
|
||||
%Date{year: year, month: month, day: day, calendar: calendar}
|
||||
end
|
||||
|
||||
defp size(%Date.Range{first_in_iso_days: first_days, last_in_iso_days: last_days, step: step})
|
||||
when step > 0 and first_days > last_days,
|
||||
do: 0
|
||||
|
||||
defp size(%Date.Range{first_in_iso_days: first_days, last_in_iso_days: last_days, step: step})
|
||||
when step < 0 and first_days < last_days,
|
||||
do: 0
|
||||
|
||||
defp size(%Date.Range{first_in_iso_days: first_days, last_in_iso_days: last_days, step: step}),
|
||||
do: abs(div(last_days - first_days, step)) + 1
|
||||
|
||||
# TODO: Remove me on v2.0
|
||||
defp size(
|
||||
%{__struct__: Date.Range, first_in_iso_days: first_days, last_in_iso_days: last_days} =
|
||||
date_range
|
||||
) do
|
||||
step = if first_days <= last_days, do: 1, else: -1
|
||||
size(Map.put(date_range, :step, step))
|
||||
end
|
||||
|
||||
defp empty?(%Date.Range{
|
||||
first_in_iso_days: first_days,
|
||||
last_in_iso_days: last_days,
|
||||
step: step
|
||||
})
|
||||
when step > 0 and first_days > last_days,
|
||||
do: true
|
||||
|
||||
defp empty?(%Date.Range{
|
||||
first_in_iso_days: first_days,
|
||||
last_in_iso_days: last_days,
|
||||
step: step
|
||||
})
|
||||
when step < 0 and first_days < last_days,
|
||||
do: true
|
||||
|
||||
defp empty?(%Date.Range{step: _}), do: false
|
||||
|
||||
# TODO: Remove me on v2.0
|
||||
defp empty?(
|
||||
%{__struct__: Date.Range, first_in_iso_days: first_days, last_in_iso_days: last_days} =
|
||||
date_range
|
||||
) do
|
||||
step = if first_days <= last_days, do: 1, else: -1
|
||||
empty?(Map.put(date_range, :step, step))
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
import Kernel, except: [inspect: 2]
|
||||
|
||||
def inspect(%Date.Range{first: first, last: last, step: 1}, _) do
|
||||
"Date.range(" <> inspect(first) <> ", " <> inspect(last) <> ")"
|
||||
end
|
||||
|
||||
def inspect(%Date.Range{first: first, last: last, step: step}, _) do
|
||||
"Date.range(" <> inspect(first) <> ", " <> inspect(last) <> ", #{step})"
|
||||
end
|
||||
|
||||
# TODO: Remove me on v2.0
|
||||
def inspect(%{__struct__: Date.Range, first: first, last: last} = date_range, opts) do
|
||||
step = if first <= last, do: 1, else: -1
|
||||
inspect(Map.put(date_range, :step, step), opts)
|
||||
def inspect(%Date.Range{first: first, last: last}, _) do
|
||||
"#DateRange<" <> inspect(first) <> ", " <> inspect(last) <> ">"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+146
-630
File diff suppressed because it is too large
Load Diff
+167
-790
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@ defmodule NaiveDateTime do
|
||||
The NaiveDateTime struct contains the fields year, month, day, hour,
|
||||
minute, second, microsecond and calendar. New naive datetimes can be
|
||||
built with the `new/2` and `new/8` functions or using the
|
||||
`~N` (see `sigil_N/2`) sigil:
|
||||
`~N` (see `Kernel.sigil_N/2`) sigil:
|
||||
|
||||
iex> ~N[2000-01-01 23:00:07]
|
||||
~N[2000-01-01 23:00:07]
|
||||
@@ -36,18 +36,12 @@ defmodule NaiveDateTime do
|
||||
|
||||
Comparisons in Elixir using `==/2`, `>/2`, `</2` and similar are structural
|
||||
and based on the `NaiveDateTime` struct fields. For proper comparison
|
||||
between naive datetimes, use the `compare/2` function. The existence of the
|
||||
`compare/2` function in this module also allows using `Enum.min/2` and
|
||||
`Enum.max/2` functions to get the minimum and maximum naive datetime of an
|
||||
`Enum`. For example:
|
||||
|
||||
iex> Enum.min([~N[2020-01-01 23:00:07], ~N[2000-01-01 23:00:07]], NaiveDateTime)
|
||||
~N[2000-01-01 23:00:07]
|
||||
between naive datetimes, use the `compare/2` function.
|
||||
|
||||
## Using epochs
|
||||
|
||||
The `add/3` and `diff/3` functions can be used for computing date
|
||||
times or retrieving the number of seconds between instants.
|
||||
The `add/3` and `diff/3` functions can be used for computing with
|
||||
date times or retrieving the number of seconds between instants.
|
||||
For example, if there is an interest in computing the number of
|
||||
seconds from the Unix epoch (1970-01-01 00:00:00):
|
||||
|
||||
@@ -84,8 +78,6 @@ defmodule NaiveDateTime do
|
||||
microsecond: Calendar.microsecond()
|
||||
}
|
||||
|
||||
@seconds_per_day 24 * 60 * 60
|
||||
|
||||
@doc """
|
||||
Returns the current naive datetime in UTC.
|
||||
|
||||
@@ -125,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.
|
||||
|
||||
@@ -216,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)
|
||||
@@ -250,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.
|
||||
|
||||
@@ -335,38 +225,14 @@ 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`.
|
||||
|
||||
Accepts an `amount_to_add` in any `unit`. `unit` can be `:day`,
|
||||
`:hour`, `:minute`, `:second` or any subsecond precision from
|
||||
`t:System.time_unit/0`. It defaults to `:second`. Negative values
|
||||
will move backwards in time.
|
||||
|
||||
This function always considers the unit to be computed according to the `Calendar.ISO`.
|
||||
Accepts an `amount_to_add` in any `unit` available from `t:System.time_unit/0`.
|
||||
Negative values will move backwards in time.
|
||||
|
||||
## Examples
|
||||
|
||||
It uses seconds by default:
|
||||
|
||||
# adds seconds by default
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], 2)
|
||||
~N[2014-10-02 00:29:12]
|
||||
@@ -375,28 +241,18 @@ defmodule NaiveDateTime do
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], -2)
|
||||
~N[2014-10-02 00:29:08]
|
||||
|
||||
It can also work with subsecond precisions:
|
||||
|
||||
# can work with other units
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], 2_000, :millisecond)
|
||||
~N[2014-10-02 00:29:12.000]
|
||||
~N[2014-10-02 00:29:12]
|
||||
|
||||
As well as days/hours/minutes:
|
||||
# keeps the same precision
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10.021], 21, :second)
|
||||
~N[2014-10-02 00:29:31.021]
|
||||
|
||||
iex> NaiveDateTime.add(~N[2015-02-28 00:29:10], 2, :day)
|
||||
~N[2015-03-02 00:29:10]
|
||||
iex> NaiveDateTime.add(~N[2015-02-28 00:29:10], 36, :hour)
|
||||
~N[2015-03-01 12:29:10]
|
||||
iex> NaiveDateTime.add(~N[2015-02-28 00:29:10], 60, :minute)
|
||||
~N[2015-02-28 01:29:10]
|
||||
|
||||
This operation merges the precision of the naive date time with the given unit:
|
||||
|
||||
iex> result = NaiveDateTime.add(~N[2014-10-02 00:29:10], 21, :millisecond)
|
||||
~N[2014-10-02 00:29:10.021]
|
||||
iex> result.microsecond
|
||||
{21000, 3}
|
||||
|
||||
Operations on top of gregorian seconds or the Unix epoch are optimized:
|
||||
# changes below the precision will not be visible
|
||||
iex> hidden = NaiveDateTime.add(~N[2014-10-02 00:29:10], 21, :millisecond)
|
||||
iex> hidden.microsecond # ~N[2014-10-02 00:29:10]
|
||||
{21000, 0}
|
||||
|
||||
# from Gregorian seconds
|
||||
iex> NaiveDateTime.add(~N[0000-01-01 00:00:00], 63_579_428_950)
|
||||
@@ -413,29 +269,14 @@ defmodule NaiveDateTime do
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec add(Calendar.naive_datetime(), integer, :day | :hour | :minute | System.time_unit()) :: t
|
||||
def add(naive_datetime, amount_to_add, unit \\ :second)
|
||||
|
||||
def add(naive_datetime, amount_to_add, :day) when is_integer(amount_to_add) do
|
||||
add(naive_datetime, amount_to_add * 86400, :second)
|
||||
end
|
||||
|
||||
def add(naive_datetime, amount_to_add, :hour) when is_integer(amount_to_add) do
|
||||
add(naive_datetime, amount_to_add * 3600, :second)
|
||||
end
|
||||
|
||||
def add(naive_datetime, amount_to_add, :minute) when is_integer(amount_to_add) do
|
||||
add(naive_datetime, amount_to_add * 60, :second)
|
||||
end
|
||||
|
||||
@spec add(Calendar.naive_datetime(), integer, System.time_unit()) :: t
|
||||
def add(
|
||||
%{microsecond: {_, precision}, calendar: calendar} = naive_datetime,
|
||||
amount_to_add,
|
||||
unit
|
||||
unit \\ :second
|
||||
)
|
||||
when is_integer(amount_to_add) do
|
||||
ppd = System.convert_time_unit(86400, :second, unit)
|
||||
precision = max(Calendar.ISO.time_unit_to_precision(unit), precision)
|
||||
|
||||
naive_datetime
|
||||
|> to_iso_days()
|
||||
@@ -446,11 +287,10 @@ defmodule NaiveDateTime do
|
||||
@doc """
|
||||
Subtracts `naive_datetime2` from `naive_datetime1`.
|
||||
|
||||
The answer can be returned in any `:day`, `:hour`, `:minute`, or any `unit`
|
||||
available from `t:System.time_unit/0`. The unit is measured according to
|
||||
`Calendar.ISO` and defaults to `:second`.
|
||||
The answer can be returned in any `unit` available from `t:System.time_unit/0`.
|
||||
|
||||
Fractional results are not supported and are truncated.
|
||||
This function returns the difference in seconds where seconds are measured
|
||||
according to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -458,57 +298,24 @@ defmodule NaiveDateTime do
|
||||
2
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:12], ~N[2014-10-02 00:29:10], :microsecond)
|
||||
2_000_000
|
||||
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10.042], ~N[2014-10-02 00:29:10.021])
|
||||
0
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10.042], ~N[2014-10-02 00:29:10.021], :millisecond)
|
||||
21
|
||||
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10], ~N[2014-10-02 00:29:12])
|
||||
-2
|
||||
iex> NaiveDateTime.diff(~N[-0001-10-02 00:29:10], ~N[-0001-10-02 00:29:12])
|
||||
-2
|
||||
|
||||
It can also compute the difference in days, hours, or minutes:
|
||||
|
||||
iex> NaiveDateTime.diff(~N[2014-10-10 00:29:10], ~N[2014-10-02 00:29:10], :day)
|
||||
8
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 12:29:10], ~N[2014-10-02 00:29:10], :hour)
|
||||
12
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:39:10], ~N[2014-10-02 00:29:10], :minute)
|
||||
10
|
||||
|
||||
But it also rounds incomplete days to zero:
|
||||
|
||||
iex> NaiveDateTime.diff(~N[2014-10-10 00:29:09], ~N[2014-10-02 00:29:10], :day)
|
||||
7
|
||||
# to Gregorian seconds
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10], ~N[0000-01-01 00:00:00])
|
||||
63579428950
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec diff(
|
||||
Calendar.naive_datetime(),
|
||||
Calendar.naive_datetime(),
|
||||
:day | :hour | :minute | System.time_unit()
|
||||
) :: integer
|
||||
|
||||
def diff(naive_datetime1, naive_datetime2, unit \\ :second)
|
||||
|
||||
def diff(naive_datetime1, naive_datetime2, :day) do
|
||||
diff(naive_datetime1, naive_datetime2, :second) |> div(86400)
|
||||
end
|
||||
|
||||
def diff(naive_datetime1, naive_datetime2, :hour) do
|
||||
diff(naive_datetime1, naive_datetime2, :second) |> div(3600)
|
||||
end
|
||||
|
||||
def diff(naive_datetime1, naive_datetime2, :minute) do
|
||||
diff(naive_datetime1, naive_datetime2, :second) |> div(60)
|
||||
end
|
||||
|
||||
@spec diff(Calendar.naive_datetime(), Calendar.naive_datetime(), System.time_unit()) :: integer
|
||||
def diff(
|
||||
%{calendar: calendar1} = naive_datetime1,
|
||||
%{calendar: calendar2} = naive_datetime2,
|
||||
unit
|
||||
unit \\ :second
|
||||
) do
|
||||
if not Calendar.compatible_calendars?(calendar1, calendar2) do
|
||||
raise ArgumentError,
|
||||
@@ -669,7 +476,7 @@ defmodule NaiveDateTime do
|
||||
|
||||
@doc """
|
||||
Parses the extended "Date and time of day" format described by
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Time zone offset may be included in the string but they will be
|
||||
simply discarded as such information is not included in naive date
|
||||
@@ -678,6 +485,9 @@ defmodule NaiveDateTime do
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
The year parsed by this function is limited to four digits and,
|
||||
while ISO 8601 allows datetimes to specify 24:00:00 as the zero
|
||||
hour of the next day, this notation is not supported by Elixir.
|
||||
Note leap seconds are not supported by the built-in Calendar.ISO.
|
||||
|
||||
## Examples
|
||||
@@ -724,27 +534,41 @@ 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
|
||||
|
||||
@doc """
|
||||
Parses the extended "Date and time of day" format described by
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Raises if the format is invalid.
|
||||
|
||||
@@ -772,7 +596,7 @@ defmodule NaiveDateTime do
|
||||
|
||||
@doc """
|
||||
Converts the given naive datetime to
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
By default, `NaiveDateTime.to_iso8601/2` returns naive datetimes formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through passing the `:basic` option.
|
||||
@@ -816,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
|
||||
@@ -840,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},
|
||||
@@ -912,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.
|
||||
|
||||
@@ -1132,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,
|
||||
@@ -1186,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,
|
||||
@@ -1194,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
|
||||
|
||||
+67
-196
@@ -4,7 +4,7 @@ defmodule Time do
|
||||
|
||||
The Time struct contains the fields hour, minute, second and microseconds.
|
||||
New times can be built with the `new/4` function or using the
|
||||
`~T` (see `sigil_T/2`) sigil:
|
||||
`~T` (see `Kernel.sigil_T/2`) sigil:
|
||||
|
||||
iex> ~T[23:00:07.001]
|
||||
~T[23:00:07.001]
|
||||
@@ -31,12 +31,7 @@ defmodule Time do
|
||||
|
||||
Comparisons in Elixir using `==/2`, `>/2`, `</2` and similar are structural
|
||||
and based on the `Time` struct fields. For proper comparison between
|
||||
times, use the `compare/2` function. The existence of the `compare/2`
|
||||
function in this module also allows using `Enum.min/2` and `Enum.max/2`
|
||||
functions to get the minimum and maximum time of an `Enum`. For example:
|
||||
|
||||
iex> Enum.min([~T[23:00:07.001], ~T[10:00:07.001]], Time)
|
||||
~T[10:00:07.001]
|
||||
times, use the `compare/2` function.
|
||||
"""
|
||||
|
||||
@enforce_keys [:hour, :minute, :second]
|
||||
@@ -51,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.
|
||||
@@ -116,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)
|
||||
@@ -145,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.
|
||||
|
||||
@@ -216,7 +172,7 @@ defmodule Time do
|
||||
|
||||
@doc """
|
||||
Parses the extended "Local time" format described by
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Time zone offset may be included in the string but they will be
|
||||
simply discarded as such information is not included in times.
|
||||
@@ -224,6 +180,12 @@ defmodule Time do
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
Time representations with reduced accuracy are not supported.
|
||||
|
||||
Note that while ISO 8601 allows times to specify 24:00:00 as the
|
||||
zero hour of the next day, this notation is not supported by Elixir.
|
||||
Leap seconds are not supported as well by the built-in Calendar.ISO.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.from_iso8601("23:50:07")
|
||||
@@ -251,18 +213,36 @@ 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
|
||||
|
||||
@doc """
|
||||
Parses the extended "Local time" format described by
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Raises if the format is invalid.
|
||||
|
||||
@@ -289,7 +269,7 @@ defmodule Time do
|
||||
|
||||
@doc """
|
||||
Converts the given time to
|
||||
[ISO 8601:2019](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
By default, `Time.to_iso8601/2` returns times formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through
|
||||
@@ -397,72 +377,10 @@ defmodule Time do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a number of seconds after midnight to a `Time` struct.
|
||||
Adds the `number` of `unit`s to the given `time`.
|
||||
|
||||
## 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 `amount_to_add` of `unit`s to the given `time`.
|
||||
|
||||
Accepts an `amount_to_add` in any `unit`. `unit` can be `:day`,
|
||||
`:hour`, `:minute`, `:second` or any subsecond precision from
|
||||
`t:System.time_unit/0`. It defaults to `:second`. Negative values
|
||||
will move backwards in time.
|
||||
|
||||
This function always consider the unit to be computed according
|
||||
to the `Calendar.ISO`.
|
||||
This function accepts the `number` measured according to `Calendar.ISO`.
|
||||
The time is returned in the same calendar as it was given in.
|
||||
|
||||
Note the result value represents the time of day, meaning that it is cyclic,
|
||||
for instance, it will never go over 24 hours for the ISO calendar.
|
||||
@@ -470,64 +388,30 @@ defmodule Time do
|
||||
## Examples
|
||||
|
||||
iex> Time.add(~T[10:00:00], 27000)
|
||||
~T[17:30:00]
|
||||
~T[17:30:00.000000]
|
||||
iex> Time.add(~T[11:00:00.005], 2400)
|
||||
~T[11:40:00.005]
|
||||
iex> Time.add(~T[00:00:00.000], 86_399_999, :millisecond)
|
||||
~T[23:59:59.999]
|
||||
|
||||
Negative values are allowed:
|
||||
|
||||
iex> Time.add(~T[23:00:00], -60)
|
||||
~T[22:59:00]
|
||||
|
||||
Note that the time is cyclic:
|
||||
|
||||
~T[11:40:00.005000]
|
||||
iex> Time.add(~T[00:00:00], 86_399_999, :millisecond)
|
||||
~T[23:59:59.999000]
|
||||
iex> Time.add(~T[17:10:05], 86400)
|
||||
~T[17:10:05]
|
||||
|
||||
Hours and minutes are also supported:
|
||||
|
||||
iex> Time.add(~T[17:10:05], 2, :hour)
|
||||
~T[19:10:05]
|
||||
iex> Time.add(~T[17:10:05], 30, :minute)
|
||||
~T[17:40:05]
|
||||
|
||||
This operation merges the precision of the time with the given unit:
|
||||
|
||||
iex> result = Time.add(~T[00:29:10], 21, :millisecond)
|
||||
~T[00:29:10.021]
|
||||
iex> result.microsecond
|
||||
{21000, 3}
|
||||
~T[17:10:05.000000]
|
||||
iex> Time.add(~T[23:00:00], -60)
|
||||
~T[22:59:00.000000]
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec add(Calendar.time(), integer, :hour | :minute | System.time_unit()) :: t
|
||||
def add(time, amount_to_add, unit \\ :second)
|
||||
|
||||
def add(time, amount_to_add, :hour) when is_integer(amount_to_add) do
|
||||
add(time, amount_to_add * 3600, :second)
|
||||
end
|
||||
|
||||
def add(time, amount_to_add, :minute) when is_integer(amount_to_add) do
|
||||
add(time, amount_to_add * 60, :second)
|
||||
end
|
||||
|
||||
def add(%{calendar: calendar, microsecond: {_, precision}} = time, amount_to_add, unit)
|
||||
when is_integer(amount_to_add) do
|
||||
amount_to_add = System.convert_time_unit(amount_to_add, unit, :microsecond)
|
||||
total = time_to_microseconds(time) + amount_to_add
|
||||
@spec add(Calendar.time(), integer, System.time_unit()) :: t
|
||||
def add(%{calendar: calendar} = time, number, unit \\ :second) when is_integer(number) do
|
||||
number = System.convert_time_unit(number, unit, :microsecond)
|
||||
total = time_to_microseconds(time) + number
|
||||
parts = Integer.mod(total, @parts_per_day)
|
||||
precision = max(Calendar.ISO.time_unit_to_precision(unit), precision)
|
||||
|
||||
{hour, minute, second, {microsecond, _}} =
|
||||
calendar.time_from_day_fraction({parts, @parts_per_day})
|
||||
{hour, minute, second, microsecond} = calendar.time_from_day_fraction({parts, @parts_per_day})
|
||||
|
||||
%Time{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond, precision},
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
}
|
||||
end
|
||||
@@ -690,16 +574,16 @@ 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 `:hour`, `:minute`, `:second` or any
|
||||
subsecond `unit` available from `t:System.time_unit/0`. If the first time
|
||||
value is earlier than the second, a negative number is returned.
|
||||
The answer can be returned in any `unit` available from
|
||||
`t:System.time_unit/0`. If the first unit is smaller than
|
||||
the second, a negative number is returned.
|
||||
|
||||
The unit is measured according to `Calendar.ISO` and defaults to `:second`.
|
||||
Fractional results are not supported and are truncated.
|
||||
This function returns the difference in seconds where seconds
|
||||
are measured according to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -720,38 +604,25 @@ defmodule Time do
|
||||
iex> Time.diff(~T[00:29:10], ~T[00:29:12], :microsecond)
|
||||
-2_000_000
|
||||
|
||||
iex> Time.diff(~T[02:29:10], ~T[00:29:10], :hour)
|
||||
2
|
||||
iex> Time.diff(~T[02:29:10], ~T[00:29:11], :hour)
|
||||
1
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec diff(Calendar.time(), Calendar.time(), :hour | :minute | System.time_unit()) :: integer
|
||||
@spec diff(Calendar.time(), Calendar.time(), System.time_unit()) :: integer
|
||||
def diff(time1, time2, unit \\ :second)
|
||||
|
||||
def diff(time1, time2, :hour) do
|
||||
diff(time1, time2, :second) |> div(3600)
|
||||
end
|
||||
|
||||
def diff(time1, time2, :minute) do
|
||||
diff(time1, time2, :second) |> div(60)
|
||||
end
|
||||
|
||||
def diff(
|
||||
%{
|
||||
calendar: Calendar.ISO,
|
||||
hour: hour1,
|
||||
minute: minute1,
|
||||
second: second1,
|
||||
microsecond: {microsecond1, _}
|
||||
microsecond: {microsecond1, @parts_per_day}
|
||||
},
|
||||
%{
|
||||
calendar: Calendar.ISO,
|
||||
hour: hour2,
|
||||
minute: minute2,
|
||||
second: second2,
|
||||
microsecond: {microsecond2, _}
|
||||
microsecond: {microsecond2, @parts_per_day}
|
||||
},
|
||||
unit
|
||||
) do
|
||||
@@ -822,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"
|
||||
|
||||
+320
-953
File diff suppressed because it is too large
Load Diff
+447
-509
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,7 @@ defmodule Code.Identifier do
|
||||
def unary_op(op) do
|
||||
cond do
|
||||
op in [:&] -> {:non_associative, 90}
|
||||
op in [:!, :^, :not, :+, :-, :"~~~"] -> {:non_associative, 300}
|
||||
op in [:!, :^, :not, :+, :-, :~~~] -> {:non_associative, 300}
|
||||
op in [:@] -> {:non_associative, 320}
|
||||
true -> :error
|
||||
end
|
||||
@@ -37,23 +37,163 @@ defmodule Code.Identifier do
|
||||
op in [:"::"] -> {:right, 60}
|
||||
op in [:|] -> {:right, 70}
|
||||
op in [:=] -> {:right, 100}
|
||||
op in [:||, :|||, :or] -> {:left, 120}
|
||||
op in [:&&, :&&&, :and] -> {:left, 130}
|
||||
op in [:==, :!=, :=~, :===, :!==] -> {:left, 140}
|
||||
op in [:<, :<=, :>=, :>] -> {:left, 150}
|
||||
op in [:|>, :<<<, :>>>, :<~, :~>, :<<~, :~>>, :<~>, :"<|>"] -> {:left, 160}
|
||||
op in [:in] -> {:left, 170}
|
||||
op in [:"^^^"] -> {:left, 180}
|
||||
op in [:"//"] -> {:right, 190}
|
||||
op in [:++, :--, :.., :<>, :+++, :---] -> {:right, 200}
|
||||
op in [:||, :|||, :or] -> {:left, 130}
|
||||
op in [:&&, :&&&, :and] -> {:left, 140}
|
||||
op in [:==, :!=, :=~, :===, :!==] -> {:left, 150}
|
||||
op in [:<, :<=, :>=, :>] -> {:left, 160}
|
||||
op in [:|>, :<<<, :>>>, :<~, :~>, :<<~, :~>>, :<~>, :<|>] -> {:left, 170}
|
||||
op in [:in] -> {:left, 180}
|
||||
op in [:^^^] -> {:left, 190}
|
||||
op in [:++, :--, :.., :<>] -> {:right, 200}
|
||||
op in [:+, :-] -> {:left, 210}
|
||||
op in [:*, :/] -> {:left, 220}
|
||||
op in [:**] -> {:left, 230}
|
||||
op in [:.] -> {:left, 310}
|
||||
true -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Classifies the given atom into one of the following categories:
|
||||
|
||||
* `:alias` - a valid Elixir alias, like `Foo`, `Foo.Bar` and so on
|
||||
|
||||
* `:callable_local` - an atom that can be used as a local call;
|
||||
this category includes identifiers like `:foo`
|
||||
|
||||
* `:callable_operator` - all callable operators, such as `:<>`. Note
|
||||
operators such as `:..` are not callable because of ambiguity
|
||||
|
||||
* `:not_atomable` - callable operators that must be wrapped in quotes when
|
||||
defined as an atom. For example, `::` must be written as `:"::"` to avoid
|
||||
the ambiguity between the atom and the keyword identifier
|
||||
|
||||
* `:not_callable` - an atom that cannot be used as a function call after the
|
||||
`.` operator (for example, `:<<>>` is not callable because `Foo.<<>>` is a
|
||||
syntax error); this category includes atoms like `:Foo`, since they are
|
||||
valid identifiers but they need quotes to be used in function calls
|
||||
(`Foo."Bar"`)
|
||||
|
||||
* `:other` - any other atom (these are usually escaped when inspected, like
|
||||
`:"foo and bar"`)
|
||||
|
||||
"""
|
||||
def classify(atom) when is_atom(atom) do
|
||||
charlist = Atom.to_charlist(atom)
|
||||
|
||||
cond do
|
||||
atom in [:%, :%{}, :{}, :<<>>, :..., :.., :., :->] ->
|
||||
:not_callable
|
||||
|
||||
atom in [:"::"] ->
|
||||
:not_atomable
|
||||
|
||||
unary_op(atom) != :error or binary_op(atom) != :error ->
|
||||
:callable_operator
|
||||
|
||||
valid_alias?(charlist) ->
|
||||
:alias
|
||||
|
||||
true ->
|
||||
case :elixir_config.get(:identifier_tokenizer, String.Tokenizer).tokenize(charlist) do
|
||||
{kind, _acc, [], _, _, special} ->
|
||||
if kind == :identifier and not :lists.member(?@, special) do
|
||||
:callable_local
|
||||
else
|
||||
:not_callable
|
||||
end
|
||||
|
||||
_ ->
|
||||
:other
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp valid_alias?('Elixir' ++ rest), do: valid_alias_piece?(rest)
|
||||
defp valid_alias?(_other), do: false
|
||||
|
||||
defp valid_alias_piece?([?., char | rest]) when char >= ?A and char <= ?Z,
|
||||
do: valid_alias_piece?(trim_leading_while_valid_identifier(rest))
|
||||
|
||||
defp valid_alias_piece?([]), do: true
|
||||
defp valid_alias_piece?(_other), do: false
|
||||
|
||||
defp trim_leading_while_valid_identifier([char | rest])
|
||||
when char >= ?a and char <= ?z
|
||||
when char >= ?A and char <= ?Z
|
||||
when char >= ?0 and char <= ?9
|
||||
when char == ?_ do
|
||||
trim_leading_while_valid_identifier(rest)
|
||||
end
|
||||
|
||||
defp trim_leading_while_valid_identifier(other) do
|
||||
other
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inspects the identifier as an atom.
|
||||
"""
|
||||
def inspect_as_atom(atom) when is_nil(atom) or is_boolean(atom) do
|
||||
Atom.to_string(atom)
|
||||
end
|
||||
|
||||
def inspect_as_atom(atom) when is_atom(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
case classify(atom) do
|
||||
:alias ->
|
||||
case binary do
|
||||
binary when binary in ["Elixir", "Elixir.Elixir"] -> binary
|
||||
"Elixir.Elixir." <> _rest -> binary
|
||||
"Elixir." <> rest -> rest
|
||||
end
|
||||
|
||||
type when type in [:callable_local, :callable_operator, :not_callable] ->
|
||||
":" <> binary
|
||||
|
||||
_ ->
|
||||
{escaped, _} = escape(binary, ?")
|
||||
IO.iodata_to_binary([?:, ?", escaped, ?"])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inspects the given identifier as a key.
|
||||
"""
|
||||
def inspect_as_key(atom) when is_atom(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
case classify(atom) do
|
||||
type when type in [:callable_local, :callable_operator, :not_callable] ->
|
||||
IO.iodata_to_binary([binary, ?:])
|
||||
|
||||
_ ->
|
||||
{escaped, _} = escape(binary, ?")
|
||||
IO.iodata_to_binary([?", escaped, ?", ?:])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inspects the given identifier as a function name.
|
||||
"""
|
||||
def inspect_as_function(atom) when is_atom(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
case classify(atom) do
|
||||
type when type in [:callable_local, :callable_operator, :not_atomable] ->
|
||||
binary
|
||||
|
||||
type ->
|
||||
escaped =
|
||||
if type in [:not_callable, :alias] do
|
||||
binary
|
||||
else
|
||||
elem(escape(binary, ?"), 0)
|
||||
end
|
||||
|
||||
IO.iodata_to_binary([?", escaped, ?"])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Extracts the name and arity of the parent from the anonymous function identifier.
|
||||
"""
|
||||
@@ -71,12 +211,8 @@ defmodule Code.Identifier do
|
||||
@doc """
|
||||
Escapes the given identifier.
|
||||
"""
|
||||
@spec escape(binary(), char() | nil, :infinity | non_neg_integer, (char() -> iolist() | false)) ::
|
||||
{escaped :: iolist(), remaining :: binary()}
|
||||
def escape(binary, char, limit \\ :infinity, fun \\ &escape_map/1)
|
||||
when ((char in 0..0x10FFFF or is_nil(char)) and limit == :infinity) or
|
||||
(is_integer(limit) and limit >= 0) do
|
||||
escape(binary, char, limit, [], fun)
|
||||
def escape(other, char, count \\ :infinity, fun \\ &escape_map/1) do
|
||||
escape(other, char, count, [], fun)
|
||||
end
|
||||
|
||||
defp escape(<<_, _::binary>> = binary, _char, 0, acc, _fun) do
|
||||
|
||||
@@ -1,600 +0,0 @@
|
||||
defmodule Code.Normalizer do
|
||||
@moduledoc false
|
||||
|
||||
defguard is_literal(x)
|
||||
when is_integer(x) or
|
||||
is_float(x) or
|
||||
is_binary(x) or
|
||||
is_atom(x)
|
||||
|
||||
@doc """
|
||||
Wraps literals in the quoted expression to conform to the AST format expected
|
||||
by the formatter.
|
||||
"""
|
||||
def normalize(quoted, opts \\ []) do
|
||||
line = Keyword.get(opts, :line, nil)
|
||||
escape = Keyword.get(opts, :escape, true)
|
||||
locals_without_parens = Keyword.get(opts, :locals_without_parens, [])
|
||||
|
||||
state = %{
|
||||
escape: escape,
|
||||
parent_meta: [line: line],
|
||||
locals_without_parens: locals_without_parens ++ Code.Formatter.locals_without_parens()
|
||||
}
|
||||
|
||||
do_normalize(quoted, state)
|
||||
end
|
||||
|
||||
# Wrapped literals should receive the block meta
|
||||
defp do_normalize({:__block__, meta, [literal]}, state)
|
||||
when not is_tuple(literal) or tuple_size(literal) == 2 do
|
||||
normalize_literal(literal, meta, state)
|
||||
end
|
||||
|
||||
# Only normalize the first argument of an alias if it's not an atom
|
||||
defp do_normalize({:__aliases__, meta, [first | rest]}, state) when not is_atom(first) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
first = do_normalize(first, %{state | parent_meta: meta})
|
||||
{:__aliases__, meta, [first | rest]}
|
||||
end
|
||||
|
||||
defp do_normalize({:__aliases__, _, _} = quoted, _state) do
|
||||
quoted
|
||||
end
|
||||
|
||||
# Skip captured arguments like &1
|
||||
defp do_normalize({:&, meta, [term]}, state) when is_integer(term) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
{:&, meta, [term]}
|
||||
end
|
||||
|
||||
# Ranges
|
||||
defp do_normalize(left..right//step, state) do
|
||||
left = do_normalize(left, state)
|
||||
right = do_normalize(right, state)
|
||||
meta = meta_line(state)
|
||||
|
||||
if step == 1 do
|
||||
{:.., meta, [left, right]}
|
||||
else
|
||||
step = do_normalize(step, state)
|
||||
{:"..//", meta, [left, right, step]}
|
||||
end
|
||||
end
|
||||
|
||||
# Bit containers
|
||||
defp do_normalize({:<<>>, _, args} = quoted, state) when is_list(args) do
|
||||
normalize_bitstring(quoted, state)
|
||||
end
|
||||
|
||||
# Atoms with interpolations
|
||||
defp do_normalize(
|
||||
{{:., dot_meta, [:erlang, :binary_to_atom]}, call_meta,
|
||||
[{:<<>>, _, parts} = string, :utf8]},
|
||||
state
|
||||
)
|
||||
when is_list(parts) do
|
||||
dot_meta = patch_meta_line(dot_meta, state.parent_meta)
|
||||
call_meta = patch_meta_line(call_meta, dot_meta)
|
||||
|
||||
utf8 =
|
||||
if parts == [] or binary_interpolated?(parts) do
|
||||
# a non-normalized :utf8 atom signals an atom interpolation
|
||||
:utf8
|
||||
else
|
||||
normalize_literal(:utf8, [], state)
|
||||
end
|
||||
|
||||
string =
|
||||
if state.escape do
|
||||
normalize_bitstring(string, state, true)
|
||||
else
|
||||
normalize_bitstring(string, state)
|
||||
end
|
||||
|
||||
{{:., dot_meta, [:erlang, :binary_to_atom]}, call_meta, [string, utf8]}
|
||||
end
|
||||
|
||||
# Charlists with interpolations
|
||||
defp do_normalize({{:., dot_meta, [List, :to_charlist]}, call_meta, [parts]} = quoted, state) do
|
||||
if list_interpolated?(parts) do
|
||||
parts =
|
||||
Enum.map(parts, fn
|
||||
{{:., part_dot_meta, [Kernel, :to_string]}, part_call_meta, args} ->
|
||||
args = normalize_args(args, state)
|
||||
|
||||
{{:., part_dot_meta, [Kernel, :to_string]}, part_call_meta, args}
|
||||
|
||||
part when is_binary(part) ->
|
||||
if state.escape do
|
||||
maybe_escape_literal(part, state)
|
||||
else
|
||||
part
|
||||
end
|
||||
end)
|
||||
|
||||
{{:., dot_meta, [List, :to_charlist]}, call_meta, [parts]}
|
||||
else
|
||||
normalize_call(quoted, state)
|
||||
end
|
||||
end
|
||||
|
||||
# Don't normalize the `Access` atom in access syntax
|
||||
defp do_normalize({:., meta, [Access, :get]}, state) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
{:., meta, [Access, :get]}
|
||||
end
|
||||
|
||||
# Only normalize the left side of the dot operator
|
||||
# The right hand side is an atom in the AST but it's not an atom literal, so
|
||||
# it should not be wrapped
|
||||
defp do_normalize({:., meta, [left, right]}, state) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
|
||||
left = do_normalize(left, %{state | parent_meta: meta})
|
||||
|
||||
{:., meta, [left, right]}
|
||||
end
|
||||
|
||||
# A list of left to right arrows is not considered as a list literal, so it's not wrapped
|
||||
defp do_normalize([{:->, _, [_ | _]} | _] = quoted, state) do
|
||||
normalize_args(quoted, state)
|
||||
end
|
||||
|
||||
# left -> right
|
||||
defp do_normalize({:->, meta, [left, right]}, state) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
|
||||
left = normalize_args(left, %{state | parent_meta: meta})
|
||||
right = do_normalize(right, %{state | parent_meta: meta})
|
||||
{:->, meta, [left, right]}
|
||||
end
|
||||
|
||||
# Maps
|
||||
defp do_normalize({:%{}, meta, args}, state) when is_list(args) do
|
||||
meta =
|
||||
if meta == [] do
|
||||
line = state.parent_meta[:line]
|
||||
[line: line, closing: [line: line]]
|
||||
else
|
||||
meta
|
||||
end
|
||||
|
||||
state = %{state | parent_meta: meta}
|
||||
|
||||
args =
|
||||
case args do
|
||||
[{:|, pipe_meta, [left, right]}] ->
|
||||
left = do_normalize(left, state)
|
||||
right = normalize_map_args(right, state)
|
||||
[{:|, pipe_meta, [left, right]}]
|
||||
|
||||
[{_, _, _} = call] ->
|
||||
[do_normalize(call, state)]
|
||||
|
||||
args ->
|
||||
normalize_map_args(args, state)
|
||||
end
|
||||
|
||||
{:%{}, meta, args}
|
||||
end
|
||||
|
||||
# Sigils
|
||||
defp do_normalize({sigil, meta, [{:<<>>, _, args} = string, modifiers]} = quoted, state)
|
||||
when is_list(args) and is_atom(sigil) do
|
||||
case Atom.to_string(sigil) do
|
||||
<<"sigil_", _name>> ->
|
||||
meta =
|
||||
meta
|
||||
|> patch_meta_line(state.parent_meta)
|
||||
|> Keyword.put_new(:delimiter, "\"")
|
||||
|
||||
{sigil, meta, [do_normalize(string, %{state | parent_meta: meta}), modifiers]}
|
||||
|
||||
_ ->
|
||||
normalize_call(quoted, state)
|
||||
end
|
||||
end
|
||||
|
||||
# Tuples
|
||||
defp do_normalize({:{}, meta, args} = quoted, state) when is_list(args) do
|
||||
{last_arg, args} = List.pop_at(args, -1)
|
||||
|
||||
if args != [] and match?([_ | _], last_arg) and keyword?(last_arg) do
|
||||
args = normalize_args(args, state)
|
||||
kw_list = normalize_kw_args(last_arg, state, true)
|
||||
{:{}, meta, args ++ kw_list}
|
||||
else
|
||||
normalize_call(quoted, state)
|
||||
end
|
||||
end
|
||||
|
||||
# Module attributes
|
||||
defp do_normalize({:@, meta, [{name, name_meta, [value]}]}, state) do
|
||||
value =
|
||||
cond do
|
||||
keyword?(value) and value != [] ->
|
||||
normalize_kw_args(value, state, true)
|
||||
|
||||
is_list(value) ->
|
||||
normalize_literal(value, meta, state)
|
||||
|
||||
true ->
|
||||
do_normalize(value, state)
|
||||
end
|
||||
|
||||
{:@, meta, [{name, name_meta, [value]}]}
|
||||
end
|
||||
|
||||
# Regular blocks
|
||||
defp do_normalize({:__block__, meta, args}, state) when is_list(args) do
|
||||
{:__block__, meta, normalize_args(args, state)}
|
||||
end
|
||||
|
||||
# Calls
|
||||
defp do_normalize({_, _, args} = quoted, state) when is_list(args) do
|
||||
normalize_call(quoted, state)
|
||||
end
|
||||
|
||||
# Vars
|
||||
defp do_normalize({_, _, context} = quoted, _state) when is_atom(context) do
|
||||
quoted
|
||||
end
|
||||
|
||||
# Literals
|
||||
defp do_normalize(quoted, state) do
|
||||
normalize_literal(quoted, [], state)
|
||||
end
|
||||
|
||||
# Numbers
|
||||
defp normalize_literal(number, meta, state) when is_number(number) do
|
||||
meta =
|
||||
meta
|
||||
|> Keyword.put_new(:token, inspect(number))
|
||||
|> patch_meta_line(state.parent_meta)
|
||||
|
||||
{:__block__, meta, [number]}
|
||||
end
|
||||
|
||||
# Atom, Strings
|
||||
defp normalize_literal(literal, meta, state) when is_atom(literal) or is_binary(literal) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
literal = maybe_escape_literal(literal, state)
|
||||
|
||||
if is_atom(literal) and Macro.classify_atom(literal) == :alias and
|
||||
is_nil(meta[:delimiter]) do
|
||||
segments =
|
||||
case Atom.to_string(literal) do
|
||||
"Elixir" ->
|
||||
[:"Elixir"]
|
||||
|
||||
"Elixir." <> segments ->
|
||||
segments
|
||||
|> String.split(".")
|
||||
|> Enum.map(&String.to_atom/1)
|
||||
end
|
||||
|
||||
{:__aliases__, meta, segments}
|
||||
else
|
||||
{:__block__, meta, [literal]}
|
||||
end
|
||||
end
|
||||
|
||||
# 2-tuples
|
||||
defp normalize_literal({left, right}, meta, state) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
state = %{state | parent_meta: meta}
|
||||
|
||||
if match?([_ | _], right) and keyword?(right) do
|
||||
{:__block__, meta, [{do_normalize(left, state), normalize_kw_args(right, state, true)}]}
|
||||
else
|
||||
{:__block__, meta, [{do_normalize(left, state), do_normalize(right, state)}]}
|
||||
end
|
||||
end
|
||||
|
||||
# Lists
|
||||
defp normalize_literal(list, meta, state) when is_list(list) do
|
||||
if list != [] and List.ascii_printable?(list) do
|
||||
# It's a charlist
|
||||
list =
|
||||
if state.escape do
|
||||
{string, _} = Code.Identifier.escape(IO.chardata_to_string(list), nil)
|
||||
IO.iodata_to_binary(string) |> to_charlist()
|
||||
else
|
||||
list
|
||||
end
|
||||
|
||||
meta =
|
||||
meta
|
||||
|> Keyword.put_new(:delimiter, "'")
|
||||
|> patch_meta_line(state.parent_meta)
|
||||
|
||||
{:__block__, meta, [list]}
|
||||
else
|
||||
meta =
|
||||
if line = state.parent_meta[:line] do
|
||||
meta
|
||||
|> Keyword.put_new(:closing, line: line)
|
||||
|> patch_meta_line(state.parent_meta)
|
||||
else
|
||||
meta
|
||||
end
|
||||
|
||||
{:__block__, meta, [normalize_kw_args(list, state, false)]}
|
||||
end
|
||||
end
|
||||
|
||||
# Probably an invalid value, wrap it and send it upstream
|
||||
defp normalize_literal(quoted, meta, _state) do
|
||||
{:__block__, meta, [quoted]}
|
||||
end
|
||||
|
||||
defp normalize_call({form, meta, args}, state) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
arity = length(args)
|
||||
|
||||
# Only normalize the form if it's a qualified call
|
||||
form =
|
||||
if is_atom(form) do
|
||||
form
|
||||
else
|
||||
do_normalize(form, %{state | parent_meta: meta})
|
||||
end
|
||||
|
||||
meta =
|
||||
if is_nil(meta[:no_parens]) and is_nil(meta[:closing]) and is_nil(meta[:do]) and
|
||||
not Code.Formatter.local_without_parens?(form, arity, state.locals_without_parens) do
|
||||
[closing: [line: meta[:line]]] ++ meta
|
||||
else
|
||||
meta
|
||||
end
|
||||
|
||||
cond do
|
||||
Keyword.has_key?(meta, :do) or match?([{{:__block__, _, [:do]}, _} | _], List.last(args)) ->
|
||||
# def foo do :ok end
|
||||
# def foo, do: :ok
|
||||
normalize_kw_blocks(form, meta, args, state)
|
||||
|
||||
match?([{:do, _} | _], List.last(args)) ->
|
||||
# Non normalized kw blocks
|
||||
line = state.parent_meta[:line]
|
||||
meta = meta ++ [do: [line: line], end: [line: line]]
|
||||
normalize_kw_blocks(form, meta, args, state)
|
||||
|
||||
allow_keyword?(form, arity) ->
|
||||
args = normalize_args(args, %{state | parent_meta: meta})
|
||||
{last_arg, leading_args} = List.pop_at(args, -1, [])
|
||||
|
||||
last_args =
|
||||
case last_arg do
|
||||
{:__block__, _, [[{{:__block__, key_meta, _}, _} | _]] = last_args} ->
|
||||
if key_meta[:format] == :keyword do
|
||||
last_args
|
||||
else
|
||||
[last_arg]
|
||||
end
|
||||
|
||||
[] ->
|
||||
[]
|
||||
|
||||
_ ->
|
||||
[last_arg]
|
||||
end
|
||||
|
||||
{form, meta, leading_args ++ last_args}
|
||||
|
||||
true ->
|
||||
args = normalize_args(args, %{state | parent_meta: meta})
|
||||
{form, meta, args}
|
||||
end
|
||||
end
|
||||
|
||||
defp allow_keyword?(:when, 2), do: true
|
||||
defp allow_keyword?(:{}, _), do: false
|
||||
defp allow_keyword?(op, arity), do: not is_atom(op) or not Macro.operator?(op, arity)
|
||||
|
||||
defp normalize_bitstring({:<<>>, meta, parts}, state, escape_interpolation \\ false) do
|
||||
meta = patch_meta_line(meta, state.parent_meta)
|
||||
|
||||
parts =
|
||||
if binary_interpolated?(parts) do
|
||||
normalize_interpolation_parts(parts, %{state | parent_meta: meta}, escape_interpolation)
|
||||
else
|
||||
state = %{state | parent_meta: meta}
|
||||
|
||||
Enum.map(parts, fn part ->
|
||||
with {:"::", meta, [left, _]} <- part,
|
||||
true <- meta[:inferred_bitstring_spec] do
|
||||
do_normalize(left, state)
|
||||
else
|
||||
_ -> do_normalize(part, state)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
{:<<>>, meta, parts}
|
||||
end
|
||||
|
||||
defp normalize_interpolation_parts(parts, state, escape_interpolation) do
|
||||
Enum.map(parts, fn
|
||||
{:"::", interpolation_meta,
|
||||
[
|
||||
{{:., dot_meta, [Kernel, :to_string]}, middle_meta, [middle]},
|
||||
{:binary, binary_meta, context}
|
||||
]} ->
|
||||
middle = do_normalize(middle, %{state | parent_meta: dot_meta})
|
||||
|
||||
{:"::", interpolation_meta,
|
||||
[
|
||||
{{:., dot_meta, [Kernel, :to_string]}, middle_meta, [middle]},
|
||||
{:binary, binary_meta, context}
|
||||
]}
|
||||
|
||||
part ->
|
||||
if escape_interpolation do
|
||||
maybe_escape_literal(part, state)
|
||||
else
|
||||
part
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp normalize_map_args(args, state) do
|
||||
Enum.map(normalize_kw_args(args, state, false), fn
|
||||
{:__block__, _, [{_, _} = pair]} -> pair
|
||||
pair -> pair
|
||||
end)
|
||||
end
|
||||
|
||||
defp normalize_kw_blocks(form, meta, args, state) do
|
||||
{kw_blocks, leading_args} = List.pop_at(args, -1)
|
||||
|
||||
kw_blocks =
|
||||
Enum.map(kw_blocks, fn {tag, block} ->
|
||||
block = do_normalize(block, %{state | parent_meta: meta})
|
||||
|
||||
block =
|
||||
case block do
|
||||
{_, _, [[{:->, _, _} | _] = block]} -> block
|
||||
block -> block
|
||||
end
|
||||
|
||||
# Only wrap the tag if it isn't already wrapped
|
||||
tag =
|
||||
case tag do
|
||||
{:__block__, _, _} -> tag
|
||||
_ -> {:__block__, [line: meta[:line]], [tag]}
|
||||
end
|
||||
|
||||
{tag, block}
|
||||
end)
|
||||
|
||||
leading_args = normalize_args(leading_args, %{state | parent_meta: meta})
|
||||
{form, meta, leading_args ++ [kw_blocks]}
|
||||
end
|
||||
|
||||
defp normalize_kw_args(elems, state, keyword?)
|
||||
|
||||
defp normalize_kw_args(
|
||||
[{{:__block__, key_meta, [key]}, value} = first | rest] = current,
|
||||
state,
|
||||
keyword?
|
||||
)
|
||||
when is_atom(key) do
|
||||
keyword? = keyword? or keyword?(current)
|
||||
|
||||
first =
|
||||
if key_meta[:format] == :keyword and not keyword? do
|
||||
key_meta = Keyword.delete(key_meta, :format)
|
||||
line = key_meta[:line] || meta_line(state)
|
||||
{:__block__, [line: line], [{{:__block__, key_meta, [key]}, value}]}
|
||||
else
|
||||
first
|
||||
end
|
||||
|
||||
[first | normalize_kw_args(rest, state, keyword?)]
|
||||
end
|
||||
|
||||
defp normalize_kw_args([{left, right} | rest] = current, state, keyword?) do
|
||||
keyword? = keyword? or keyword?(current)
|
||||
|
||||
left =
|
||||
if keyword? do
|
||||
meta = [format: :keyword] ++ meta_line(state)
|
||||
{:__block__, meta, [maybe_escape_literal(left, state)]}
|
||||
else
|
||||
do_normalize(left, state)
|
||||
end
|
||||
|
||||
right = do_normalize(right, state)
|
||||
|
||||
pair =
|
||||
with {:__block__, meta, _} <- left,
|
||||
:keyword <- meta[:format] do
|
||||
{left, right}
|
||||
else
|
||||
_ -> {:__block__, meta_line(state), [{left, right}]}
|
||||
end
|
||||
|
||||
[pair | normalize_kw_args(rest, state, keyword?)]
|
||||
end
|
||||
|
||||
defp normalize_kw_args([first | rest], state, keyword?) do
|
||||
[do_normalize(first, state) | normalize_kw_args(rest, state, keyword?)]
|
||||
end
|
||||
|
||||
defp normalize_kw_args([], _state, _keyword?) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp normalize_args(args, state) do
|
||||
Enum.map(args, &do_normalize(&1, state))
|
||||
end
|
||||
|
||||
defp maybe_escape_literal(string, %{escape: true}) when is_binary(string) do
|
||||
{string, _} = Code.Identifier.escape(string, nil)
|
||||
IO.iodata_to_binary(string)
|
||||
end
|
||||
|
||||
defp maybe_escape_literal(atom, %{escape: true} = state) when is_atom(atom) do
|
||||
atom
|
||||
|> Atom.to_string()
|
||||
|> maybe_escape_literal(state)
|
||||
|> String.to_atom()
|
||||
end
|
||||
|
||||
defp maybe_escape_literal(term, _) do
|
||||
term
|
||||
end
|
||||
|
||||
defp binary_interpolated?(parts) do
|
||||
Enum.all?(parts, fn
|
||||
{:"::", _, [{{:., _, [Kernel, :to_string]}, _, [_]}, {:binary, _, _}]} -> true
|
||||
binary when is_binary(binary) -> true
|
||||
_ -> false
|
||||
end)
|
||||
end
|
||||
|
||||
defp list_interpolated?(parts) do
|
||||
Enum.all?(parts, fn
|
||||
{{:., _, [Kernel, :to_string]}, _, [_]} -> true
|
||||
binary when is_binary(binary) -> true
|
||||
_ -> false
|
||||
end)
|
||||
end
|
||||
|
||||
defp patch_meta_line(meta, parent_meta) do
|
||||
with nil <- meta[:line],
|
||||
line when is_integer(line) <- parent_meta[:line] do
|
||||
[line: line] ++ meta
|
||||
else
|
||||
_ -> meta
|
||||
end
|
||||
end
|
||||
|
||||
defp meta_line(state) do
|
||||
if line = state.parent_meta[:line] do
|
||||
[line: line]
|
||||
else
|
||||
[]
|
||||
end
|
||||
end
|
||||
|
||||
defp keyword?([{{:__block__, key_meta, [key]}, _} | rest]) when is_atom(key) do
|
||||
if key_meta[:format] == :keyword do
|
||||
keyword?(rest)
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
defp keyword?([{key, _value} | rest]) when is_atom(key) do
|
||||
case Atom.to_charlist(key) do
|
||||
'Elixir.' ++ _ -> false
|
||||
_ -> keyword?(rest)
|
||||
end
|
||||
end
|
||||
|
||||
defp keyword?([]), do: true
|
||||
defp keyword?(_other), do: false
|
||||
end
|
||||
@@ -7,9 +7,9 @@ defmodule Code.Typespec do
|
||||
@spec spec_to_quoted(atom, tuple) :: {atom, keyword, [Macro.t()]}
|
||||
def spec_to_quoted(name, spec)
|
||||
|
||||
def spec_to_quoted(name, {:type, anno, :fun, [{:type, _, :product, args}, result]})
|
||||
def spec_to_quoted(name, {:type, line, :fun, [{:type, _, :product, args}, result]})
|
||||
when is_atom(name) do
|
||||
meta = meta(anno)
|
||||
meta = [line: line]
|
||||
body = {name, meta, Enum.map(args, &typespec_to_quoted/1)}
|
||||
|
||||
vars =
|
||||
@@ -27,13 +27,11 @@ defmodule Code.Typespec do
|
||||
end
|
||||
end
|
||||
|
||||
def spec_to_quoted(name, {:type, anno, :fun, []}) when is_atom(name) do
|
||||
meta = meta(anno)
|
||||
{:"::", meta, [{name, meta, []}, quote(do: term)]}
|
||||
def spec_to_quoted(name, {:type, line, :fun, []}) when is_atom(name) do
|
||||
{:"::", [line: line], [{name, [line: line], []}, quote(do: term)]}
|
||||
end
|
||||
|
||||
def spec_to_quoted(name, {:type, anno, :bounded_fun, [type, constrs]}) when is_atom(name) do
|
||||
meta = meta(anno)
|
||||
def spec_to_quoted(name, {:type, line, :bounded_fun, [type, constrs]}) when is_atom(name) do
|
||||
{:type, _, :fun, [{:type, _, :product, args}, result]} = type
|
||||
|
||||
guards =
|
||||
@@ -41,6 +39,7 @@ defmodule Code.Typespec do
|
||||
{erl_to_ex_var(var), typespec_to_quoted(type)}
|
||||
end
|
||||
|
||||
meta = [line: line]
|
||||
ignore_vars = Keyword.keys(guards)
|
||||
|
||||
vars =
|
||||
@@ -53,7 +52,7 @@ defmodule Code.Typespec do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
|
||||
when_args = [
|
||||
{:"::", meta, [{name, meta, args}, typespec_to_quoted(result)]},
|
||||
{:"::", meta, [{name, [line: line], args}, typespec_to_quoted(result)]},
|
||||
guards ++ vars
|
||||
]
|
||||
|
||||
@@ -174,11 +173,9 @@ defmodule Code.Typespec do
|
||||
end
|
||||
|
||||
defp get_module_and_beam(module) when is_atom(module) do
|
||||
with {^module, beam, _filename} <- :code.get_object_code(module),
|
||||
{:ok, ^module} <- beam |> :beam_lib.info() |> Keyword.fetch(:module) do
|
||||
{module, beam}
|
||||
else
|
||||
_ -> :error
|
||||
case :code.get_object_code(module) do
|
||||
{^module, beam, _filename} -> {module, beam}
|
||||
:error -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@@ -191,27 +188,27 @@ defmodule Code.Typespec do
|
||||
|
||||
## To AST conversion
|
||||
|
||||
defp collect_vars({:ann_type, _anno, args}) when is_list(args) do
|
||||
defp collect_vars({:ann_type, _line, args}) when is_list(args) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp collect_vars({:type, _anno, _kind, args}) when is_list(args) do
|
||||
defp collect_vars({:type, _line, _kind, args}) when is_list(args) do
|
||||
Enum.flat_map(args, &collect_vars/1)
|
||||
end
|
||||
|
||||
defp collect_vars({:remote_type, _anno, args}) when is_list(args) do
|
||||
defp collect_vars({:remote_type, _line, args}) when is_list(args) do
|
||||
Enum.flat_map(args, &collect_vars/1)
|
||||
end
|
||||
|
||||
defp collect_vars({:typed_record_field, _anno, type}) do
|
||||
defp collect_vars({:typed_record_field, _line, type}) do
|
||||
collect_vars(type)
|
||||
end
|
||||
|
||||
defp collect_vars({:paren_type, _anno, [type]}) do
|
||||
defp collect_vars({:paren_type, _line, [type]}) do
|
||||
collect_vars(type)
|
||||
end
|
||||
|
||||
defp collect_vars({:var, _anno, var}) do
|
||||
defp collect_vars({:var, _line, var}) do
|
||||
[erl_to_ex_var(var)]
|
||||
end
|
||||
|
||||
@@ -219,48 +216,47 @@ defmodule Code.Typespec do
|
||||
[]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:user_type, anno, name, args}) do
|
||||
defp typespec_to_quoted({:user_type, line, name, args}) do
|
||||
typespec_to_quoted({:type, line, name, args})
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, line, :tuple, :any}) do
|
||||
{:tuple, [line: line], []}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, line, :tuple, args}) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
{name, meta(anno), args}
|
||||
{:{}, [line: line], args}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :tuple, :any}) do
|
||||
{:tuple, meta(anno), []}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :tuple, args}) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
{:{}, meta(anno), args}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, _anno, :list, [{:type, _, :union, unions} = arg]}) do
|
||||
defp typespec_to_quoted({:type, _line, :list, [{:type, _, :union, unions} = arg]}) do
|
||||
case unpack_typespec_kw(unions, []) do
|
||||
{:ok, ast} -> ast
|
||||
:error -> [typespec_to_quoted(arg)]
|
||||
end
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :list, []}) do
|
||||
{:list, meta(anno), []}
|
||||
defp typespec_to_quoted({:type, line, :list, []}) do
|
||||
{:list, [line: line], []}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, _anno, :list, [arg]}) do
|
||||
defp typespec_to_quoted({:type, _line, :list, [arg]}) do
|
||||
[typespec_to_quoted(arg)]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :nonempty_list, []}) do
|
||||
[{:..., meta(anno), nil}]
|
||||
defp typespec_to_quoted({:type, line, :nonempty_list, []}) do
|
||||
[{:..., [line: line], nil}]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :nonempty_list, [arg]}) do
|
||||
[typespec_to_quoted(arg), {:..., meta(anno), nil}]
|
||||
defp typespec_to_quoted({:type, line, :nonempty_list, [arg]}) do
|
||||
[typespec_to_quoted(arg), {:..., [line: line], nil}]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :map, :any}) do
|
||||
{:map, meta(anno), []}
|
||||
defp typespec_to_quoted({:type, line, :map, :any}) do
|
||||
{:map, [line: line], []}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :map, fields}) do
|
||||
defp typespec_to_quoted({:type, line, :map, fields}) do
|
||||
fields =
|
||||
Enum.map(fields, fn
|
||||
{:type, _, :map_field_assoc, :any} ->
|
||||
@@ -276,19 +272,18 @@ 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 = {:%{}, meta(anno), fields_pruned}
|
||||
{:%, meta(anno), [struct, map_pruned]}
|
||||
{struct, fields} = Keyword.pop(fields, :__struct__)
|
||||
map = {:%{}, [line: line], fields}
|
||||
|
||||
_ ->
|
||||
{:%{}, meta(anno), fields}
|
||||
if struct do
|
||||
{:%, [line: line], [struct, map]}
|
||||
else
|
||||
map
|
||||
end
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :binary, [arg1, arg2]}) do
|
||||
defp typespec_to_quoted({:type, line, :binary, [arg1, arg2]}) do
|
||||
[arg1, arg2] = for arg <- [arg1, arg2], do: typespec_to_quoted(arg)
|
||||
line = meta(anno)[:line]
|
||||
|
||||
case {typespec_to_quoted(arg1), typespec_to_quoted(arg2)} do
|
||||
{arg1, 0} ->
|
||||
@@ -302,57 +297,57 @@ defmodule Code.Typespec do
|
||||
end
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :union, args}) do
|
||||
defp typespec_to_quoted({:type, line, :union, args}) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
Enum.reduce(Enum.reverse(args), fn arg, expr -> {:|, meta(anno), [arg, expr]} end)
|
||||
Enum.reduce(Enum.reverse(args), fn arg, expr -> {:|, [line: line], [arg, expr]} end)
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :fun, [{:type, _, :product, args}, result]}) do
|
||||
defp typespec_to_quoted({:type, line, :fun, [{:type, _, :product, args}, result]}) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
[{:->, meta(anno), [args, typespec_to_quoted(result)]}]
|
||||
[{:->, [line: line], [args, typespec_to_quoted(result)]}]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :fun, [args, result]}) do
|
||||
[{:->, meta(anno), [[typespec_to_quoted(args)], typespec_to_quoted(result)]}]
|
||||
defp typespec_to_quoted({:type, line, :fun, [args, result]}) do
|
||||
[{:->, [line: line], [[typespec_to_quoted(args)], typespec_to_quoted(result)]}]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :fun, []}) do
|
||||
typespec_to_quoted({:type, anno, :fun, [{:type, anno, :any}, {:type, anno, :any, []}]})
|
||||
defp typespec_to_quoted({:type, line, :fun, []}) do
|
||||
typespec_to_quoted({:type, line, :fun, [{:type, line, :any}, {:type, line, :any, []}]})
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, :range, [left, right]}) do
|
||||
{:.., meta(anno), [typespec_to_quoted(left), typespec_to_quoted(right)]}
|
||||
defp typespec_to_quoted({:type, line, :range, [left, right]}) do
|
||||
{:.., [line: line], [typespec_to_quoted(left), typespec_to_quoted(right)]}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, _anno, nil, []}) do
|
||||
defp typespec_to_quoted({:type, _line, nil, []}) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, anno, name, args}) do
|
||||
defp typespec_to_quoted({:type, line, name, args}) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
{name, meta(anno), args}
|
||||
{name, [line: line], args}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:var, anno, var}) do
|
||||
{erl_to_ex_var(var), meta(anno), nil}
|
||||
defp typespec_to_quoted({:var, line, var}) do
|
||||
{erl_to_ex_var(var), [line: line], nil}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:op, anno, op, arg}) do
|
||||
{op, meta(anno), [typespec_to_quoted(arg)]}
|
||||
defp typespec_to_quoted({:op, line, op, arg}) do
|
||||
{op, [line: line], [typespec_to_quoted(arg)]}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:remote_type, anno, [mod, name, args]}) do
|
||||
remote_type(anno, mod, name, args)
|
||||
defp typespec_to_quoted({:remote_type, line, [mod, name, args]}) do
|
||||
remote_type(line, mod, name, args)
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:ann_type, anno, [var, type]}) do
|
||||
{:"::", meta(anno), [typespec_to_quoted(var), typespec_to_quoted(type)]}
|
||||
defp typespec_to_quoted({:ann_type, line, [var, type]}) do
|
||||
{:"::", [line: line], [typespec_to_quoted(var), typespec_to_quoted(type)]}
|
||||
end
|
||||
|
||||
defp typespec_to_quoted(
|
||||
{:typed_record_field, {:record_field, anno1, {:atom, anno2, name}}, type}
|
||||
{:typed_record_field, {:record_field, line, {:atom, line1, name}}, type}
|
||||
) do
|
||||
typespec_to_quoted({:ann_type, anno1, [{:var, anno2, name}, type]})
|
||||
typespec_to_quoted({:ann_type, line, [{:var, line1, name}, type]})
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({:type, _, :any}) do
|
||||
@@ -363,7 +358,7 @@ defmodule Code.Typespec do
|
||||
typespec_to_quoted(type)
|
||||
end
|
||||
|
||||
defp typespec_to_quoted({type, _anno, atom}) when is_atom(type) do
|
||||
defp typespec_to_quoted({type, _line, atom}) when is_atom(type) do
|
||||
atom
|
||||
end
|
||||
|
||||
@@ -371,30 +366,30 @@ defmodule Code.Typespec do
|
||||
|
||||
## Helpers
|
||||
|
||||
defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :charlist}, []) do
|
||||
typespec_to_quoted({:type, anno, :charlist, []})
|
||||
defp remote_type(line, {:atom, _, :elixir}, {:atom, _, :charlist}, []) do
|
||||
typespec_to_quoted({:type, line, :charlist, []})
|
||||
end
|
||||
|
||||
defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :nonempty_charlist}, []) do
|
||||
typespec_to_quoted({:type, anno, :nonempty_charlist, []})
|
||||
defp remote_type(line, {:atom, _, :elixir}, {:atom, _, :nonempty_charlist}, []) do
|
||||
typespec_to_quoted({:type, line, :nonempty_charlist, []})
|
||||
end
|
||||
|
||||
defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :struct}, []) do
|
||||
typespec_to_quoted({:type, anno, :struct, []})
|
||||
defp remote_type(line, {:atom, _, :elixir}, {:atom, _, :struct}, []) do
|
||||
typespec_to_quoted({:type, line, :struct, []})
|
||||
end
|
||||
|
||||
defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]) do
|
||||
typespec_to_quoted({:type, anno, :as_boolean, [arg]})
|
||||
defp remote_type(line, {:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]) do
|
||||
typespec_to_quoted({:type, line, :as_boolean, [arg]})
|
||||
end
|
||||
|
||||
defp remote_type(anno, {:atom, _, :elixir}, {:atom, _, :keyword}, args) do
|
||||
typespec_to_quoted({:type, anno, :keyword, args})
|
||||
defp remote_type(line, {:atom, _, :elixir}, {:atom, _, :keyword}, args) do
|
||||
typespec_to_quoted({:type, line, :keyword, args})
|
||||
end
|
||||
|
||||
defp remote_type(anno, mod, name, args) do
|
||||
defp remote_type(line, mod, name, args) do
|
||||
args = for arg <- args, do: typespec_to_quoted(arg)
|
||||
dot = {:., meta(anno), [typespec_to_quoted(mod), typespec_to_quoted(name)]}
|
||||
{dot, meta(anno), args}
|
||||
dot = {:., [line: line], [typespec_to_quoted(mod), typespec_to_quoted(name)]}
|
||||
{dot, [line: line], args}
|
||||
end
|
||||
|
||||
defp erl_to_ex_var(var) do
|
||||
@@ -418,6 +413,4 @@ defmodule Code.Typespec do
|
||||
defp unpack_typespec_kw(_, _acc) do
|
||||
:error
|
||||
end
|
||||
|
||||
defp meta(anno), do: [line: :erl_anno.line(anno)]
|
||||
end
|
||||
|
||||
@@ -17,8 +17,8 @@ defprotocol Collectable do
|
||||
|
||||
This design is intentional. `Enumerable` was designed to support infinite
|
||||
collections, resources and other structures with fixed shape. For example,
|
||||
it doesn't make sense to insert values into a `Range`, as it has a
|
||||
fixed shape where only the range limits and step are stored.
|
||||
it doesn't make sense to insert values into a range, as it has a fixed
|
||||
shape where just the range limits are stored.
|
||||
|
||||
The `Collectable` module was designed to fill the gap left by the
|
||||
`Enumerable` protocol. `Collectable.into/1` can be seen as the opposite of
|
||||
@@ -27,44 +27,32 @@ defprotocol Collectable do
|
||||
|
||||
## Examples
|
||||
|
||||
To show how to manually use the `Collectable` protocol, let's play with a
|
||||
simplified implementation for `MapSet`.
|
||||
To show how to manually use the `Collectable` protocol, let's play with its
|
||||
implementation for `MapSet`.
|
||||
|
||||
iex> {initial_acc, collector_fun} = Collectable.into(MapSet.new())
|
||||
iex> updated_acc = Enum.reduce([1, 2, 3], initial_acc, fn elem, acc ->
|
||||
...> collector_fun.(acc, {:cont, elem})
|
||||
...> end)
|
||||
iex> collector_fun.(updated_acc, :done)
|
||||
MapSet.new([1, 2, 3])
|
||||
#MapSet<[1, 2, 3]>
|
||||
|
||||
To show how the protocol can be implemented, we can again look at the
|
||||
simplified implementation for `MapSet`. In this implementation "collecting" elements
|
||||
To show how the protocol can be implemented, we can take again a look at the
|
||||
implementation for `MapSet`. In this implementation "collecting" elements
|
||||
simply means inserting them in the set through `MapSet.put/2`.
|
||||
|
||||
defimpl Collectable, for: MapSet do
|
||||
def into(map_set) do
|
||||
def into(original) do
|
||||
collector_fun = fn
|
||||
map_set_acc, {:cont, elem} ->
|
||||
MapSet.put(map_set_acc, elem)
|
||||
|
||||
map_set_acc, :done ->
|
||||
map_set_acc
|
||||
|
||||
_map_set_acc, :halt ->
|
||||
:ok
|
||||
set, {:cont, elem} -> MapSet.put(set, elem)
|
||||
set, :done -> set
|
||||
_set, :halt -> :ok
|
||||
end
|
||||
|
||||
initial_acc = map_set
|
||||
|
||||
{initial_acc, collector_fun}
|
||||
{original, collector_fun}
|
||||
end
|
||||
end
|
||||
|
||||
So now we can call `Enum.into/2`:
|
||||
|
||||
iex> Enum.into([1, 2, 3], MapSet.new())
|
||||
MapSet.new([1, 2, 3])
|
||||
|
||||
"""
|
||||
|
||||
@type command :: {:cont, term} | :done | :halt
|
||||
@@ -72,11 +60,8 @@ defprotocol Collectable do
|
||||
@doc """
|
||||
Returns an initial accumulator and a "collector" function.
|
||||
|
||||
Receives a `collectable` which can be used as the initial accumulator that will
|
||||
be passed to the function.
|
||||
|
||||
The collector function receives a term and a command and injects the term into
|
||||
the collectable accumulator on every `{:cont, term}` command.
|
||||
The returned function receives a term and a command and injects the term into
|
||||
the collectable on every `{:cont, term}` command.
|
||||
|
||||
`:done` is passed as a command when no further values will be injected. This
|
||||
is useful when there's a need to close resources or normalizing values. A
|
||||
@@ -88,17 +73,16 @@ defprotocol Collectable do
|
||||
For examples on how to use the `Collectable` protocol and `into/1` see the
|
||||
module documentation.
|
||||
"""
|
||||
@spec into(t) :: {initial_acc :: term, collector :: (term, command -> t | term)}
|
||||
@spec into(t) :: {term, (term, command -> t | term)}
|
||||
def into(collectable)
|
||||
end
|
||||
|
||||
defimpl Collectable, for: List do
|
||||
def into(list) do
|
||||
# TODO: Change the behaviour so the into always comes last on Elixir v2.0
|
||||
if list != [] do
|
||||
def into(original) do
|
||||
if original != [] do
|
||||
IO.warn(
|
||||
"the Collectable protocol is deprecated for non-empty lists. The behaviour of " <>
|
||||
"Enum.into/2 and \"for\" comprehensions with an :into option is incorrect " <>
|
||||
"things like Enum.into/2 or \"for\" comprehensions with an :into option is incorrect " <>
|
||||
"when collecting into non-empty lists. If you're collecting into a non-empty keyword " <>
|
||||
"list, consider using Keyword.merge/2 instead. If you're collecting into a non-empty " <>
|
||||
"list, consider concatenating the two lists with the ++ operator."
|
||||
@@ -106,14 +90,9 @@ defimpl Collectable, for: List do
|
||||
end
|
||||
|
||||
fun = fn
|
||||
list_acc, {:cont, elem} ->
|
||||
[elem | list_acc]
|
||||
|
||||
list_acc, :done ->
|
||||
list ++ :lists.reverse(list_acc)
|
||||
|
||||
_list_acc, :halt ->
|
||||
:ok
|
||||
list, {:cont, x} -> [x | list]
|
||||
list, :done -> original ++ :lists.reverse(list)
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{[], fun}
|
||||
@@ -121,7 +100,7 @@ defimpl Collectable, for: List do
|
||||
end
|
||||
|
||||
defimpl Collectable, for: BitString do
|
||||
def into(binary) when is_binary(binary) do
|
||||
def into(original) when is_binary(original) do
|
||||
fun = fn
|
||||
acc, {:cont, x} when is_binary(x) and is_list(acc) ->
|
||||
[acc | x]
|
||||
@@ -138,14 +117,14 @@ defimpl Collectable, for: BitString do
|
||||
acc, :done ->
|
||||
IO.iodata_to_binary(acc)
|
||||
|
||||
__acc, :halt ->
|
||||
_, :halt ->
|
||||
:ok
|
||||
end
|
||||
|
||||
{[binary], fun}
|
||||
{[original], fun}
|
||||
end
|
||||
|
||||
def into(bitstring) do
|
||||
def into(original) when is_bitstring(original) do
|
||||
fun = fn
|
||||
acc, {:cont, x} when is_bitstring(x) ->
|
||||
<<acc::bitstring, x::bitstring>>
|
||||
@@ -153,27 +132,22 @@ defimpl Collectable, for: BitString do
|
||||
acc, :done ->
|
||||
acc
|
||||
|
||||
_acc, :halt ->
|
||||
_, :halt ->
|
||||
:ok
|
||||
end
|
||||
|
||||
{bitstring, fun}
|
||||
{original, fun}
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Collectable, for: Map do
|
||||
def into(map) do
|
||||
def into(original) do
|
||||
fun = fn
|
||||
map_acc, {:cont, {key, value}} ->
|
||||
Map.put(map_acc, key, value)
|
||||
|
||||
map_acc, :done ->
|
||||
map_acc
|
||||
|
||||
_map_acc, :halt ->
|
||||
:ok
|
||||
map, {:cont, {k, v}} -> :maps.put(k, v, map)
|
||||
map, :done -> map
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{map, fun}
|
||||
{original, fun}
|
||||
end
|
||||
end
|
||||
|
||||
+65
-158
@@ -13,11 +13,10 @@ 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`
|
||||
`config_env/0`, `config_target/0`, and `import_config/1`
|
||||
to help you manage your configuration.
|
||||
and `import_config/1` to help you manage your configuration.
|
||||
|
||||
`config/2` and `config/3` are used to define key-value configuration
|
||||
for a given application. Once Mix starts, it will automatically
|
||||
@@ -27,26 +26,24 @@ 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.
|
||||
|
||||
> **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. Also note that
|
||||
> the `config/config.exs` of a library is not evaluated when the library is
|
||||
> used as a dependency, as configuration is always meant to configure the
|
||||
> current project. For more information, read our [library guidelines](library-guidelines.md).
|
||||
**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).
|
||||
|
||||
## 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`.
|
||||
|
||||
@@ -62,50 +59,43 @@ defmodule Config do
|
||||
import_config config
|
||||
end
|
||||
|
||||
The last step is to replace all `Mix.env()` calls in the config files with `config_env()`.
|
||||
## config/releases.exs
|
||||
|
||||
Keep in mind you must also avoid using `Mix.env()` inside your project files.
|
||||
To check the environment at _runtime_, you may add a configuration key:
|
||||
|
||||
# config.exs
|
||||
...
|
||||
config :my_app, env: config_env()
|
||||
|
||||
Then, in other scripts and modules, you may get the environment with
|
||||
`Application.fetch_env!/2`:
|
||||
|
||||
# router.exs
|
||||
...
|
||||
if Application.fetch_env!(:my_app, :env) == :prod do
|
||||
...
|
||||
end
|
||||
|
||||
The only files where you may access functions from the `Mix` module are
|
||||
the `mix.exs` file and inside custom Mix tasks, which always within the
|
||||
`Mix.Tasks` namespace.
|
||||
|
||||
## 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) || raise_improper_use!()
|
||||
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. " <>
|
||||
@@ -122,9 +112,8 @@ defmodule Config do
|
||||
|
||||
The given `opts` are merged into the existing configuration
|
||||
for the given `root_key`. Conflicting keys are overridden by the
|
||||
ones specified in `opts`, unless they are keywords, which are
|
||||
deep merged recursively. For example, the application configuration
|
||||
below
|
||||
ones specified in `opts`. For example, the application
|
||||
configuration below
|
||||
|
||||
config :logger,
|
||||
level: :warn,
|
||||
@@ -159,30 +148,21 @@ defmodule Config do
|
||||
|
||||
The given `opts` are merged into the existing values for `key`
|
||||
in the given `root_key`. Conflicting keys are overridden by the
|
||||
ones specified in `opts`, unless they are keywords, which are
|
||||
deep merged recursively. For example, the application configuration
|
||||
below
|
||||
ones specified in `opts`. For example, the application
|
||||
configuration below
|
||||
|
||||
config :ecto, Repo,
|
||||
log_level: :warn,
|
||||
adapter: Ecto.Adapters.Postgres,
|
||||
metadata: [read_only: true]
|
||||
adapter: Ecto.Adapters.Postgres
|
||||
|
||||
config :ecto, Repo,
|
||||
log_level: :info,
|
||||
pool_size: 10,
|
||||
metadata: [replica: true]
|
||||
pool_size: 10
|
||||
|
||||
will have a final value of the configuration for the `Repo`
|
||||
key in the `:ecto` application of:
|
||||
|
||||
Application.get_env(:ecto, Repo)
|
||||
#=> [
|
||||
#=> log_level: :info,
|
||||
#=> pool_size: 10,
|
||||
#=> adapter: Ecto.Adapters.Postgres,
|
||||
#=> metadata: [read_only: true, replica: true]
|
||||
#=> ]
|
||||
[log_level: :info, pool_size: 10, adapter: Ecto.Adapters.Postgres]
|
||||
|
||||
"""
|
||||
@doc since: "1.9.0"
|
||||
@@ -192,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.
|
||||
|
||||
@@ -253,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
|
||||
@@ -268,62 +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
|
||||
|
||||
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 ->
|
||||
|
||||
@@ -11,55 +11,18 @@ defmodule Config.Provider do
|
||||
the file system. For more information on runtime configuration,
|
||||
see `mix release`.
|
||||
|
||||
## Multiple config files
|
||||
## Sample config provider
|
||||
|
||||
One common use of config providers is to specify multiple
|
||||
configuration files in a release. Elixir ships with one provider,
|
||||
called `Config.Reader`, which is capable of handling Elixir's
|
||||
built-in config files.
|
||||
|
||||
For example, imagine you want to list some basic configuration
|
||||
on Mix's built-in `config/runtime.exs` file, but you also want
|
||||
to support additional configuration files. To do so, you can add
|
||||
this inside the `def project` portion of your `mix.exs`:
|
||||
|
||||
releases: [
|
||||
demo: [
|
||||
config_providers: [
|
||||
{Config.Reader, {:system, "RELEASE_ROOT", "/extra_config.exs"}}
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
You can place this `extra_config.exs` file in your release in
|
||||
multiple ways:
|
||||
|
||||
1. If it is available on the host when assembling the release,
|
||||
you can place it on "rel/overlays/extra_config.exs" and it
|
||||
will be automatically copied to the release root
|
||||
|
||||
2. If it is available on the target during deployment, you can
|
||||
simply copy it to the release root as a step in your deployment
|
||||
|
||||
Now once the system boots, it will load both `config/runtime.exs`
|
||||
and `extra_config.exs` early in the boot process. You can learn
|
||||
more options on `Config.Reader`.
|
||||
|
||||
## Custom config provider
|
||||
|
||||
You can also implement custom config providers, similar to how
|
||||
`Config.Reader` works. For example, imagine you need to load
|
||||
some configuration from a JSON file and load that into the system.
|
||||
Said configuration provider would look like:
|
||||
For example, imagine you need to load some configuration from
|
||||
a JSON file and load that into the system. Said configuration
|
||||
provider would look like:
|
||||
|
||||
defmodule JSONConfigProvider do
|
||||
@behaviour Config.Provider
|
||||
|
||||
# Let's pass the path to the JSON file as config
|
||||
@impl true
|
||||
def init(path) when is_binary(path), do: path
|
||||
|
||||
@impl true
|
||||
def load(config, path) do
|
||||
# We need to start any app we may depend on.
|
||||
{:ok, _} = Application.ensure_all_started(:jason)
|
||||
@@ -76,17 +39,13 @@ 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
|
||||
reboot the system with the new values in place.
|
||||
"""
|
||||
|
||||
@type config :: keyword
|
||||
@@ -100,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()
|
||||
@@ -128,7 +86,7 @@ defmodule Config.Provider do
|
||||
Loads configuration (typically during system boot).
|
||||
|
||||
It receives the current `config` and the `state` returned by
|
||||
`c:init/1`. Then, you typically read the extra configuration
|
||||
`c:init/1`. Then you typically read the extra configuration
|
||||
from an external source and merge it into the received `config`.
|
||||
Merging should be done with `Config.Reader.merge/2`, as it
|
||||
performs deep merge. It should return the updated config.
|
||||
@@ -140,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`.
|
||||
@@ -184,175 +133,60 @@ 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
|
||||
original_config = read_config!(path)
|
||||
defp booted_key(%{prune_after_boot: true}, path), do: {:booted, path}
|
||||
defp booted_key(%{prune_after_boot: false}, _path), do: :booted
|
||||
|
||||
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.()
|
||||
defp validate_no_cyclic_boot!(path) do
|
||||
if System.get_env("ELIXIR_CONFIG_PROVIDER_BOOTED") do
|
||||
bad_path_abort("Got infinite loop when running Config.Provider", path)
|
||||
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
|
||||
System.put_env("ELIXIR_CONFIG_PROVIDER_BOOTED", "1")
|
||||
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)
|
||||
|
||||
if 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 read_config!(path) do
|
||||
case :file.consult(path) do
|
||||
{:ok, [inner]} ->
|
||||
@@ -388,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
|
||||
|
||||
@@ -409,7 +243,7 @@ defmodule Config.Provider do
|
||||
end
|
||||
|
||||
defp abort(msg) do
|
||||
IO.puts("ERROR! " <> msg)
|
||||
:erlang.raise(:error, "aborting boot", [{Config.Provider, :boot, 2, []}])
|
||||
IO.puts(:stderr, "ERROR! " <> msg)
|
||||
raise(msg)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,110 +4,59 @@ defmodule Config.Reader do
|
||||
|
||||
## As a provider
|
||||
|
||||
`Config.Reader` can also be used as a `Config.Provider`. A config
|
||||
provider is used during releases to customize how applications are
|
||||
configured. 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 add this inside the `def project` portion
|
||||
of your `mix.exs`:
|
||||
|
||||
releases: [
|
||||
demo: [
|
||||
config_providers: [
|
||||
{Config.Reader, "/etc/config.exs"}
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
Or if you want to read a custom path inside the release:
|
||||
|
||||
config_providers: [{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}
|
||||
]
|
||||
|
||||
Remember Mix already loads `config/runtime.exs` by default.
|
||||
For more examples and scenarios, see the `Config.Provider` module.
|
||||
`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), __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
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
defmodule DynamicSupervisor do
|
||||
@moduledoc ~S"""
|
||||
A supervisor optimized to only start children dynamically.
|
||||
A supervisor that starts children dynamically.
|
||||
|
||||
The `Supervisor` module was designed to handle mostly static children
|
||||
that are started in the given order when the supervisor starts. A
|
||||
`DynamicSupervisor` starts with no children. Instead, children are
|
||||
started on demand via `start_child/2` and there is no ordering between
|
||||
children. This allows the `DynamicSupervisor` to hold millions of
|
||||
children by using efficient data structures and to execute certain
|
||||
operations, such as shutting down, concurrently.
|
||||
started on demand via `start_child/2`. When a dynamic supervisor
|
||||
terminates, all children are shut down at the same time, with no guarantee
|
||||
of ordering.
|
||||
|
||||
## Examples
|
||||
|
||||
A dynamic supervisor is started with no children and often 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, name: MyApp.DynamicSupervisor}
|
||||
{DynamicSupervisor, strategy: :one_for_one, name: MyApp.DynamicSupervisor}
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_one)
|
||||
@@ -37,46 +38,6 @@ defmodule DynamicSupervisor do
|
||||
DynamicSupervisor.count_children(MyApp.DynamicSupervisor)
|
||||
#=> %{active: 2, specs: 2, supervisors: 0, workers: 2}
|
||||
|
||||
## Scalability and partitioning
|
||||
|
||||
The `DynamicSupervisor` is a single process responsible for starting
|
||||
other processes. In some applications, the `DynamicSupervisor` may
|
||||
become a bottleneck. To address this, you can start multiple instances
|
||||
of the `DynamicSupervisor` and then pick a "random" instance to start
|
||||
the child on.
|
||||
|
||||
Instead of:
|
||||
|
||||
children = [
|
||||
{DynamicSupervisor, name: MyApp.DynamicSupervisor}
|
||||
]
|
||||
|
||||
and:
|
||||
|
||||
DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Agent, fn -> %{} end})
|
||||
|
||||
You can do this:
|
||||
|
||||
children = [
|
||||
{PartitionSupervisor,
|
||||
child_spec: DynamicSupervisor,
|
||||
name: MyApp.DynamicSupervisors}
|
||||
]
|
||||
|
||||
and then:
|
||||
|
||||
DynamicSupervisor.start_child(
|
||||
{:via, PartitionSupervisor, {MyApp.DynamicSupervisors, self()}},
|
||||
{Agent, fn -> %{} end}
|
||||
)
|
||||
|
||||
In the code above, we start a partition supervisor that will by default
|
||||
start a dynamic supervisor for each core in your machine. Then, instead
|
||||
of calling the `DynamicSupervisor` by name, you call it through the
|
||||
partition supervisor, using `self()` as the routing key. This means each
|
||||
process will be assigned one of the existing dynamic supervisors.
|
||||
Read the `PartitionSupervisor` docs for more information.
|
||||
|
||||
## Module-based supervisors
|
||||
|
||||
Similar to `Supervisor`, dynamic supervisors also support module-based
|
||||
@@ -187,10 +148,13 @@ defmodule DynamicSupervisor do
|
||||
extra_arguments: [term()]
|
||||
}
|
||||
|
||||
@typedoc "Options given to `start_link` functions"
|
||||
@type option :: GenServer.option()
|
||||
@typedoc "Option values used by the `start*` functions"
|
||||
@type option :: {:name, Supervisor.name()} | init_option()
|
||||
|
||||
@typedoc "Options given to `start_link` and `init/1` functions"
|
||||
@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()}
|
||||
@@ -247,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.
|
||||
|
||||
@@ -272,74 +236,12 @@ defmodule DynamicSupervisor do
|
||||
@doc """
|
||||
Starts a supervisor with the given options.
|
||||
|
||||
This function is typically not invoked directly, instead it is invoked
|
||||
when using a `DynamicSupervisor` as a child of another supervisor:
|
||||
The `:strategy` is a required option and the currently supported
|
||||
value is `:one_for_one`. The remaining options can be found in the
|
||||
`init/1` docs.
|
||||
|
||||
children = [
|
||||
{DynamicSupervisor, name: MySupervisor}
|
||||
]
|
||||
|
||||
If the supervisor is successfully spawned, this function returns
|
||||
`{:ok, pid}`, where `pid` is the PID of the supervisor. If the supervisor
|
||||
is given a name and a process with the specified name already exists,
|
||||
the function returns `{:error, {:already_started, pid}}`, where `pid`
|
||||
is the PID of that process.
|
||||
|
||||
Note that a supervisor started with this function is linked to the parent
|
||||
process and exits not only on crashes but also if the parent process exits
|
||||
with `:normal` reason.
|
||||
|
||||
## Options
|
||||
|
||||
* `:name` - registers the supervisor under the given name.
|
||||
The supported values are described under the "Name registration"
|
||||
section in the `GenServer` module docs.
|
||||
|
||||
* `:strategy` - the restart strategy option. The only supported
|
||||
value is `:one_for_one` which means that no other child is
|
||||
terminated if a child process terminates. You can learn more
|
||||
about strategies in the `Supervisor` module docs.
|
||||
|
||||
* `:max_restarts` - the maximum number of restarts allowed in
|
||||
a time frame. Defaults to `3`.
|
||||
|
||||
* `:max_seconds` - the time frame in which `:max_restarts` applies.
|
||||
Defaults to `5`.
|
||||
|
||||
* `:max_children` - the maximum amount of children to be running
|
||||
under this supervisor at the same time. When `:max_children` is
|
||||
exceeded, `start_child/2` returns `{:error, :max_children}`. Defaults
|
||||
to `:infinity`.
|
||||
|
||||
* `:extra_arguments` - arguments that are prepended to the arguments
|
||||
specified in the child spec given to `start_child/2`. Defaults to
|
||||
an empty list.
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_link([option | init_option]) :: Supervisor.on_start()
|
||||
def start_link(options) when is_list(options) do
|
||||
keys = [:extra_arguments, :max_children, :max_seconds, :max_restarts, :strategy]
|
||||
{sup_opts, start_opts} = Keyword.split(options, keys)
|
||||
start_link(Supervisor.Default, init(sup_opts), start_opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts a module-based supervisor process with the given `module` and `init_arg`.
|
||||
|
||||
To start the supervisor, the `c:init/1` callback will be invoked in the given
|
||||
`module`, with `init_arg` as its argument. The `c:init/1` callback must return a
|
||||
supervisor specification which can be created with the help of the `init/1`
|
||||
function.
|
||||
|
||||
If the `c:init/1` callback returns `:ignore`, this function returns
|
||||
`:ignore` as well and the supervisor terminates with reason `:normal`.
|
||||
If it fails or returns an incorrect value, this function returns
|
||||
`{:error, term}` where `term` is a term with information about the
|
||||
error, and the supervisor terminates with reason `term`.
|
||||
|
||||
The `:name` option can also be given in order to register a supervisor
|
||||
name, the supported values are described in the "Name registration"
|
||||
The `:name` option can also be used to register a supervisor name.
|
||||
The supported values are described under the "Name registration"
|
||||
section in the `GenServer` module docs.
|
||||
|
||||
If the supervisor is successfully spawned, this function returns
|
||||
@@ -353,19 +255,43 @@ defmodule DynamicSupervisor do
|
||||
with `:normal` reason.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_link(module, term, [option]) :: Supervisor.on_start()
|
||||
def start_link(module, init_arg, opts \\ []) do
|
||||
GenServer.start_link(__MODULE__, {module, init_arg, opts[:name]}, opts)
|
||||
@spec start_link(options) :: Supervisor.on_start()
|
||||
def start_link(options) when is_list(options) do
|
||||
keys = [:extra_arguments, :max_children, :max_seconds, :max_restarts, :strategy]
|
||||
{sup_opts, start_opts} = Keyword.split(options, keys)
|
||||
start_link(Supervisor.Default, init(sup_opts), start_opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts a module-based supervisor process with the given `module` and `arg`.
|
||||
|
||||
To start the supervisor, the `c:init/1` callback will be invoked in the given
|
||||
`module`, with `arg` as its argument. The `c:init/1` callback must return a
|
||||
supervisor specification which can be created with the help of the `init/1`
|
||||
function.
|
||||
|
||||
If the `c:init/1` callback returns `:ignore`, this function returns
|
||||
`:ignore` as well and the supervisor terminates with reason `:normal`.
|
||||
If it fails or returns an incorrect value, this function returns
|
||||
`{:error, term}` where `term` is a term with information about the
|
||||
error, and the supervisor terminates with reason `term`.
|
||||
|
||||
The `:name` option can also be given in order to register a supervisor
|
||||
name, the supported values are described in the "Name registration"
|
||||
section in the `GenServer` module docs.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_link(module, term, GenServer.options()) :: Supervisor.on_start()
|
||||
def start_link(mod, init_arg, opts \\ []) do
|
||||
GenServer.start_link(__MODULE__, {mod, init_arg, opts[:name]}, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
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
|
||||
process will be started as defined in the child specification. Note that while
|
||||
the `:id` field is still required in the spec, the value is ignored and
|
||||
therefore does not need to be unique.
|
||||
"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,
|
||||
info}`, then child specification and PID are added to the supervisor and
|
||||
@@ -384,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)
|
||||
@@ -496,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)
|
||||
@@ -554,20 +473,46 @@ defmodule DynamicSupervisor do
|
||||
module-based supervisors. See the "Module-based supervisors" section
|
||||
in the module documentation for more information.
|
||||
|
||||
It accepts the same `options` as `start_link/1` (except for `:name`)
|
||||
and it returns a tuple containing the supervisor options.
|
||||
The `options` received by this function are also supported by `start_link/2`.
|
||||
|
||||
This function returns a tuple containing the supervisor options.
|
||||
|
||||
## Examples
|
||||
|
||||
def init(_arg) do
|
||||
DynamicSupervisor.init(max_children: 1000)
|
||||
DynamicSupervisor.init(max_children: 1000, strategy: :one_for_one)
|
||||
end
|
||||
|
||||
## Options
|
||||
|
||||
* `:strategy` - the restart strategy option. The only supported
|
||||
value is `:one_for_one` which means that no other child is
|
||||
terminated if a child process terminates. You can learn more
|
||||
about strategies in the `Supervisor` module docs.
|
||||
|
||||
* `:max_restarts` - the maximum number of restarts allowed in
|
||||
a time frame. Defaults to `3`.
|
||||
|
||||
* `:max_seconds` - the time frame in which `:max_restarts` applies.
|
||||
Defaults to `5`.
|
||||
|
||||
* `:max_children` - the maximum amount of children to be running
|
||||
under this supervisor at the same time. When `:max_children` is
|
||||
exceeded, `start_child/2` returns `{:error, :max_children}`. Defaults
|
||||
to `:infinity`.
|
||||
|
||||
* `:extra_arguments` - arguments that are prepended to the arguments
|
||||
specified in the child spec given to `start_child/2`. Defaults to
|
||||
an empty list.
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec init([init_option]) :: {:ok, sup_flags()}
|
||||
def init(options) when is_list(options) do
|
||||
strategy = Keyword.get(options, :strategy, :one_for_one)
|
||||
unless strategy = options[:strategy] do
|
||||
raise ArgumentError, "expected :strategy option to be given"
|
||||
end
|
||||
|
||||
intensity = Keyword.get(options, :max_restarts, 3)
|
||||
period = Keyword.get(options, :max_seconds, 5)
|
||||
max_children = Keyword.get(options, :max_children, :infinity)
|
||||
@@ -800,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
|
||||
|
||||
@@ -1056,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
|
||||
|
||||
@@ -1102,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
|
||||
|
||||
+428
-1844
File diff suppressed because it is too large
Load Diff
+144
-477
@@ -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()
|
||||
@@ -43,17 +43,9 @@ defmodule Exception do
|
||||
@callback blame(t, stacktrace) :: {t, stacktrace}
|
||||
@optional_callbacks [blame: 2]
|
||||
|
||||
@doc false
|
||||
# Callback for formatting Erlang exceptions
|
||||
def format_error(%struct{} = exception, _stacktrace) do
|
||||
%{general: message(exception), reason: "#" <> Atom.to_string(struct)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns `true` if the given `term` is an exception.
|
||||
"""
|
||||
# TODO: Deprecate 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
|
||||
@@ -68,7 +60,7 @@ defmodule Exception do
|
||||
caught_exception ->
|
||||
"got #{inspect(caught_exception.__struct__)} with message " <>
|
||||
"#{inspect(message(caught_exception))} while retrieving Exception.message/1 " <>
|
||||
"for #{inspect(exception)}. Stacktrace:\n#{format_stacktrace(__STACKTRACE__)}"
|
||||
"for #{inspect(exception)}"
|
||||
else
|
||||
result when is_binary(result) ->
|
||||
result
|
||||
@@ -196,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)
|
||||
@@ -217,21 +209,16 @@ defmodule Exception do
|
||||
clauses =
|
||||
for {meta, ex_args, guards, _block} <- clauses do
|
||||
scope = :elixir_erl.scope(meta, true)
|
||||
ann = :elixir_erl.get_ann(meta)
|
||||
|
||||
{erl_args, scope} =
|
||||
:elixir_erl_clauses.match(ann, &:elixir_erl_pass.translate_args/3, ex_args, scope)
|
||||
:elixir_erl_clauses.match(&:elixir_erl_pass.translate_args/2, ex_args, scope)
|
||||
|
||||
{args, binding} =
|
||||
[call_args, ex_args, erl_args]
|
||||
|> Enum.zip()
|
||||
|> Enum.map_reduce([], &blame_arg/2)
|
||||
|
||||
guards =
|
||||
guards
|
||||
|> Enum.map(&blame_guard(&1, ann, scope, binding))
|
||||
|> Enum.map(&Macro.prewalk(&1, fn guard -> translate_guard(guard) end))
|
||||
|
||||
guards = Enum.map(guards, &blame_guard(&1, scope, binding))
|
||||
{args, guards}
|
||||
end
|
||||
|
||||
@@ -241,69 +228,6 @@ defmodule Exception do
|
||||
end
|
||||
end
|
||||
|
||||
defp is_map_node?({:is_map, _, [_]}), do: true
|
||||
defp is_map_node?(_), do: false
|
||||
defp is_map_key_node?({:is_map_key, _, [_, _]}), do: true
|
||||
defp is_map_key_node?(_), do: false
|
||||
|
||||
defp struct_validation_node?(
|
||||
{:is_atom, _, [{{:., [], [:erlang, :map_get]}, _, [:__struct__, _]}]}
|
||||
),
|
||||
do: true
|
||||
|
||||
defp struct_validation_node?(
|
||||
{:==, _, [{{:., [], [:erlang, :map_get]}, _, [:__struct__, _]}, _module]}
|
||||
),
|
||||
do: true
|
||||
|
||||
defp struct_validation_node?(_), do: false
|
||||
|
||||
defp is_struct_macro?(
|
||||
{:and, _,
|
||||
[
|
||||
{:and, _, [%{node: node_1 = {_, _, [arg]}}, %{node: node_2 = {_, _, [arg, _]}}]},
|
||||
%{node: node_3 = {_, _, [{_, _, [_, arg]}]}}
|
||||
]}
|
||||
),
|
||||
do: is_map_node?(node_1) and is_map_key_node?(node_2) and struct_validation_node?(node_3)
|
||||
|
||||
defp is_struct_macro?(
|
||||
{:and, _,
|
||||
[
|
||||
{:and, _,
|
||||
[
|
||||
{:and, _,
|
||||
[
|
||||
%{node: node_1 = {_, _, [arg]}},
|
||||
{:or, _, [%{node: {:is_atom, _, [_]}}, %{node: :fail}]}
|
||||
]},
|
||||
%{node: node_2 = {_, _, [arg, _]}}
|
||||
]},
|
||||
%{node: node_3 = {_, _, [{_, _, [_, arg]}, _]}}
|
||||
]}
|
||||
),
|
||||
do: is_map_node?(node_1) and is_map_key_node?(node_2) and struct_validation_node?(node_3)
|
||||
|
||||
defp is_struct_macro?(_), do: false
|
||||
|
||||
defp translate_guard(guard) do
|
||||
if is_struct_macro?(guard) do
|
||||
undo_is_struct_guard(guard)
|
||||
else
|
||||
guard
|
||||
end
|
||||
end
|
||||
|
||||
defp undo_is_struct_guard({:and, meta, [_, %{node: {_, _, [{_, _, [_, arg]} | optional]}}]}) do
|
||||
args =
|
||||
case optional do
|
||||
[] -> [arg]
|
||||
[module] -> [arg, module]
|
||||
end
|
||||
|
||||
%{match?: meta[:value], node: {:is_struct, meta, args}}
|
||||
end
|
||||
|
||||
defp blame_arg({call_arg, ex_arg, erl_arg}, binding) do
|
||||
{match?, binding} = blame_arg(erl_arg, call_arg, binding)
|
||||
{blame_wrap(match?, rewrite_arg(ex_arg)), binding}
|
||||
@@ -313,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}
|
||||
@@ -326,72 +246,66 @@ defmodule Exception do
|
||||
|
||||
defp rewrite_arg(arg) do
|
||||
Macro.prewalk(arg, fn
|
||||
{:%{}, meta, [__struct__: Range, first: first, last: last, step: step]} ->
|
||||
{:"..//", meta, [first, last, step]}
|
||||
{:%{}, meta, [__struct__: Range, first: first, last: last]} ->
|
||||
{:.., meta, [first, last]}
|
||||
|
||||
other ->
|
||||
other
|
||||
end)
|
||||
end
|
||||
|
||||
defp blame_guard({{:., _, [:erlang, op]}, meta, [left, right]}, ann, scope, binding)
|
||||
defp blame_guard({{:., _, [:erlang, op]}, meta, [left, right]}, scope, binding)
|
||||
when op == :andalso or op == :orelse do
|
||||
guards = [
|
||||
blame_guard(left, ann, scope, binding),
|
||||
blame_guard(right, ann, scope, binding)
|
||||
blame_guard(left, scope, binding),
|
||||
blame_guard(right, scope, binding)
|
||||
]
|
||||
|
||||
kernel_op =
|
||||
case op do
|
||||
:orelse -> :or
|
||||
:andalso -> :and
|
||||
{rewrite_guard_call(op), meta, guards}
|
||||
end
|
||||
|
||||
defp blame_guard(ex_guard, scope, binding) do
|
||||
{erl_guard, _} = :elixir_erl_pass.translate(ex_guard, scope)
|
||||
|
||||
match? =
|
||||
try do
|
||||
{:value, true, _} = :erl_eval.expr(erl_guard, binding, :none)
|
||||
true
|
||||
rescue
|
||||
_ -> false
|
||||
end
|
||||
|
||||
evaluate_guard(kernel_op, meta, guards)
|
||||
blame_wrap(match?, rewrite_guard(ex_guard))
|
||||
end
|
||||
|
||||
defp blame_guard(ex_guard, ann, scope, binding) do
|
||||
ex_guard
|
||||
|> blame_guard?(binding, ann, scope)
|
||||
|> blame_wrap(rewrite_guard(ex_guard))
|
||||
end
|
||||
|
||||
defp blame_guard?(ex_guard, binding, ann, scope) do
|
||||
{erl_guard, _} = :elixir_erl_pass.translate(ex_guard, ann, scope)
|
||||
{:value, true, _} = :erl_eval.expr(erl_guard, binding, :none)
|
||||
true
|
||||
rescue
|
||||
_ -> false
|
||||
end
|
||||
|
||||
defp evaluate_guard(kernel_op, meta, guards = [_, _]) do
|
||||
[x, y] = Enum.map(guards, &evaluate_guard/1)
|
||||
|
||||
logic_value =
|
||||
case kernel_op do
|
||||
:or -> x or y
|
||||
:and -> x and y
|
||||
end
|
||||
|
||||
{kernel_op, Keyword.put(meta, :value, logic_value), guards}
|
||||
end
|
||||
|
||||
defp evaluate_guard(%{match?: value}), do: value
|
||||
defp evaluate_guard({_, meta, _}) when is_list(meta), do: meta[:value]
|
||||
|
||||
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}
|
||||
|
||||
@@ -630,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
|
||||
|
||||
@@ -704,12 +609,12 @@ defmodule Exception do
|
||||
case Code.Identifier.extract_anonymous_fun_parent(fun) do
|
||||
{outer_name, outer_arity} ->
|
||||
"anonymous fn#{format_arity(arity)} in " <>
|
||||
"#{Macro.inspect_atom(:literal, module)}." <>
|
||||
"#{Macro.inspect_atom(:remote_call, outer_name)}/#{outer_arity}"
|
||||
"#{Code.Identifier.inspect_as_atom(module)}." <>
|
||||
"#{Code.Identifier.inspect_as_function(outer_name)}/#{outer_arity}"
|
||||
|
||||
:error ->
|
||||
"#{Macro.inspect_atom(:literal, module)}." <>
|
||||
"#{Macro.inspect_atom(:remote_call, fun)}#{format_arity(arity)}"
|
||||
"#{Code.Identifier.inspect_as_atom(module)}." <>
|
||||
"#{Code.Identifier.inspect_as_function(fun)}#{format_arity(arity)}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -724,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
|
||||
@@ -740,56 +644,17 @@ 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
|
||||
|
||||
@doc false
|
||||
def format_snippet(snippet, error_line) do
|
||||
line_digits = error_line |> Integer.to_string() |> byte_size()
|
||||
placeholder = String.duplicate(" ", max(line_digits, 2))
|
||||
padding = if line_digits < 2, do: " "
|
||||
|
||||
" #{placeholder} |\n" <>
|
||||
" #{padding}#{error_line} | #{snippet.content}\n" <>
|
||||
" #{placeholder} | #{String.duplicate(" ", snippet.offset)}^"
|
||||
end
|
||||
|
||||
defp format_location(opts) when is_list(opts) do
|
||||
format_file_line(Keyword.get(opts, :file), Keyword.get(opts, :line), " ")
|
||||
end
|
||||
@@ -809,30 +674,29 @@ defmodule ArgumentError do
|
||||
|
||||
@impl true
|
||||
def blame(
|
||||
exception,
|
||||
%{message: "argument error"} = exception,
|
||||
[{:erlang, :apply, [module, function, args], _} | _] = stacktrace
|
||||
) do
|
||||
message =
|
||||
cond do
|
||||
not proper_list?(args) ->
|
||||
"you attempted to apply a function named #{inspect(function)} on module #{inspect(module)} " <>
|
||||
"with arguments #{inspect(args)}. Arguments (the third argument of apply) must always be a proper list"
|
||||
|
||||
# Note that args may be an empty list even if they were supplied
|
||||
not is_atom(module) and is_atom(function) and args == [] ->
|
||||
"you attempted to apply a function named #{inspect(function)} on #{inspect(module)}. " <>
|
||||
"If you are using Kernel.apply/3, make sure the module is an atom. " <>
|
||||
"If you are using the dot syntax, such as module.function(), " <>
|
||||
"make sure the left-hand side of the dot is a module atom"
|
||||
"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, " <>
|
||||
"make sure the left side of the dot is an atom or a map"
|
||||
|
||||
not is_atom(module) ->
|
||||
"you attempted to apply a function on #{inspect(module)}. " <>
|
||||
"Modules (the first argument of apply) must always be an atom"
|
||||
|
||||
not is_atom(function) ->
|
||||
"you attempted to apply a function named #{inspect(function)} on module #{inspect(module)}. " <>
|
||||
"However #{inspect(function)} is not a valid function name. Function names (the second argument " <>
|
||||
"of apply) must always be an atom"
|
||||
"you attempted to apply #{inspect(function)} on module #{inspect(module)}. " <>
|
||||
"Functions (the second argument of apply) must always be an atom"
|
||||
|
||||
not is_list(args) ->
|
||||
"you attempted to apply #{inspect(function)} on module #{inspect(module)} " <>
|
||||
"with arguments #{inspect(args)}. Arguments (the third argument of apply) must always be a list"
|
||||
end
|
||||
|
||||
{%{exception | message: message}, stacktrace}
|
||||
@@ -841,9 +705,6 @@ defmodule ArgumentError do
|
||||
def blame(exception, stacktrace) do
|
||||
{exception, stacktrace}
|
||||
end
|
||||
|
||||
defp proper_list?(list) when length(list) >= 0, do: true
|
||||
defp proper_list?(_), do: false
|
||||
end
|
||||
|
||||
defmodule ArithmeticError do
|
||||
@@ -887,62 +748,30 @@ defmodule ArithmeticError do
|
||||
end
|
||||
|
||||
defmodule SystemLimitError do
|
||||
defexception message: "a system limit has been reached"
|
||||
defexception []
|
||||
|
||||
@impl true
|
||||
def message(_) do
|
||||
"a system limit has been reached"
|
||||
end
|
||||
end
|
||||
|
||||
defmodule SyntaxError do
|
||||
defexception [:file, :line, :column, :snippet, description: "syntax error"]
|
||||
defexception [:file, :line, description: "syntax error"]
|
||||
|
||||
@impl true
|
||||
def message(%{
|
||||
file: file,
|
||||
line: line,
|
||||
column: column,
|
||||
description: description,
|
||||
snippet: snippet
|
||||
})
|
||||
when not is_nil(snippet) and not is_nil(column) do
|
||||
Exception.format_file_line_column(Path.relative_to_cwd(file), line, column) <>
|
||||
" " <> description <> "\n" <> Exception.format_snippet(snippet, line)
|
||||
end
|
||||
|
||||
@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, :snippet, :column, description: "expression is incomplete"]
|
||||
defexception [:file, :line, description: "expression is incomplete"]
|
||||
|
||||
@impl true
|
||||
def message(%{
|
||||
file: file,
|
||||
line: line,
|
||||
column: column,
|
||||
description: description,
|
||||
snippet: snippet
|
||||
})
|
||||
when not is_nil(snippet) and not is_nil(column) do
|
||||
Exception.format_file_line_column(Path.relative_to_cwd(file), line, column) <>
|
||||
" " <> description <> "\n" <> Exception.format_snippet(snippet, line)
|
||||
end
|
||||
|
||||
@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
|
||||
|
||||
@@ -1112,8 +941,8 @@ defmodule UndefinedFunctionError do
|
||||
end
|
||||
|
||||
defp hint(nil, _function, 0, _loaded?) do
|
||||
". If you are using the dot syntax, such as module.function(), " <>
|
||||
"make sure the left-hand side of the dot is a module atom"
|
||||
". 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
|
||||
|
||||
defp hint(module, function, arity, true) do
|
||||
@@ -1127,23 +956,11 @@ defmodule UndefinedFunctionError do
|
||||
|
||||
@doc false
|
||||
def hint_for_loaded_module(module, function, arity, exports) do
|
||||
cond do
|
||||
macro_exported?(module, function, arity) ->
|
||||
". However there is a macro with the same name and arity. " <>
|
||||
"Be sure to require #{inspect(module)} if you intend to invoke this macro"
|
||||
|
||||
message = otp_obsolete(module, function, arity) ->
|
||||
", #{message}"
|
||||
|
||||
true ->
|
||||
IO.iodata_to_binary(did_you_mean(module, function, exports))
|
||||
end
|
||||
end
|
||||
|
||||
defp otp_obsolete(module, function, arity) do
|
||||
case :otp_internal.obsolete(module, function, arity) do
|
||||
{:removed, [_ | _] = string} -> string
|
||||
_ -> nil
|
||||
if macro_exported?(module, function, arity) do
|
||||
". However there is a macro with the same name and arity. " <>
|
||||
"Be sure to require #{inspect(module)} if you intend to invoke this macro"
|
||||
else
|
||||
IO.iodata_to_binary(did_you_mean(module, function, exports))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1173,12 +990,12 @@ defmodule UndefinedFunctionError do
|
||||
|
||||
case result do
|
||||
[] -> []
|
||||
suggestions -> [". Did you mean:\n\n" | Enum.map(suggestions, &format_fa/1)]
|
||||
suggestions -> [". Did you mean one of:\n\n" | Enum.map(suggestions, &format_fa/1)]
|
||||
end
|
||||
end
|
||||
|
||||
defp format_fa({_dist, fun, arity}) do
|
||||
[" * ", Macro.inspect_atom(:remote_call, fun), ?/, Integer.to_string(arity), ?\n]
|
||||
[" * ", Code.Identifier.inspect_as_function(fun), ?/, Integer.to_string(arity), ?\n]
|
||||
end
|
||||
|
||||
defp behaviour_hint(module, function, arity) do
|
||||
@@ -1204,9 +1021,7 @@ defmodule UndefinedFunctionError do
|
||||
end
|
||||
|
||||
defp expects_callback?(behaviour, function, arity) do
|
||||
callbacks =
|
||||
behaviour.behaviour_info(:callbacks) -- behaviour.behaviour_info(:optional_callbacks)
|
||||
|
||||
callbacks = behaviour.behaviour_info(:callbacks)
|
||||
Enum.member?(callbacks, {function, arity})
|
||||
end
|
||||
|
||||
@@ -1238,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
|
||||
@@ -1248,7 +1061,7 @@ defmodule FunctionClauseError do
|
||||
|
||||
%{module: module, function: function, arity: arity} ->
|
||||
formatted = Exception.format_mfa(module, function, arity)
|
||||
blamed = blame(exception, &inspect/1, &blame_match/1)
|
||||
blamed = blame(exception, &inspect/1, &blame_match/2)
|
||||
"no function clause matching in #{formatted}" <> blamed
|
||||
end
|
||||
end
|
||||
@@ -1270,79 +1083,63 @@ defmodule FunctionClauseError do
|
||||
end
|
||||
end
|
||||
|
||||
defp blame_match(%{match?: true, node: node}), do: Macro.to_string(node)
|
||||
defp blame_match(%{match?: false, node: node}), do: "-" <> Macro.to_string(node) <> "-"
|
||||
defp blame_match(%{match?: true, node: node}, _), do: Macro.to_string(node)
|
||||
defp blame_match(%{match?: false, node: node}, _), do: "-" <> Macro.to_string(node) <> "-"
|
||||
defp blame_match(_, string), do: string
|
||||
|
||||
@doc false
|
||||
def blame(%{args: nil}, _, _) do
|
||||
""
|
||||
end
|
||||
|
||||
def blame(exception, inspect_fun, fun) do
|
||||
def blame(exception, inspect_fun, ast_fun) do
|
||||
%{module: module, function: function, arity: arity, kind: kind, args: args, clauses: clauses} =
|
||||
exception
|
||||
|
||||
mfa = Exception.format_mfa(module, function, arity)
|
||||
|
||||
format_clause_fun = fn {args, guards} ->
|
||||
args = Enum.map_join(args, ", ", fun)
|
||||
base = " #{kind} #{function}(#{args})"
|
||||
Enum.reduce(guards, base, &"#{&2} when #{clause_to_string(&1, 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 clause_to_string({op, _, [left, right]}, fun),
|
||||
do: clause_to_string(left, fun) <> " #{op} " <> clause_to_string(right, fun)
|
||||
|
||||
defp clause_to_string(node, fun), do: fun.(node)
|
||||
|
||||
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
|
||||
end
|
||||
|
||||
defmodule Code.LoadError do
|
||||
defexception [:file, :message, :reason]
|
||||
defexception [:file, :message]
|
||||
|
||||
def exception(opts) do
|
||||
file = Keyword.fetch!(opts, :file)
|
||||
reason = Keyword.fetch!(opts, :reason)
|
||||
message = "could not load #{file}. Reason: #{reason}"
|
||||
%Code.LoadError{message: message, file: file, reason: reason}
|
||||
%Code.LoadError{message: "could not load #{file}", file: file}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1404,10 +1201,6 @@ defmodule KeyError do
|
||||
end
|
||||
|
||||
@impl true
|
||||
def blame(exception = %{message: message}, stacktrace) when is_binary(message) do
|
||||
{exception, stacktrace}
|
||||
end
|
||||
|
||||
def blame(exception = %{term: nil}, stacktrace) do
|
||||
message = message(exception.key, exception.term)
|
||||
{%{exception | message: message}, stacktrace}
|
||||
@@ -1446,7 +1239,7 @@ defmodule KeyError do
|
||||
|
||||
case suggestions do
|
||||
[] -> []
|
||||
suggestions -> [". Did you mean:\n\n" | format_suggestions(suggestions)]
|
||||
suggestions -> [". Did you mean one of:\n\n" | format_suggestions(suggestions)]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1516,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
|
||||
@@ -1534,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
|
||||
@@ -1557,38 +1350,24 @@ defmodule File.LinkError do
|
||||
end
|
||||
|
||||
defmodule ErlangError do
|
||||
defexception [:original, :reason]
|
||||
defexception [:original]
|
||||
|
||||
@impl true
|
||||
def message(exception)
|
||||
|
||||
def message(%__MODULE__{original: original, reason: nil}) do
|
||||
"Erlang error: #{inspect(original)}"
|
||||
end
|
||||
|
||||
def message(%__MODULE__{original: original, reason: reason}) do
|
||||
IO.iodata_to_binary(["Erlang error: ", inspect(original), reason])
|
||||
def message(exception) do
|
||||
"Erlang error: #{inspect(exception.original)}"
|
||||
end
|
||||
|
||||
@doc false
|
||||
def normalize(:badarg, stacktrace) do
|
||||
case error_info(:badarg, stacktrace, "errors were found at the given arguments") do
|
||||
{:ok, reason, details} -> %ArgumentError{message: reason <> details}
|
||||
:error -> %ArgumentError{}
|
||||
end
|
||||
def normalize(:badarg, _stacktrace) do
|
||||
%ArgumentError{}
|
||||
end
|
||||
|
||||
def normalize(:badarith, _stacktrace) do
|
||||
%ArithmeticError{}
|
||||
end
|
||||
|
||||
def normalize(:system_limit, stacktrace) do
|
||||
default_reason = "a system limit has been reached due to errors at the given arguments"
|
||||
|
||||
case error_info(:system_limit, stacktrace, default_reason) do
|
||||
{:ok, reason, details} -> %SystemLimitError{message: reason <> details}
|
||||
:error -> %SystemLimitError{}
|
||||
end
|
||||
def normalize(:system_limit, _stacktrace) do
|
||||
%SystemLimitError{}
|
||||
end
|
||||
|
||||
def normalize(:cond_clause, _stacktrace) do
|
||||
@@ -1633,19 +1412,10 @@ defmodule ErlangError do
|
||||
%KeyError{key: key, term: term}
|
||||
end
|
||||
|
||||
def normalize({:badkey, key, map}, _stacktrace) when is_map(map) do
|
||||
def normalize({:badkey, key, map}, _stacktrace) do
|
||||
%KeyError{key: key, term: map}
|
||||
end
|
||||
|
||||
def normalize({:badkey, key, term}, _stacktrace) do
|
||||
message =
|
||||
"key #{inspect(key)} not found in: #{inspect(term)}. " <>
|
||||
"If you are using the dot syntax, such as map.field, " <>
|
||||
"make sure the left-hand side of the dot is a map"
|
||||
|
||||
%KeyError{key: key, term: term, message: message}
|
||||
end
|
||||
|
||||
def normalize({:case_clause, term}, _stacktrace) do
|
||||
%CaseClauseError{term: term}
|
||||
end
|
||||
@@ -1672,11 +1442,8 @@ defmodule ErlangError do
|
||||
%ArgumentError{message: "argument error: #{inspect(payload)}"}
|
||||
end
|
||||
|
||||
def normalize(other, stacktrace) do
|
||||
case error_info(other, stacktrace, "") do
|
||||
{:ok, _reason, details} -> %ErlangError{original: other, reason: details}
|
||||
:error -> %ErlangError{original: other}
|
||||
end
|
||||
def normalize(other, _stacktrace) do
|
||||
%ErlangError{original: other}
|
||||
end
|
||||
|
||||
defp from_stacktrace([{module, function, args, _} | _]) when is_list(args) do
|
||||
@@ -1690,104 +1457,4 @@ defmodule ErlangError do
|
||||
defp from_stacktrace(_) do
|
||||
{nil, nil, nil}
|
||||
end
|
||||
|
||||
defp error_info(erl_exception, stacktrace, default_reason) do
|
||||
with [{module, fun, args_or_arity, opts} | tail] <- stacktrace,
|
||||
%{} = error_info <- opts[:error_info] do
|
||||
error_module = Map.get(error_info, :module, module)
|
||||
error_fun = Map.get(error_info, :function, :format_error)
|
||||
|
||||
error_info = Map.put(error_info, :pretty_printer, &inspect/1)
|
||||
head = {module, fun, args_or_arity, Keyword.put(opts, :error_info, error_info)}
|
||||
|
||||
extra =
|
||||
try do
|
||||
apply(error_module, error_fun, [erl_exception, [head | tail]])
|
||||
rescue
|
||||
_ -> %{}
|
||||
end
|
||||
|
||||
arity = if is_integer(args_or_arity), do: args_or_arity, else: length(args_or_arity)
|
||||
args_errors = Map.take(extra, Enum.to_list(1..arity//1))
|
||||
reason = Map.get(extra, :reason, default_reason)
|
||||
|
||||
cond do
|
||||
map_size(args_errors) > 0 ->
|
||||
{:ok, reason, IO.iodata_to_binary([":\n\n" | Enum.map(args_errors, &arg_error/1)])}
|
||||
|
||||
general = extra[:general] ->
|
||||
{:ok, reason, ": " <> general}
|
||||
|
||||
true ->
|
||||
:error
|
||||
end
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp arg_error({n, message}), do: " * #{nth(n)} argument: #{message}\n"
|
||||
|
||||
defp nth(1), do: "1st"
|
||||
defp nth(2), do: "2nd"
|
||||
defp nth(3), do: "3rd"
|
||||
defp nth(n), do: "#{n}th"
|
||||
end
|
||||
|
||||
defmodule Inspect.Error do
|
||||
@moduledoc """
|
||||
Raised when a struct cannot be inspected.
|
||||
"""
|
||||
@enforce_keys [:exception_module, :exception_message, :stacktrace, :inspected_struct]
|
||||
defexception @enforce_keys
|
||||
|
||||
@impl true
|
||||
def exception(arguments) when is_list(arguments) do
|
||||
exception = Keyword.fetch!(arguments, :exception)
|
||||
exception_module = exception.__struct__
|
||||
exception_message = Exception.message(exception) |> String.trim_trailing("\n")
|
||||
stacktrace = Keyword.fetch!(arguments, :stacktrace)
|
||||
inspected_struct = Keyword.fetch!(arguments, :inspected_struct)
|
||||
|
||||
%Inspect.Error{
|
||||
exception_module: exception_module,
|
||||
exception_message: exception_message,
|
||||
stacktrace: stacktrace,
|
||||
inspected_struct: inspected_struct
|
||||
}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def message(%__MODULE__{
|
||||
exception_module: exception_module,
|
||||
exception_message: exception_message,
|
||||
inspected_struct: inspected_struct
|
||||
}) do
|
||||
~s'''
|
||||
got #{inspect(exception_module)} with message:
|
||||
|
||||
"""
|
||||
#{pad(exception_message, 4)}
|
||||
"""
|
||||
|
||||
while inspecting:
|
||||
|
||||
#{pad(inspected_struct, 4)}
|
||||
'''
|
||||
end
|
||||
|
||||
@doc false
|
||||
def pad(message, padding_length)
|
||||
when is_binary(message) and is_integer(padding_length) and padding_length >= 0 do
|
||||
padding = String.duplicate(" ", padding_length)
|
||||
|
||||
message
|
||||
|> String.split("\n")
|
||||
|> Enum.map(fn
|
||||
"" -> "\n"
|
||||
line -> [padding, line, ?\n]
|
||||
end)
|
||||
|> IO.iodata_to_binary()
|
||||
|> String.trim_trailing("\n")
|
||||
end
|
||||
end
|
||||
|
||||
+102
-170
@@ -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,9 +110,6 @@ defmodule File do
|
||||
|
||||
@type stream_mode ::
|
||||
encoding_mode()
|
||||
| :append
|
||||
| :compressed
|
||||
| :delayed_write
|
||||
| :trim_bom
|
||||
| {:read_ahead, pos_integer | false}
|
||||
| {:delayed_write, non_neg_integer, non_neg_integer}
|
||||
@@ -123,8 +120,6 @@ defmodule File do
|
||||
|
||||
@type posix_time :: integer()
|
||||
|
||||
@type on_conflict_callback :: (Path.t(), Path.t() -> boolean)
|
||||
|
||||
@doc """
|
||||
Returns `true` if the path is a regular file.
|
||||
|
||||
@@ -590,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)
|
||||
|
||||
@@ -696,10 +691,7 @@ defmodule File do
|
||||
@spec copy(Path.t() | io_device, Path.t() | io_device, pos_integer | :infinity) ::
|
||||
{:ok, non_neg_integer} | {:error, posix}
|
||||
def copy(source, destination, bytes_count \\ :infinity) do
|
||||
source = normalize_path_or_io_device(source)
|
||||
destination = normalize_path_or_io_device(destination)
|
||||
|
||||
:file.copy(source, destination, bytes_count)
|
||||
:file.copy(maybe_to_string(source), maybe_to_string(destination), bytes_count)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -717,8 +709,8 @@ defmodule File do
|
||||
raise File.CopyError,
|
||||
reason: reason,
|
||||
action: "copy",
|
||||
source: normalize_path_or_io_device(source),
|
||||
destination: normalize_path_or_io_device(destination)
|
||||
source: maybe_to_string(source),
|
||||
destination: maybe_to_string(destination)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -730,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.
|
||||
|
||||
@@ -743,11 +735,8 @@ 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
|
||||
source = IO.chardata_to_string(source)
|
||||
destination = IO.chardata_to_string(destination)
|
||||
:file.rename(source, destination)
|
||||
end
|
||||
|
||||
@@ -772,11 +761,15 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Copies the contents of `source_file` to `destination_file` preserving its modes.
|
||||
Copies the contents in `source_file` to `destination_file` preserving its modes.
|
||||
|
||||
`source_file` must be a file or a symbolic link to one. `destination_file` must
|
||||
be a path to a non-existent file. If either is a directory, `{:error, :eisdir}`
|
||||
will be returned.
|
||||
`source_file` and `destination_file` must be a file or a symbolic link to one,
|
||||
or in the case of destination, a path to a non-existent file. If either one of
|
||||
them is a directory, `{:error, :eisdir}` will be returned.
|
||||
|
||||
If a file already exists in the destination, it invokes a
|
||||
callback which should return `true` if the existing file
|
||||
should be overwritten, `false` otherwise. The callback defaults to return `true`.
|
||||
|
||||
The function returns `:ok` in case of success. Otherwise, it returns
|
||||
`{:error, reason}`.
|
||||
@@ -785,34 +778,17 @@ 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.
|
||||
|
||||
## Options
|
||||
|
||||
* `:on_conflict` - (since v1.14.0) Invoked when a file already exists in the destination.
|
||||
The function receives arguments for `source_file` and `destination_file`. It should
|
||||
return `true` if the existing file should be overwritten, `false` if otherwise.
|
||||
The default callback returns `true`. On earlier versions, this callback could be
|
||||
given as third argument, but such behaviour is now deprecated.
|
||||
|
||||
"""
|
||||
@spec cp(Path.t(), Path.t(), on_conflict: on_conflict_callback) :: :ok | {:error, posix}
|
||||
def cp(source_file, destination_file, options \\ [])
|
||||
|
||||
# TODO: Deprecate me on Elixir v1.19
|
||||
def cp(source_file, destination_file, callback) when is_function(callback, 2) do
|
||||
cp(source_file, destination_file, on_conflict: callback)
|
||||
end
|
||||
|
||||
def cp(source_file, destination_file, options) when is_list(options) do
|
||||
on_conflict = Keyword.get(options, :on_conflict, fn _, _ -> true end)
|
||||
@spec cp(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok | {:error, posix}
|
||||
def cp(source_file, destination_file, callback \\ fn _, _ -> true end) do
|
||||
source_file = IO.chardata_to_string(source_file)
|
||||
destination_file = IO.chardata_to_string(destination_file)
|
||||
|
||||
case do_cp_file(source_file, destination_file, on_conflict, []) do
|
||||
case do_cp_file(source_file, destination_file, callback, []) do
|
||||
{:error, reason, _} -> {:error, reason}
|
||||
_ -> :ok
|
||||
end
|
||||
@@ -828,9 +804,9 @@ defmodule File do
|
||||
The same as `cp/3`, but raises a `File.CopyError` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
"""
|
||||
@spec cp!(Path.t(), Path.t(), on_conflict: on_conflict_callback) :: :ok
|
||||
def cp!(source_file, destination_file, options \\ []) do
|
||||
case cp(source_file, destination_file, options) do
|
||||
@spec cp!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok
|
||||
def cp!(source_file, destination_file, callback \\ fn _, _ -> true end) do
|
||||
case cp(source_file, destination_file, callback) do
|
||||
:ok ->
|
||||
:ok
|
||||
|
||||
@@ -853,38 +829,28 @@ defmodule File do
|
||||
If `source` is a directory, or a symbolic link to it, then `destination` must
|
||||
be an existent `directory` or a symbolic link to one, or a path to a non-existent directory.
|
||||
|
||||
If the source is a file, it copies `source` to `destination`. If the `source`
|
||||
is a directory, it copies the contents inside source into the `destination` directory.
|
||||
If the source is a file, it copies `source` to
|
||||
`destination`. If the `source` is a directory, it copies
|
||||
the contents inside source into the `destination` directory.
|
||||
|
||||
If a file already exists in the destination, it invokes the optional `on_conflict`
|
||||
callback given as an option. See "Options" for more information.
|
||||
If a file already exists in the destination, it invokes `callback`.
|
||||
`callback` must be a function that takes two arguments: `source` and `destination`.
|
||||
The callback should return `true` if the existing file should be overwritten and `false` otherwise.
|
||||
|
||||
This function may fail while copying files, in such cases, it will leave the
|
||||
destination directory in a dirty state, where file which have already been
|
||||
copied won't be removed.
|
||||
This function may fail while copying files,
|
||||
in such cases, it will leave the destination
|
||||
directory in a dirty state, where file which have already been copied
|
||||
won't be removed.
|
||||
|
||||
The function returns `{:ok, files_and_directories}` in case of
|
||||
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.
|
||||
|
||||
## Options
|
||||
|
||||
* `:on_conflict` - (since v1.14.0) Invoked when a file already exists in the destination.
|
||||
The function receives arguments for `source` and `destination`. It should return
|
||||
`true` if the existing file should be overwritten, `false` if otherwise. The default
|
||||
callback returns `true`. On earlier versions, this callback could be given as third
|
||||
argument, but such behaviour is now deprecated.
|
||||
|
||||
* `:dereference_symlinks` - (since v1.14.0) By default, this function will copy symlinks
|
||||
by creating symlinks that point to the same location. This option forces symlinks to be
|
||||
dereferenced and have their contents copied instead when set to `true`. If the dereferenced
|
||||
files do not exist, than the operation fails. The default is `false`.
|
||||
|
||||
## Examples
|
||||
|
||||
# Copies file "a.txt" to "b.txt"
|
||||
@@ -894,28 +860,14 @@ defmodule File do
|
||||
File.cp_r("samples", "tmp")
|
||||
|
||||
# Same as before, but asks the user how to proceed in case of conflicts
|
||||
File.cp_r("samples", "tmp", on_conflict: fn source, destination ->
|
||||
File.cp_r("samples", "tmp", fn source, destination ->
|
||||
IO.gets("Overwriting #{destination} by #{source}. Type y to confirm. ") == "y\n"
|
||||
end)
|
||||
|
||||
"""
|
||||
@spec cp_r(Path.t(), Path.t(),
|
||||
on_conflict: on_conflict_callback,
|
||||
dereference_symlinks: boolean()
|
||||
) ::
|
||||
@spec cp_r(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) ::
|
||||
{:ok, [binary]} | {:error, posix, binary}
|
||||
|
||||
def cp_r(source, destination, options \\ [])
|
||||
|
||||
# TODO: Deprecate me on Elixir v1.19
|
||||
def cp_r(source, destination, callback) when is_function(callback, 2) do
|
||||
cp_r(source, destination, on_conflict: callback)
|
||||
end
|
||||
|
||||
def cp_r(source, destination, options) when is_list(options) do
|
||||
on_conflict = Keyword.get(options, :on_conflict, fn _, _ -> true end)
|
||||
dereference? = Keyword.get(options, :dereference_symlinks, false)
|
||||
|
||||
def cp_r(source, destination, callback \\ fn _, _ -> true end) when is_function(callback, 2) do
|
||||
source =
|
||||
source
|
||||
|> IO.chardata_to_string()
|
||||
@@ -926,7 +878,7 @@ defmodule File do
|
||||
|> IO.chardata_to_string()
|
||||
|> assert_no_null_byte!("File.cp_r/3")
|
||||
|
||||
case do_cp_r(source, destination, on_conflict, dereference?, []) do
|
||||
case do_cp_r(source, destination, callback, []) do
|
||||
{:error, _, _} = error -> error
|
||||
res -> {:ok, res}
|
||||
end
|
||||
@@ -936,12 +888,9 @@ defmodule File do
|
||||
The same as `cp_r/3`, but raises a `File.CopyError` exception if it fails.
|
||||
Returns the list of copied files otherwise.
|
||||
"""
|
||||
@spec cp_r!(Path.t(), Path.t(),
|
||||
on_conflict: on_conflict_callback,
|
||||
dereference_symlinks: boolean()
|
||||
) :: [binary]
|
||||
def cp_r!(source, destination, options \\ []) do
|
||||
case cp_r(source, destination, options) do
|
||||
@spec cp_r!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: [binary]
|
||||
def cp_r!(source, destination, callback \\ fn _, _ -> true end) do
|
||||
case cp_r(source, destination, callback) do
|
||||
{:ok, files} ->
|
||||
files
|
||||
|
||||
@@ -955,21 +904,15 @@ defmodule File do
|
||||
end
|
||||
end
|
||||
|
||||
defp do_cp_r(src, dest, on_conflict, dereference?, acc) when is_list(acc) do
|
||||
defp do_cp_r(src, dest, callback, acc) when is_list(acc) do
|
||||
case :elixir_utils.read_link_type(src) do
|
||||
{:ok, :regular} ->
|
||||
do_cp_file(src, dest, on_conflict, acc)
|
||||
do_cp_file(src, dest, callback, acc)
|
||||
|
||||
{:ok, :symlink} ->
|
||||
case :file.read_link(src) do
|
||||
{:ok, link} when dereference? ->
|
||||
do_cp_r(Path.expand(link, Path.dirname(src)), dest, on_conflict, dereference?, acc)
|
||||
|
||||
{:ok, link} ->
|
||||
do_cp_link(link, src, dest, on_conflict, acc)
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason, src}
|
||||
{:ok, link} -> do_cp_link(link, src, dest, callback, acc)
|
||||
{:error, reason} -> {:error, reason, src}
|
||||
end
|
||||
|
||||
{:ok, :directory} ->
|
||||
@@ -978,7 +921,7 @@ defmodule File do
|
||||
case mkdir(dest) do
|
||||
success when success in [:ok, {:error, :eexist}] ->
|
||||
Enum.reduce(files, [dest | acc], fn x, acc ->
|
||||
do_cp_r(Path.join(src, x), Path.join(dest, x), on_conflict, dereference?, acc)
|
||||
do_cp_r(Path.join(src, x), Path.join(dest, x), callback, acc)
|
||||
end)
|
||||
|
||||
{:error, reason} ->
|
||||
@@ -997,8 +940,9 @@ defmodule File do
|
||||
end
|
||||
end
|
||||
|
||||
# If we reach this clause, there was an error while processing a file.
|
||||
defp do_cp_r(_, _, _, _, acc) do
|
||||
# If we reach this clause, there was an error while
|
||||
# processing a file.
|
||||
defp do_cp_r(_, _, _, acc) do
|
||||
acc
|
||||
end
|
||||
|
||||
@@ -1007,14 +951,14 @@ defmodule File do
|
||||
end
|
||||
|
||||
# Both src and dest are files.
|
||||
defp do_cp_file(src, dest, on_conflict, acc) do
|
||||
defp do_cp_file(src, dest, callback, acc) do
|
||||
case :file.copy(src, {dest, [:exclusive]}) do
|
||||
{:ok, _} ->
|
||||
copy_file_mode!(src, dest)
|
||||
[dest | acc]
|
||||
|
||||
{:error, :eexist} ->
|
||||
if path_differs?(src, dest) and on_conflict.(src, dest) do
|
||||
if path_differs?(src, dest) and callback.(src, dest) do
|
||||
case copy(src, dest) do
|
||||
{:ok, _} ->
|
||||
copy_file_mode!(src, dest)
|
||||
@@ -1033,13 +977,13 @@ defmodule File do
|
||||
end
|
||||
|
||||
# Both src and dest are files.
|
||||
defp do_cp_link(link, src, dest, on_conflict, acc) do
|
||||
defp do_cp_link(link, src, dest, callback, acc) do
|
||||
case :file.make_symlink(link, dest) do
|
||||
:ok ->
|
||||
[dest | acc]
|
||||
|
||||
{:error, :eexist} ->
|
||||
if path_differs?(src, dest) and on_conflict.(src, dest) do
|
||||
if path_differs?(src, dest) and callback.(src, dest) do
|
||||
# If rm/1 fails, :file.make_symlink/2 will fail
|
||||
_ = rm(dest)
|
||||
|
||||
@@ -1096,7 +1040,9 @@ defmodule File do
|
||||
"""
|
||||
@spec write!(Path.t(), iodata, [mode]) :: :ok
|
||||
def write!(path, content, modes \\ []) do
|
||||
case write(path, content, modes) do
|
||||
modes = normalize_modes(modes, false)
|
||||
|
||||
case :file.write_file(path, content, modes) do
|
||||
:ok ->
|
||||
:ok
|
||||
|
||||
@@ -1244,79 +1190,82 @@ defmodule File do
|
||||
"""
|
||||
@spec rm_rf(Path.t()) :: {:ok, [binary]} | {:error, posix, binary}
|
||||
def rm_rf(path) do
|
||||
{major, _} = :os.type()
|
||||
|
||||
path
|
||||
|> IO.chardata_to_string()
|
||||
|> assert_no_null_byte!("File.rm_rf/1")
|
||||
|> do_rm_rf([], major)
|
||||
|> do_rm_rf({:ok, []})
|
||||
end
|
||||
|
||||
defp do_rm_rf(path, acc, major) do
|
||||
case safe_list_dir(path, major) do
|
||||
defp do_rm_rf(path, {:ok, _} = entry) do
|
||||
case safe_list_dir(path) do
|
||||
{:ok, files} when is_list(files) ->
|
||||
acc =
|
||||
Enum.reduce(files, acc, fn file, acc ->
|
||||
# In case we can't delete, continue anyway, we might succeed
|
||||
# to delete it on Windows due to how they handle symlinks.
|
||||
case do_rm_rf(Path.join(path, file), acc, major) do
|
||||
{:ok, acc} -> acc
|
||||
{:error, _, _} -> acc
|
||||
end
|
||||
res =
|
||||
Enum.reduce(files, entry, fn file, tuple ->
|
||||
do_rm_rf(Path.join(path, file), tuple)
|
||||
end)
|
||||
|
||||
case rmdir(path) do
|
||||
:ok -> {:ok, [path | acc]}
|
||||
{:error, :enoent} -> {:ok, acc}
|
||||
{:error, reason} -> {:error, reason, path}
|
||||
case res do
|
||||
{:ok, acc} ->
|
||||
case rmdir(path) do
|
||||
:ok -> {:ok, [path | acc]}
|
||||
{:error, :enoent} -> res
|
||||
{:error, reason} -> {:error, reason, path}
|
||||
end
|
||||
|
||||
reason ->
|
||||
reason
|
||||
end
|
||||
|
||||
{:ok, :directory} ->
|
||||
do_rm_directory(path, acc)
|
||||
do_rm_directory(path, entry)
|
||||
|
||||
{:ok, :regular} ->
|
||||
do_rm_regular(path, acc)
|
||||
do_rm_regular(path, entry)
|
||||
|
||||
{:error, reason} when reason in [:enoent, :enotdir] ->
|
||||
{:ok, acc}
|
||||
entry
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, reason, path}
|
||||
end
|
||||
end
|
||||
|
||||
defp do_rm_regular(path, acc) do
|
||||
defp do_rm_rf(_, reason) do
|
||||
reason
|
||||
end
|
||||
|
||||
defp do_rm_regular(path, {:ok, acc} = entry) do
|
||||
case rm(path) do
|
||||
:ok -> {:ok, [path | acc]}
|
||||
{:error, :enoent} -> {:ok, acc}
|
||||
{:error, :enoent} -> entry
|
||||
{:error, reason} -> {:error, reason, path}
|
||||
end
|
||||
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 to remove it as a directory and, if we get :enotdir,
|
||||
# we fall back to a file removal.
|
||||
defp do_rm_directory(path, acc) do
|
||||
# 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
|
||||
case rmdir(path) do
|
||||
:ok -> {:ok, [path | acc]}
|
||||
{:error, :enotdir} -> do_rm_regular(path, acc)
|
||||
{:error, :enoent} -> {:ok, acc}
|
||||
{:error, :enotdir} -> do_rm_regular(path, entry)
|
||||
{:error, :enoent} -> entry
|
||||
{:error, reason} -> {:error, reason, path}
|
||||
end
|
||||
end
|
||||
|
||||
defp safe_list_dir(path, major) do
|
||||
defp safe_list_dir(path) do
|
||||
case :elixir_utils.read_link_type(path) do
|
||||
{:ok, :directory} ->
|
||||
:file.list_dir_all(path)
|
||||
|
||||
{:ok, :symlink} when major == :win32 ->
|
||||
{:ok, :symlink} ->
|
||||
case :elixir_utils.read_file_type(path) do
|
||||
{:ok, :directory} -> {:ok, :directory}
|
||||
_ -> {:ok, :regular}
|
||||
end
|
||||
|
||||
{:ok, :directory} ->
|
||||
:file.list_dir(path)
|
||||
|
||||
{:ok, _} ->
|
||||
{:ok, :regular}
|
||||
|
||||
@@ -1361,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.
|
||||
@@ -1406,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.
|
||||
@@ -1515,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.
|
||||
@@ -1554,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}
|
||||
@@ -1589,12 +1530,6 @@ defmodule File do
|
||||
executes the given function and then reverts back
|
||||
to the previous path regardless of whether there is an exception.
|
||||
|
||||
The current working directory is temporarily 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`.
|
||||
|
||||
Raises an error if retrieving or changing the current
|
||||
directory fails.
|
||||
"""
|
||||
@@ -1654,16 +1589,14 @@ defmodule File do
|
||||
:file.close(io_device)
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
@doc """
|
||||
Returns a `File.Stream` for the given `path` with the given `modes`.
|
||||
|
||||
The stream implements both `Enumerable` and `Collectable` protocols,
|
||||
which means it can be used both for read and write.
|
||||
|
||||
The `line_or_bytes` argument configures how the file is read when
|
||||
streaming, by `:line` (default) or by a given number of bytes. When
|
||||
using the `:line` option, CRLF line breaks (`"\r\n"`) are normalized
|
||||
to LF (`"\n"`).
|
||||
streaming, by `:line` (default) or by a given number of bytes.
|
||||
|
||||
Operating the stream can fail on open for the same reasons as
|
||||
`File.open!/2`. Note that the file is automatically opened each time streaming
|
||||
@@ -1677,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` .
|
||||
@@ -1702,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)
|
||||
@@ -1852,8 +1785,7 @@ defmodule File do
|
||||
defp normalize_modes([], true), do: [:binary]
|
||||
defp normalize_modes([], false), do: []
|
||||
|
||||
defp normalize_path_or_io_device(path) when is_list(path), do: IO.chardata_to_string(path)
|
||||
defp normalize_path_or_io_device(path) when is_binary(path), do: path
|
||||
defp normalize_path_or_io_device(io_device) when is_pid(io_device), do: io_device
|
||||
defp normalize_path_or_io_device(io_device = {:file_descriptor, _, _}), do: io_device
|
||||
defp maybe_to_string(path) when is_list(path), do: IO.chardata_to_string(path)
|
||||
defp maybe_to_string(path) when is_binary(path), do: path
|
||||
defp maybe_to_string(path), do: path
|
||||
end
|
||||
|
||||
@@ -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`,
|
||||
|
||||
+53
-162
@@ -15,7 +15,7 @@ defmodule Float do
|
||||
## Known issues
|
||||
|
||||
There are some very well known problems with floating-point numbers
|
||||
and arithmetic due to the fact most decimal fractions cannot be
|
||||
and arithmetics due to the fact most decimal fractions cannot be
|
||||
represented by a floating-point binary and most operations are not exact,
|
||||
but operate on approximations. Those issues are not specific
|
||||
to Elixir, they are a property of floating point representation itself.
|
||||
@@ -46,71 +46,6 @@ defmodule Float do
|
||||
@precision_range 0..15
|
||||
@type precision_range :: 0..15
|
||||
|
||||
@min_finite then(<<0xFFEFFFFFFFFFFFFF::64>>, fn <<num::float>> -> num end)
|
||||
@max_finite then(<<0x7FEFFFFFFFFFFFFF::64>>, fn <<num::float>> -> num end)
|
||||
|
||||
@doc """
|
||||
Returns the maximum finite value for a float.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Float.max_finite()
|
||||
1.7976931348623157e308
|
||||
|
||||
"""
|
||||
def max_finite, do: @max_finite
|
||||
|
||||
@doc """
|
||||
Returns the minimum finite value for a float.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Float.min_finite()
|
||||
-1.7976931348623157e308
|
||||
|
||||
"""
|
||||
def min_finite, do: @min_finite
|
||||
|
||||
@doc """
|
||||
Computes `base` raised to power of `exponent`.
|
||||
|
||||
`base` must be a float and `exponent` can be any number.
|
||||
However, if a negative base and a fractional exponent
|
||||
are given, it raises `ArithmeticError`.
|
||||
|
||||
It always returns a float. See `Integer.pow/2` for
|
||||
exponentiation that returns integers.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Float.pow(2.0, 0)
|
||||
1.0
|
||||
iex> Float.pow(2.0, 1)
|
||||
2.0
|
||||
iex> Float.pow(2.0, 10)
|
||||
1024.0
|
||||
iex> Float.pow(2.0, -1)
|
||||
0.5
|
||||
iex> Float.pow(2.0, -3)
|
||||
0.125
|
||||
|
||||
iex> Float.pow(3.0, 1.5)
|
||||
5.196152422706632
|
||||
|
||||
iex> Float.pow(-2.0, 3)
|
||||
-8.0
|
||||
iex> Float.pow(-2.0, 4)
|
||||
16.0
|
||||
|
||||
iex> Float.pow(-1.0, 0.5)
|
||||
** (ArithmeticError) bad argument in arithmetic expression
|
||||
|
||||
"""
|
||||
@doc since: "1.12.0"
|
||||
@spec pow(float, number) :: float
|
||||
def pow(base, exponent) when is_float(base) and is_number(exponent),
|
||||
do: :math.pow(base, exponent)
|
||||
|
||||
@doc """
|
||||
Parses a binary into a float.
|
||||
|
||||
@@ -119,8 +54,7 @@ defmodule Float do
|
||||
returned.
|
||||
|
||||
If the size of float exceeds the maximum size of `1.7976931348623157e+308`,
|
||||
`:error` is returned even though the textual representation itself might be
|
||||
well formed.
|
||||
the `ArgumentError` exception is raised.
|
||||
|
||||
If you want to convert a string-formatted float directly to a float,
|
||||
`String.to_float/1` can be used instead.
|
||||
@@ -136,8 +70,6 @@ defmodule Float do
|
||||
|
||||
iex> Float.parse("pi")
|
||||
:error
|
||||
iex> Float.parse("1.7976931348623159e+308")
|
||||
:error
|
||||
|
||||
"""
|
||||
@spec parse(binary) :: {float, binary} | :error
|
||||
@@ -175,18 +107,7 @@ defmodule Float do
|
||||
when exp_marker in 'eE' and sign in '-+' and digit in ?0..?9,
|
||||
do: parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, sign, digit>>)
|
||||
|
||||
# When floats are expressed in scientific notation, :erlang.binary_to_float/1 can raise an
|
||||
# ArgumentError if the e exponent is too big. For example, "1.0e400". Because of this, we
|
||||
# rescue the ArgumentError here and return an error.
|
||||
defp parse_unsigned(rest, dot?, true = _e?, acc) do
|
||||
:erlang.binary_to_float(add_dot(acc, dot?))
|
||||
rescue
|
||||
ArgumentError -> :error
|
||||
else
|
||||
float -> {float, rest}
|
||||
end
|
||||
|
||||
defp parse_unsigned(rest, dot?, false = _e?, acc),
|
||||
defp parse_unsigned(rest, dot?, _e?, acc),
|
||||
do: {:erlang.binary_to_float(add_dot(acc, dot?)), rest}
|
||||
|
||||
defp add_dot(acc, true), do: acc
|
||||
@@ -347,11 +268,11 @@ defmodule Float do
|
||||
raise ArgumentError, invalid_precision_message(precision)
|
||||
end
|
||||
|
||||
defp round(0.0 = num, _precision, _rounding), do: num
|
||||
defp round(0.0, _precision, _rounding), do: 0.0
|
||||
|
||||
defp round(float, precision, rounding) do
|
||||
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
|
||||
{num, count} = decompose(significant, 1)
|
||||
{num, count, _} = decompose(significant, 1)
|
||||
count = count - exp + 1023
|
||||
|
||||
cond do
|
||||
@@ -403,22 +324,6 @@ defmodule Float do
|
||||
end
|
||||
end
|
||||
|
||||
defp decompose(significant, initial) do
|
||||
decompose(significant, 1, 0, initial)
|
||||
end
|
||||
|
||||
defp decompose(<<1::1, bits::bitstring>>, count, last_count, acc) do
|
||||
decompose(bits, count + 1, count, (acc <<< (count - last_count)) + 1)
|
||||
end
|
||||
|
||||
defp decompose(<<0::1, bits::bitstring>>, count, last_count, acc) do
|
||||
decompose(bits, count + 1, last_count, acc)
|
||||
end
|
||||
|
||||
defp decompose(<<>>, _count, last_count, acc) do
|
||||
{acc, last_count}
|
||||
end
|
||||
|
||||
defp scale_up(num, boundary, exp) when num >= boundary, do: {num, exp}
|
||||
defp scale_up(num, boundary, exp), do: scale_up(num <<< 1, boundary, exp - 1)
|
||||
|
||||
@@ -498,70 +403,63 @@ defmodule Float do
|
||||
def ratio(0.0), do: {0, 1}
|
||||
|
||||
def ratio(float) when is_float(float) do
|
||||
<<sign::1, exp::11, mantissa::52>> = <<float::float>>
|
||||
case <<float::float>> do
|
||||
<<sign::1, 0::11, significant::52-bitstring>> ->
|
||||
{num, _, den} = decompose(significant, 0)
|
||||
{sign(sign, num), shift_left(den, 1022)}
|
||||
|
||||
{num, den_exp} =
|
||||
if exp != 0 do
|
||||
# Floats are expressed like this:
|
||||
# (2**52 + mantissa) * 2**(-52 + exp - 1023)
|
||||
#
|
||||
# We compute the root factors of the mantissa so we have this:
|
||||
# (2**52 + mantissa * 2**count) * 2**(-52 + exp - 1023)
|
||||
{mantissa, count} = root_factors(mantissa, 0)
|
||||
<<sign::1, exp::11, significant::52-bitstring>> ->
|
||||
{num, _, den} = decompose(significant, 1)
|
||||
num = sign(sign, num)
|
||||
|
||||
# Now we can move the count around so we have this:
|
||||
# (2**(52-count) + mantissa) * 2**(count + -52 + exp - 1023)
|
||||
if mantissa == 0 do
|
||||
{1, exp - 1023}
|
||||
else
|
||||
num = (1 <<< (52 - count)) + mantissa
|
||||
den_exp = count - 52 + exp - 1023
|
||||
{num, den_exp}
|
||||
case exp - 1023 do
|
||||
exp when exp > 0 ->
|
||||
{den, exp} = shift_right(den, exp)
|
||||
{shift_left(num, exp), den}
|
||||
|
||||
exp when exp < 0 ->
|
||||
{num, shift_left(den, -exp)}
|
||||
|
||||
0 ->
|
||||
{num, den}
|
||||
end
|
||||
else
|
||||
# Subnormals are expressed like this:
|
||||
# (mantissa) * 2**(-52 + 1 - 1023)
|
||||
#
|
||||
# So we compute it to this:
|
||||
# (mantissa * 2**(count)) * 2**(-52 + 1 - 1023)
|
||||
#
|
||||
# Which becomes:
|
||||
# mantissa * 2**(count-1074)
|
||||
root_factors(mantissa, -1074)
|
||||
end
|
||||
|
||||
if den_exp > 0 do
|
||||
{sign(sign, num <<< den_exp), 1}
|
||||
else
|
||||
{sign(sign, num), 1 <<< -den_exp}
|
||||
end
|
||||
end
|
||||
|
||||
defp root_factors(mantissa, count) when mantissa != 0 and (mantissa &&& 1) == 0,
|
||||
do: root_factors(mantissa >>> 1, count + 1)
|
||||
defp decompose(significant, initial) do
|
||||
decompose(significant, 1, 0, 2, 1, initial)
|
||||
end
|
||||
|
||||
defp root_factors(mantissa, count),
|
||||
do: {mantissa, count}
|
||||
defp decompose(<<1::1, bits::bitstring>>, count, last_count, power, _last_power, acc) do
|
||||
decompose(bits, count + 1, count, power <<< 1, power, shift_left(acc, count - last_count) + 1)
|
||||
end
|
||||
|
||||
@compile {:inline, sign: 2}
|
||||
defp decompose(<<0::1, bits::bitstring>>, count, last_count, power, last_power, acc) do
|
||||
decompose(bits, count + 1, last_count, power <<< 1, last_power, acc)
|
||||
end
|
||||
|
||||
defp decompose(<<>>, _count, last_count, _power, last_power, acc) do
|
||||
{acc, last_count, last_power}
|
||||
end
|
||||
|
||||
@compile {:inline, sign: 2, shift_left: 2}
|
||||
defp sign(0, num), do: num
|
||||
defp sign(1, num), do: -num
|
||||
|
||||
defp shift_left(num, times), do: num <<< times
|
||||
|
||||
defp shift_right(num, 0), do: {num, 0}
|
||||
defp shift_right(1, times), do: {1, times}
|
||||
defp shift_right(num, times), do: shift_right(num >>> 1, times - 1)
|
||||
|
||||
@doc """
|
||||
Returns a charlist which corresponds to the shortest text representation
|
||||
Returns a charlist which corresponds to the text representation
|
||||
of the given float.
|
||||
|
||||
The underlying algorithm changes depending on the Erlang/OTP version:
|
||||
|
||||
* For OTP >= 24, it uses the algorithm presented in "Ryū: fast
|
||||
float-to-string conversion" in Proceedings of the SIGPLAN '2018
|
||||
Conference on Programming Language Design and Implementation.
|
||||
|
||||
* For OTP < 24, it uses the algorithm presented in "Printing Floating-Point
|
||||
Numbers Quickly and Accurately" in Proceedings of the SIGPLAN '1996
|
||||
Conference on Programming Language Design and Implementation.
|
||||
|
||||
For a configurable representation, use `:erlang.float_to_list/2`.
|
||||
It uses the shortest representation according to algorithm described
|
||||
in "Printing Floating-Point Numbers Quickly and Accurately" in
|
||||
Proceedings of the SIGPLAN '96 Conference on Programming Language
|
||||
Design and Implementation.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -575,20 +473,13 @@ defmodule Float do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a binary which corresponds to the shortest text representation
|
||||
Returns a binary which corresponds to the text representation
|
||||
of the given float.
|
||||
|
||||
The underlying algorithm changes depending on the Erlang/OTP version:
|
||||
|
||||
* For OTP >= 24, it uses the algorithm presented in "Ryū: fast
|
||||
float-to-string conversion" in Proceedings of the SIGPLAN '2018
|
||||
Conference on Programming Language Design and Implementation.
|
||||
|
||||
* For OTP < 24, it uses the algorithm presented in "Printing Floating-Point
|
||||
Numbers Quickly and Accurately" in Proceedings of the SIGPLAN '1996
|
||||
Conference on Programming Language Design and Implementation.
|
||||
|
||||
For a configurable representation, use `:erlang.float_to_binary/2`.
|
||||
It uses the shortest representation according to algorithm described
|
||||
in "Printing Floating-Point Numbers Quickly and Accurately" in
|
||||
Proceedings of the SIGPLAN '96 Conference on Programming Language
|
||||
Design and Implementation.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -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 `&/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
|
||||
|
||||
@@ -2,12 +2,12 @@ defmodule GenEvent do
|
||||
# Functions from this module are deprecated in elixir_dispatch.
|
||||
|
||||
@moduledoc """
|
||||
An event manager with event handlers behaviour.
|
||||
A event manager with event handlers behaviour.
|
||||
|
||||
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`](`:gen_event`) instead.
|
||||
`:gen_event` instead.
|
||||
|
||||
## Alternatives
|
||||
|
||||
@@ -38,7 +38,7 @@ defmodule GenEvent do
|
||||
|
||||
If your use case requires exactly what GenEvent provided, or you have to
|
||||
integrate with an existing `:gen_event`-based system, you can still use the
|
||||
[`:gen_event`](`:gen_event`) Erlang module.
|
||||
[`:gen_event`](http://erlang.org/doc/man/gen_event.html) Erlang module.
|
||||
"""
|
||||
|
||||
@moduledoc deprecated: "Use Erlang/OTP's :gen_event module instead"
|
||||
@@ -91,7 +91,7 @@ defmodule GenEvent do
|
||||
deprecation_message =
|
||||
"the GenEvent module is deprecated, see its documentation for alternatives"
|
||||
|
||||
IO.warn(deprecation_message, __CALLER__)
|
||||
IO.warn(deprecation_message, Macro.Env.stacktrace(__CALLER__))
|
||||
|
||||
quote location: :keep do
|
||||
@behaviour :gen_event
|
||||
|
||||
+80
-107
@@ -61,7 +61,7 @@ defmodule GenServer do
|
||||
|
||||
Every time you do a `GenServer.call/3`, the client will send a message
|
||||
that must be handled by the `c:handle_call/3` callback in the GenServer.
|
||||
A `cast/2` message must be handled by `c:handle_cast/2`. There are 8 possible
|
||||
A `cast/2` message must be handled by `c:handle_cast/2`. There are 7 possible
|
||||
callbacks to be implemented when you use a `GenServer`. The only required
|
||||
callback is `c:init/1`.
|
||||
|
||||
@@ -153,27 +153,22 @@ defmodule GenServer do
|
||||
detailed information. The `@doc` annotation immediately preceding
|
||||
`use GenServer` will be attached to the generated `child_spec/1` function.
|
||||
|
||||
When stopping the GenServer, for example by returning a `{:stop, reason, new_state}`
|
||||
tuple from a callback, the exit reason is used by the supervisor to determine
|
||||
whether the GenServer needs to be restarted. See the "Exit reasons and restarts"
|
||||
section in the `Supervisor` module.
|
||||
|
||||
## Name registration
|
||||
|
||||
Both `start_link/3` and `start/3` support the `GenServer` to register
|
||||
a name on start via the `:name` option. Registered names are also
|
||||
automatically cleaned up on termination. The supported values are:
|
||||
|
||||
* an atom - the GenServer is registered locally (to the current node)
|
||||
with the given name using `Process.register/2`.
|
||||
* an atom - the GenServer is registered locally with the given name
|
||||
using `Process.register/2`.
|
||||
|
||||
* `{:global, term}` - the GenServer is registered globally with the given
|
||||
term using the functions in the [`:global` module](`:global`).
|
||||
term using the functions in the [`:global` module](http://www.erlang.org/doc/man/global.html).
|
||||
|
||||
* `{:via, module, term}` - the GenServer is registered with the given
|
||||
mechanism and name. The `:via` option expects a module that exports
|
||||
`register_name/2`, `unregister_name/1`, `whereis_name/1` and `send/2`.
|
||||
One such example is the [`:global` module](`:global`) which uses these functions
|
||||
One such example is the [`:global` module](http://www.erlang.org/doc/man/global.html) which uses these functions
|
||||
for keeping the list of names of processes and their associated PIDs
|
||||
that are available globally for a network of Elixir nodes. Elixir also
|
||||
ships with a local, decentralized and scalable registry called `Registry`
|
||||
@@ -212,7 +207,7 @@ defmodule GenServer do
|
||||
the GenServer callbacks as doing so will cause the GenServer to misbehave.
|
||||
|
||||
Besides the synchronous and asynchronous communication provided by `call/3`
|
||||
and `cast/2`, "regular" messages sent by functions such as `send/2`,
|
||||
and `cast/2`, "regular" messages sent by functions such as `Kernel.send/2`,
|
||||
`Process.send_after/4` and similar, can be handled inside the `c:handle_info/2`
|
||||
callback.
|
||||
|
||||
@@ -247,8 +242,7 @@ defmodule GenServer do
|
||||
end
|
||||
|
||||
defp schedule_work do
|
||||
# We schedule the work to happen in 2 hours (written in milliseconds).
|
||||
# Alternatively, one might write :timer.hours(2)
|
||||
# In 2 hours
|
||||
Process.send_after(self(), :work, 2 * 60 * 60 * 1000)
|
||||
end
|
||||
end
|
||||
@@ -259,20 +253,15 @@ defmodule GenServer do
|
||||
a timeout value in milliseconds; if not, `:infinity` is assumed.
|
||||
The timeout can be used to detect a lull in incoming messages.
|
||||
|
||||
The `timeout()` value is used as follows:
|
||||
If the process has no messages waiting when the timeout is set and the
|
||||
number of given milliseconds pass without any message arriving,
|
||||
then `handle_info/2` will be called with `:timeout` as the first argument.
|
||||
The timeout is cleared if any message is waiting or arrives before the
|
||||
given timeout.
|
||||
|
||||
* If the process has any message already waiting when the `timeout()` value
|
||||
is returned, the timeout is ignored and the waiting message is handled as
|
||||
usual. This means that even a timeout of `0` milliseconds is not guaranteed
|
||||
to execute (if you want to take another action immediately and unconditionally,
|
||||
use a `:continue` instruction instead).
|
||||
|
||||
* If any message arrives before the specified number of milliseconds
|
||||
elapse, the timeout is cleared and that message is handled as usual.
|
||||
|
||||
* Otherwise, when the specified number of milliseconds have elapsed with no
|
||||
message arriving, `handle_info/2` is called with `:timeout` as the first
|
||||
argument.
|
||||
Because a message may arrive before the timeout is set, even a timeout of `0`
|
||||
milliseconds is not guaranteed to execute. To take another action immediately
|
||||
and unconditionally, use a `:continue` instruction.
|
||||
|
||||
## When (not) to use a GenServer
|
||||
|
||||
@@ -291,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
|
||||
@@ -322,14 +307,14 @@ defmodule GenServer do
|
||||
|
||||
## Debugging with the :sys module
|
||||
|
||||
GenServers, as [special processes](https://www.erlang.org/doc/design_principles/spec_proc.html),
|
||||
can be debugged using the [`:sys` module](`:sys`).
|
||||
GenServers, as [special processes](http://erlang.org/doc/design_principles/spec_proc.html),
|
||||
can be debugged using the [`:sys` module](http://www.erlang.org/doc/man/sys.html).
|
||||
Through various hooks, this module allows developers to introspect the state of
|
||||
the process and trace system events that happen during its execution, such as
|
||||
received messages, sent replies and state changes.
|
||||
|
||||
Let's explore the basic functions from the
|
||||
[`:sys` module](`:sys`) used for debugging:
|
||||
[`:sys` module](http://www.erlang.org/doc/man/sys.html) used for debugging:
|
||||
|
||||
* `:sys.get_state/2` - allows retrieval of the state of the process.
|
||||
In the case of a GenServer process, it will be the callback module state,
|
||||
@@ -411,8 +396,8 @@ defmodule GenServer do
|
||||
in Erlang can also provide extra insight.
|
||||
|
||||
* [GenServer - Elixir's Getting Started Guide](https://elixir-lang.org/getting-started/mix-otp/genserver.html)
|
||||
* [`:gen_server` module documentation](`:gen_server`)
|
||||
* [gen_server Behaviour - OTP Design Principles](https://www.erlang.org/doc/design_principles/gen_server_concepts.html)
|
||||
* [`:gen_server` module documentation](http://www.erlang.org/doc/man/gen_server.html)
|
||||
* [gen_server Behaviour - OTP Design Principles](http://www.erlang.org/doc/design_principles/gen_server_concepts.html)
|
||||
* [Clients and Servers - Learn You Some Erlang for Great Good!](http://learnyousomeerlang.com/clients-and-servers)
|
||||
|
||||
"""
|
||||
@@ -434,10 +419,10 @@ defmodule GenServer do
|
||||
except the process is hibernated before entering the loop. See
|
||||
`c:handle_call/3` for more information on hibernation.
|
||||
|
||||
Returning `{:ok, state, {:continue, continue_arg}}` is similar to
|
||||
`{:ok, state}` except that immediately after entering the loop,
|
||||
the `c:handle_continue/2` callback will be invoked with `continue_arg`
|
||||
as the first argument and `state` as the second one.
|
||||
Returning `{:ok, state, {:continue, continue}}` is similar to
|
||||
`{:ok, state}` except that immediately after entering the loop
|
||||
the `c:handle_continue/2` callback will be invoked with the value
|
||||
`continue` as first argument.
|
||||
|
||||
Returning `:ignore` will cause `start_link/3` to return `:ignore` and
|
||||
the process will exit normally without entering the loop or calling
|
||||
@@ -460,7 +445,7 @@ defmodule GenServer do
|
||||
"""
|
||||
@callback init(init_arg :: term) ::
|
||||
{:ok, state}
|
||||
| {:ok, state, timeout | :hibernate | {:continue, continue_arg :: term}}
|
||||
| {:ok, state, timeout | :hibernate | {:continue, term}}
|
||||
| :ignore
|
||||
| {:stop, reason :: any}
|
||||
when state: any
|
||||
@@ -482,15 +467,14 @@ defmodule GenServer do
|
||||
|
||||
Returning `{:reply, reply, new_state, :hibernate}` is similar to
|
||||
`{:reply, reply, new_state}` except the process is hibernated and will
|
||||
continue the loop once a message is in its message queue. However, if a message is
|
||||
already in the message queue, the process will continue the loop immediately. Hibernating a
|
||||
continue the loop once a message is in its message queue. If a message is
|
||||
already in the message queue this will be immediately. Hibernating a
|
||||
`GenServer` causes garbage collection and leaves a continuous heap that
|
||||
minimises the memory used by the process.
|
||||
|
||||
Returning `{:reply, reply, new_state, {:continue, continue_arg}}` is similar to
|
||||
`{:reply, reply, new_state}` except that `c:handle_continue/2` will be invoked
|
||||
immediately after with `continue_arg` as the first argument and
|
||||
`state` as the second one.
|
||||
Returning `{:reply, reply, new_state, {:continue, continue}}` is similar to
|
||||
`{:reply, reply, new_state}` except `c:handle_continue/2` will be invoked
|
||||
immediately after with the value `continue` as first argument.
|
||||
|
||||
Hibernating should not be used aggressively as too much time could be spent
|
||||
garbage collecting. Normally it should only be used when a message is not
|
||||
@@ -513,12 +497,12 @@ defmodule GenServer do
|
||||
process exits without replying as the caller will be blocking awaiting a
|
||||
reply.
|
||||
|
||||
Returning `{:noreply, new_state, timeout | :hibernate | {:continue, continue_arg}}`
|
||||
Returning `{:noreply, new_state, timeout | :hibernate | {:continue, continue}}`
|
||||
is similar to `{:noreply, new_state}` except a timeout, hibernation or continue
|
||||
occurs as with a `:reply` tuple.
|
||||
|
||||
Returning `{:stop, reason, reply, new_state}` stops the loop and `c:terminate/2`
|
||||
is called with reason `reason` and state `new_state`. Then, the `reply` is sent
|
||||
is called with reason `reason` and state `new_state`. Then the `reply` is sent
|
||||
as the response to call and the process exits with reason `reason`.
|
||||
|
||||
Returning `{:stop, reason, new_state}` is similar to
|
||||
@@ -529,10 +513,9 @@ defmodule GenServer do
|
||||
"""
|
||||
@callback handle_call(request :: term, from, state :: term) ::
|
||||
{:reply, reply, new_state}
|
||||
| {:reply, reply, new_state,
|
||||
timeout | :hibernate | {:continue, continue_arg :: term}}
|
||||
| {:reply, reply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, continue_arg :: term}}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:stop, reason, reply, new_state}
|
||||
| {:stop, reason, new_state}
|
||||
when reply: term, new_state: term, reason: term
|
||||
@@ -553,10 +536,9 @@ defmodule GenServer do
|
||||
`{:noreply, new_state}` except the process is hibernated before continuing the
|
||||
loop. See `c:handle_call/3` for more information.
|
||||
|
||||
Returning `{:noreply, new_state, {:continue, continue_arg}}` is similar to
|
||||
Returning `{:noreply, new_state, {:continue, continue}}` is similar to
|
||||
`{:noreply, new_state}` except `c:handle_continue/2` will be invoked
|
||||
immediately after with `continue_arg` as the first argument and
|
||||
`state` as the second one.
|
||||
immediately after with the value `continue` as first argument.
|
||||
|
||||
Returning `{:stop, reason, new_state}` stops the loop and `c:terminate/2` is
|
||||
called with the reason `reason` and state `new_state`. The process exits with
|
||||
@@ -567,7 +549,7 @@ defmodule GenServer do
|
||||
"""
|
||||
@callback handle_cast(request :: term, state :: term) ::
|
||||
{:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, continue_arg :: term}}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:stop, reason :: term, new_state}
|
||||
when new_state: term
|
||||
|
||||
@@ -584,12 +566,12 @@ defmodule GenServer do
|
||||
"""
|
||||
@callback handle_info(msg :: :timeout | term, state :: term) ::
|
||||
{:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, continue_arg :: term}}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:stop, reason :: term, new_state}
|
||||
when new_state: term
|
||||
|
||||
@doc """
|
||||
Invoked to handle continue instructions.
|
||||
Invoked to handle `continue` instructions.
|
||||
|
||||
It is useful for performing work after initialization or for splitting the work
|
||||
in a callback in multiple steps, updating the process state along the way.
|
||||
@@ -598,12 +580,14 @@ defmodule GenServer do
|
||||
|
||||
This callback is optional. If one is not implemented, the server will fail
|
||||
if a continue instruction is used.
|
||||
|
||||
This callback is only supported on Erlang/OTP 21+.
|
||||
"""
|
||||
@callback handle_continue(continue_arg, state :: term) ::
|
||||
@callback handle_continue(continue :: term, state :: term) ::
|
||||
{:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, continue_arg}}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:stop, reason :: term, new_state}
|
||||
when new_state: term, continue_arg: term
|
||||
when new_state: term
|
||||
|
||||
@doc """
|
||||
Invoked when the server is about to exit. It should do any cleanup required.
|
||||
@@ -611,13 +595,15 @@ defmodule GenServer do
|
||||
`reason` is exit reason and `state` is the current state of the `GenServer`.
|
||||
The return value is ignored.
|
||||
|
||||
`c:terminate/2` is called if the `GenServer` traps exits (using `Process.flag/2`)
|
||||
*and* the parent process sends an exit signal, or a callback (except `c:init/1`)
|
||||
does one of the following:
|
||||
`c:terminate/2` is called if a callback (except `c:init/1`) does one of the
|
||||
following:
|
||||
|
||||
* returns a `:stop` tuple
|
||||
* raises (via `raise/2`) or exits (via `exit/1`)
|
||||
* raises
|
||||
* calls `Kernel.exit/1`
|
||||
* returns an invalid value
|
||||
* the `GenServer` traps exits (using `Process.flag/2`) *and* the parent
|
||||
process sends an exit signal
|
||||
|
||||
If part of a supervision tree, a `GenServer` will receive an exit
|
||||
signal when the tree is shutting down. The exit signal is based on
|
||||
@@ -643,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`.
|
||||
@@ -654,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
|
||||
@@ -683,7 +669,11 @@ defmodule GenServer do
|
||||
when old_vsn: term | {:down, term}
|
||||
|
||||
@doc """
|
||||
Invoked in some cases to retrieve a formatted version of the `GenServer` status:
|
||||
Invoked in some cases to retrieve a formatted version of the `GenServer` status.
|
||||
|
||||
This callback can be useful to control the *appearance* of the status of the
|
||||
`GenServer`. For example, it can be used to return a compact representation of
|
||||
the `GenServer`'s state to avoid having large state terms printed.
|
||||
|
||||
* one of `:sys.get_status/1` or `:sys.get_status/2` is invoked to get the
|
||||
status of the `GenServer`; in such cases, `reason` is `:normal`
|
||||
@@ -691,10 +681,6 @@ defmodule GenServer do
|
||||
* the `GenServer` terminates abnormally and logs an error; in such cases,
|
||||
`reason` is `:terminate`
|
||||
|
||||
This callback can be useful to control the *appearance* of the status of the
|
||||
`GenServer`. For example, it can be used to return a compact representation of
|
||||
the `GenServer`'s state to avoid having large state terms printed.
|
||||
|
||||
`pdict_and_state` is a two-elements list `[pdict, state]` where `pdict` is a
|
||||
list of `{key, value}` tuples representing the current process dictionary of
|
||||
the `GenServer` and `state` is the current state of the `GenServer`.
|
||||
@@ -724,7 +710,7 @@ defmodule GenServer do
|
||||
{:debug, debug}
|
||||
| {:name, name}
|
||||
| {:timeout, timeout}
|
||||
| {:spawn_opt, [Process.spawn_opt()]}
|
||||
| {:spawn_opt, Process.spawn_opt()}
|
||||
| {:hibernate_after, timeout}
|
||||
|
||||
@typedoc "Debug options supported by the `start*` functions"
|
||||
@@ -751,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.
|
||||
|
||||
@@ -799,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
|
||||
|
||||
@@ -866,7 +838,7 @@ defmodule GenServer do
|
||||
the arguments given to GenServer.start_link/3 to the server state.
|
||||
"""
|
||||
|
||||
IO.warn(message, env)
|
||||
IO.warn(message, Macro.Env.stacktrace(env))
|
||||
|
||||
quote do
|
||||
@doc false
|
||||
@@ -903,7 +875,7 @@ defmodule GenServer do
|
||||
milliseconds initializing or it will be terminated and the start function
|
||||
will return `{:error, :timeout}`
|
||||
|
||||
* `:debug` - if present, the corresponding function in the [`:sys` module](`:sys`) is invoked
|
||||
* `:debug` - if present, the corresponding function in the [`:sys` module](http://www.erlang.org/doc/man/sys.html) is invoked
|
||||
|
||||
* `:spawn_opt` - if present, its value is passed as options to the
|
||||
underlying process as in `Process.spawn/4`
|
||||
@@ -1026,7 +998,6 @@ defmodule GenServer do
|
||||
nil ->
|
||||
exit({:noproc, {__MODULE__, :call, [server, request, timeout]}})
|
||||
|
||||
# TODO: remove this clause when we require Erlang/OTP 25+
|
||||
pid when pid == self() ->
|
||||
exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}})
|
||||
|
||||
@@ -1050,8 +1021,18 @@ defmodule GenServer do
|
||||
is unknown whether the destination `server` successfully
|
||||
handled the message.
|
||||
|
||||
`c:handle_cast/2` will be called on the server to handle
|
||||
the request. In case the `server` is on a node which is
|
||||
not yet connected to the caller one, the semantics differ
|
||||
depending on the used Erlang/OTP version.
|
||||
|
||||
`server` can be any of the values described in the "Name registration"
|
||||
section of the documentation for this module.
|
||||
|
||||
Before Erlang/OTP 21, the call is going to block until a
|
||||
connection happens. This was done to guarantee ordering.
|
||||
Starting with Erlang/OTP 21, both Erlang and Elixir do
|
||||
not block the call.
|
||||
"""
|
||||
@spec cast(server, term) :: :ok
|
||||
def cast(server, request)
|
||||
@@ -1174,16 +1155,16 @@ defmodule GenServer do
|
||||
|
||||
"""
|
||||
@spec reply(from, term) :: :ok
|
||||
def reply(client, reply) do
|
||||
:gen.reply(client, reply)
|
||||
def reply(client, reply)
|
||||
|
||||
def reply({to, tag}, reply) when is_pid(to) do
|
||||
send(to, {tag, reply})
|
||||
:ok
|
||||
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
|
||||
|
||||
@@ -1224,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
|
||||
|
||||
+89
-262
@@ -8,85 +8,16 @@ defprotocol Inspect do
|
||||
The `Inspect` protocol converts an Elixir data structure into an
|
||||
algebra document.
|
||||
|
||||
This is typically done when you want to customize how your own
|
||||
structs are inspected in logs and the terminal.
|
||||
|
||||
This documentation refers to implementing the `Inspect` protocol
|
||||
for your own data structures. To learn more about using inspect,
|
||||
see `Kernel.inspect/2` and `IO.inspect/2`.
|
||||
|
||||
## Inspect representation
|
||||
The `inspect/2` function receives the entity to be inspected
|
||||
followed by the inspecting options, represented by the struct
|
||||
`Inspect.Opts`. Building of the algebra document is done with
|
||||
`Inspect.Algebra`.
|
||||
|
||||
There are typically three choices of inspect representation. In order
|
||||
to understand them, let's imagine we have the following `User` struct:
|
||||
|
||||
defmodule User do
|
||||
defstruct [:id, :name, :address]
|
||||
end
|
||||
|
||||
Our choices are:
|
||||
|
||||
1. Print the struct using Elixir's struct syntax, for example:
|
||||
`%User{address: "Earth", id: 13, name: "Jane"}`. This is the
|
||||
default representation and best choice if all struct fields
|
||||
are public.
|
||||
|
||||
2. Print using the `#User<...>` notation, for example: `#User<id: 13, name: "Jane", ...>`.
|
||||
This notation does not emit valid Elixir code and is typically
|
||||
used when the struct has private fields (for example, you may want
|
||||
to hide the field `:address` to redact person identifiable information).
|
||||
|
||||
3. Print the struct using the expression syntax, for example:
|
||||
`User.new(13, "Jane", "Earth")`. This assumes there is a `User.new/3`
|
||||
function. This option is mostly used as an alternative to option 2
|
||||
for representing custom data structures, such as `MapSet`, `Date.Range`,
|
||||
and others.
|
||||
|
||||
You can implement the Inspect protocol for your own structs while
|
||||
adhering to the conventions above. Option 1 is the default representation
|
||||
and you can quickly achieve option 2 by deriving the `Inspect` protocol.
|
||||
For option 3, you need your custom implementation.
|
||||
|
||||
## Deriving
|
||||
|
||||
The `Inspect` protocol can be derived to customize the order of fields
|
||||
(the default is alphabetical) and hide certain fields from structs,
|
||||
so they don't show up in logs, inspects and similar. The latter is
|
||||
especially useful for fields containing private information.
|
||||
|
||||
The supported options are:
|
||||
|
||||
* `:only` - only include the given fields when inspecting.
|
||||
|
||||
* `:except` - remove the given fields when inspecting.
|
||||
|
||||
* `:optional` - (since v1.14.0) do not include a field if it
|
||||
matches its default value. This can be used to simplify the
|
||||
struct representation at the cost of hiding information.
|
||||
|
||||
Whenever `:only` or `:except` are used to restrict fields,
|
||||
the struct will be printed using the `#User<...>` notation,
|
||||
as the struct can no longer be copy and pasted as valid Elixir
|
||||
code. Let's see an example:
|
||||
|
||||
defmodule User do
|
||||
@derive {Inspect, only: [:id, :name]}
|
||||
defstruct [:id, :name, :address]
|
||||
end
|
||||
|
||||
inspect(%User{id: 1, name: "Jane", address: "Earth"})
|
||||
#=> #User<id: 1, name: "Jane", ...>
|
||||
|
||||
If you use only the `:optional` option, the struct will still be
|
||||
printed as `%User{...}`.
|
||||
|
||||
## Custom implementation
|
||||
|
||||
You can also define your custom protocol implementation by
|
||||
defining the `inspect/2` function. The function receives the
|
||||
entity to be inspected followed by the inspecting options,
|
||||
represented by the struct `Inspect.Opts`. Building of the
|
||||
algebra document is done with `Inspect.Algebra`.
|
||||
## Examples
|
||||
|
||||
Many times, inspecting a structure can be implemented in function
|
||||
of existing entities. For example, here is `MapSet`'s `inspect/2`
|
||||
@@ -95,25 +26,23 @@ defprotocol Inspect do
|
||||
defimpl Inspect, for: MapSet do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(map_set, opts) do
|
||||
concat(["MapSet.new(", Inspect.List.inspect(MapSet.to_list(map_set), opts), ")"])
|
||||
def inspect(dict, opts) do
|
||||
concat(["#MapSet<", to_doc(MapSet.to_list(dict), opts), ">"])
|
||||
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.new("`,
|
||||
the document returned by `Inspect.Algebra.to_doc/2`, and the final
|
||||
string `")"`. Therefore, the MapSet with the numbers 1, 2, and 3
|
||||
will be printed as:
|
||||
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 `">"`.
|
||||
|
||||
iex> MapSet.new([1, 2, 3], fn x -> x * 2 end)
|
||||
MapSet.new([2, 4, 6])
|
||||
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.
|
||||
|
||||
In other words, `MapSet`'s inspect representation returns an expression
|
||||
that, when evaluated, builds the `MapSet` itself.
|
||||
|
||||
### Error handling
|
||||
## Error handling
|
||||
|
||||
In case there is an error while your structure is being inspected,
|
||||
Elixir will raise an `ArgumentError` error and will automatically fall back
|
||||
@@ -125,6 +54,24 @@ defprotocol Inspect do
|
||||
|
||||
Inspect.MapSet.inspect(MapSet.new(), %Inspect.Opts{})
|
||||
|
||||
## Deriving
|
||||
|
||||
The `Inspect` protocol can be derived to hide certain fields from
|
||||
structs, so they don't show up in logs, inspects and similar. This
|
||||
is especially useful for fields containing private information.
|
||||
|
||||
The options `:only` and `:except` can be used with `@derive` to
|
||||
specify which fields should and should not appear in the
|
||||
algebra document:
|
||||
|
||||
defmodule User do
|
||||
@derive {Inspect, only: [:id, :name]}
|
||||
defstruct [:id, :name, :address]
|
||||
end
|
||||
|
||||
inspect(%User{id: 1, name: "Homer", address: "742 Evergreen Terrace"})
|
||||
#=> #User<id: 1, name: "Homer", ...>
|
||||
|
||||
"""
|
||||
|
||||
# Handle structs in Any
|
||||
@@ -146,7 +93,7 @@ defimpl Inspect, for: Atom do
|
||||
require Macro
|
||||
|
||||
def inspect(atom, opts) do
|
||||
color(Macro.inspect_atom(:literal, atom), color_key(atom), opts)
|
||||
color(Identifier.inspect_as_atom(atom), color_key(atom), opts)
|
||||
end
|
||||
|
||||
defp color_key(atom) when is_boolean(atom), do: :boolean
|
||||
@@ -209,7 +156,7 @@ defimpl Inspect, for: BitString do
|
||||
defp each_bit(bitstring, _counter, opts) do
|
||||
size = bit_size(bitstring)
|
||||
<<h::size(size)>> = bitstring
|
||||
concat(Inspect.Integer.inspect(h, opts), "::size(" <> Integer.to_string(size) <> ")")
|
||||
Inspect.Integer.inspect(h, opts) <> "::size(" <> Integer.to_string(size) <> ")"
|
||||
end
|
||||
|
||||
@compile {:inline, decrement: 1}
|
||||
@@ -262,7 +209,7 @@ defimpl Inspect, for: List do
|
||||
{escaped, _} -> [?', escaped, ?', " ++ ..."]
|
||||
end
|
||||
|
||||
color(IO.iodata_to_binary(inspected), :charlist, opts)
|
||||
IO.iodata_to_binary(inspected)
|
||||
|
||||
keyword?(term) ->
|
||||
container_doc(open, term, close, opts, &keyword/2, separator: sep, break: :strict)
|
||||
@@ -274,7 +221,7 @@ defimpl Inspect, for: List do
|
||||
|
||||
@doc false
|
||||
def keyword({key, value}, opts) do
|
||||
key = color(Macro.inspect_atom(:key, key), :atom, opts)
|
||||
key = color(Identifier.inspect_as_key(key), :atom, opts)
|
||||
concat(key, concat(" ", to_doc(value, opts)))
|
||||
end
|
||||
|
||||
@@ -302,38 +249,28 @@ end
|
||||
|
||||
defimpl Inspect, for: Map do
|
||||
def inspect(map, opts) do
|
||||
list =
|
||||
if Keyword.get(opts.custom_options, :sort_maps) do
|
||||
map |> Map.to_list() |> :lists.sort()
|
||||
else
|
||||
Map.to_list(map)
|
||||
end
|
||||
|
||||
fun =
|
||||
if Inspect.List.keyword?(list) do
|
||||
&Inspect.List.keyword/2
|
||||
else
|
||||
sep = color(" => ", :map, opts)
|
||||
&to_assoc(&1, &2, sep)
|
||||
end
|
||||
|
||||
map_container_doc(list, "", opts, fun)
|
||||
inspect(map, "", opts)
|
||||
end
|
||||
|
||||
def inspect(map, name, infos, opts) do
|
||||
fun = fn %{field: field}, opts -> Inspect.List.keyword({field, Map.get(map, field)}, opts) end
|
||||
map_container_doc(infos, name, opts, fun)
|
||||
end
|
||||
|
||||
defp to_assoc({key, value}, opts, sep) do
|
||||
concat(concat(to_doc(key, opts), sep), to_doc(value, opts))
|
||||
end
|
||||
|
||||
defp map_container_doc(list, name, opts, fun) do
|
||||
def inspect(map, name, opts) do
|
||||
map = :maps.to_list(map)
|
||||
open = color("%" <> name <> "{", :map, opts)
|
||||
sep = color(",", :map, opts)
|
||||
close = color("}", :map, opts)
|
||||
container_doc(open, list, close, opts, fun, separator: sep, break: :strict)
|
||||
container_doc(open, map, close, opts, traverse_fun(map, opts), separator: sep, break: :strict)
|
||||
end
|
||||
|
||||
defp traverse_fun(list, opts) do
|
||||
if Inspect.List.keyword?(list) do
|
||||
&Inspect.List.keyword/2
|
||||
else
|
||||
sep = color(" => ", :map, opts)
|
||||
&to_map(&1, &2, sep)
|
||||
end
|
||||
end
|
||||
|
||||
defp to_map({key, value}, opts, sep) do
|
||||
concat(concat(to_doc(key, opts), sep), to_doc(value, opts))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -371,31 +308,13 @@ defimpl Inspect, for: Integer do
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Float do
|
||||
def inspect(float, opts) do
|
||||
abs = abs(float)
|
||||
|
||||
formatted =
|
||||
if abs >= 1.0 and abs < 1.0e16 and trunc(float) == float do
|
||||
[Integer.to_string(trunc(float)), ?., ?0]
|
||||
else
|
||||
:io_lib_format.fwrite_g(float)
|
||||
end
|
||||
|
||||
color(IO.iodata_to_binary(formatted), :number, opts)
|
||||
def inspect(term, opts) do
|
||||
inspected = IO.iodata_to_binary(:io_lib_format.fwrite_g(term))
|
||||
color(inspected, :number, opts)
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Regex do
|
||||
def inspect(regex = %{opts: regex_opts}, opts) when is_list(regex_opts) do
|
||||
concat([
|
||||
"Regex.compile!(",
|
||||
Inspect.BitString.inspect(regex.source, opts),
|
||||
", ",
|
||||
Inspect.List.inspect(regex_opts, opts),
|
||||
")"
|
||||
])
|
||||
end
|
||||
|
||||
def inspect(regex, opts) do
|
||||
{escaped, _} =
|
||||
regex.source
|
||||
@@ -427,12 +346,9 @@ defimpl Inspect, for: Function do
|
||||
name = fun_info[:name]
|
||||
|
||||
cond do
|
||||
not is_atom(mod) ->
|
||||
"#Function<#{uniq(fun_info)}/#{fun_info[:arity]}>"
|
||||
|
||||
fun_info[:type] == :external and fun_info[:env] == [] ->
|
||||
inspected_as_atom = Macro.inspect_atom(:literal, mod)
|
||||
inspected_as_function = Macro.inspect_atom(:remote_call, name)
|
||||
inspected_as_atom = Identifier.inspect_as_atom(mod)
|
||||
inspected_as_function = Identifier.inspect_as_function(name)
|
||||
"&#{inspected_as_atom}.#{inspected_as_function}/#{fun_info[:arity]}"
|
||||
|
||||
match?('elixir_compiler_' ++ _, Atom.to_charlist(mod)) ->
|
||||
@@ -448,7 +364,7 @@ defimpl Inspect, for: Function do
|
||||
end
|
||||
|
||||
defp default_inspect(mod, fun_info) do
|
||||
inspected_as_atom = Macro.inspect_atom(:literal, mod)
|
||||
inspected_as_atom = Identifier.inspect_as_atom(mod)
|
||||
extracted_name = extract_name(fun_info[:name])
|
||||
"#Function<#{uniq(fun_info)}/#{fun_info[:arity]} in #{inspected_as_atom}#{extracted_name}>"
|
||||
end
|
||||
@@ -460,10 +376,10 @@ defimpl Inspect, for: Function do
|
||||
defp extract_name(name) do
|
||||
case Identifier.extract_anonymous_fun_parent(name) do
|
||||
{name, arity} ->
|
||||
"." <> Macro.inspect_atom(:remote_call, name) <> "/" <> arity
|
||||
"." <> Identifier.inspect_as_function(name) <> "/" <> arity
|
||||
|
||||
:error ->
|
||||
"." <> Macro.inspect_atom(:remote_call, name)
|
||||
"." <> Identifier.inspect_as_function(name)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -472,36 +388,6 @@ defimpl Inspect, for: Function do
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Inspect.Error do
|
||||
@impl true
|
||||
def inspect(%{stacktrace: stacktrace} = inspect_error, _opts) do
|
||||
message = Exception.message(inspect_error)
|
||||
format_output(message, stacktrace)
|
||||
end
|
||||
|
||||
defp format_output(message, [_ | _] = stacktrace) do
|
||||
stacktrace = Exception.format_stacktrace(stacktrace)
|
||||
|
||||
"""
|
||||
#Inspect.Error<
|
||||
#{Inspect.Error.pad(message, 2)}
|
||||
|
||||
Stacktrace:
|
||||
|
||||
#{stacktrace}
|
||||
>\
|
||||
"""
|
||||
end
|
||||
|
||||
defp format_output(message, []) do
|
||||
"""
|
||||
#Inspect.Error<
|
||||
#{Inspect.Error.pad(message, 2)}
|
||||
>\
|
||||
"""
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect, for: PID do
|
||||
def inspect(pid, _opts) do
|
||||
"#PID" <> IO.iodata_to_binary(:erlang.pid_to_list(pid))
|
||||
@@ -523,122 +409,63 @@ 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, [])
|
||||
optional = Keyword.get(options, :optional, [])
|
||||
|
||||
:ok = validate_option(:only, only, fields, module)
|
||||
:ok = validate_option(:except, except, fields, module)
|
||||
:ok = validate_option(:optional, optional, fields, module)
|
||||
|
||||
inspect_module =
|
||||
if fields == only and except == [] do
|
||||
Inspect.Map
|
||||
else
|
||||
Inspect.Any
|
||||
end
|
||||
|
||||
filtered_fields =
|
||||
fields
|
||||
|> Enum.reject(&(&1 in except))
|
||||
|> Enum.filter(&(&1 in only))
|
||||
|
||||
optional? =
|
||||
if optional == [] do
|
||||
false
|
||||
inspect_module =
|
||||
if fields == only and except == [] do
|
||||
quote(do: Inspect.Map)
|
||||
else
|
||||
optional_map = for field <- optional, into: %{}, do: {field, Map.fetch!(struct, field)}
|
||||
|
||||
quote do
|
||||
case unquote(Macro.escape(optional_map)) do
|
||||
%{^var!(field) => var!(default)} ->
|
||||
var!(default) == Map.get(var!(struct), var!(field))
|
||||
|
||||
%{} ->
|
||||
false
|
||||
end
|
||||
end
|
||||
quote(do: Inspect.Any)
|
||||
end
|
||||
|
||||
quote do
|
||||
defimpl Inspect, for: unquote(module) do
|
||||
def inspect(var!(struct), var!(opts)) do
|
||||
var!(infos) =
|
||||
for %{field: var!(field)} = var!(info) <- unquote(module).__info__(:struct),
|
||||
var!(field) in unquote(filtered_fields) and not unquote(optional?),
|
||||
do: var!(info)
|
||||
|
||||
var!(name) = Macro.inspect_atom(:literal, unquote(module))
|
||||
unquote(inspect_module).inspect(var!(struct), var!(name), var!(infos), 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
|
||||
end
|
||||
|
||||
defp validate_option(option, option_list, fields, module) do
|
||||
case option_list -- fields do
|
||||
[] ->
|
||||
:ok
|
||||
|
||||
unknown_fields ->
|
||||
raise ArgumentError,
|
||||
"unknown fields #{Kernel.inspect(unknown_fields)} in #{Kernel.inspect(option)} " <>
|
||||
"when deriving the Inspect protocol for #{Kernel.inspect(module)}"
|
||||
end
|
||||
end
|
||||
|
||||
def inspect(%module{} = struct, opts) do
|
||||
try do
|
||||
{module.__struct__(), module.__info__(:struct)}
|
||||
module.__struct__
|
||||
rescue
|
||||
_ -> Inspect.Map.inspect(struct, opts)
|
||||
else
|
||||
{dunder, fields} ->
|
||||
if Map.keys(dunder) == Map.keys(struct) do
|
||||
infos =
|
||||
for %{field: field} = info <- fields,
|
||||
field not in [:__struct__, :__exception__],
|
||||
do: info
|
||||
|
||||
Inspect.Map.inspect(struct, Macro.inspect_atom(:literal, module), infos, opts)
|
||||
dunder ->
|
||||
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)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def inspect(map, name, infos, opts) do
|
||||
def inspect(map, name, opts) do
|
||||
# Use the :limit option and an extra element to force
|
||||
# `container_doc/6` to append "...".
|
||||
opts = %{opts | limit: min(opts.limit, map_size(map))}
|
||||
map = :maps.to_list(map) ++ ["..."]
|
||||
|
||||
open = color("#" <> name <> "<", :map, opts)
|
||||
sep = color(",", :map, opts)
|
||||
close = color(">", :map, opts)
|
||||
|
||||
fun = fn
|
||||
%{field: field}, opts -> Inspect.List.keyword({field, Map.get(map, field)}, opts)
|
||||
:..., _opts -> "..."
|
||||
end
|
||||
|
||||
container_doc(open, infos ++ [:...], close, opts, fun, separator: sep, break: :strict)
|
||||
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,144 +25,89 @@ 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.
|
||||
|
||||
It supports some pre-defined keys:
|
||||
- `:sort_maps` (since v1.15.0) - if set to `true`, sorts key-value pairs in maps.
|
||||
This can be helpful to make map inspection deterministic for testing,
|
||||
especially since key order is random since OTP 26.
|
||||
|
||||
* `:inspect_fun` (since v1.9.0) - a function to build algebra documents.
|
||||
Defaults to `Inspect.Opts.default_inspect_fun/0`.
|
||||
|
||||
* `: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. Defaults to `true`.
|
||||
|
||||
* `:structs` - when `false`, structs are not formatted by the inspect
|
||||
protocol, they are instead printed as maps. Defaults to `true`.
|
||||
implementations.
|
||||
|
||||
* `: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`.
|
||||
A default list of colors can be retrieved from `IO.ANSI.syntax_colors/0`.
|
||||
|
||||
* `: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,
|
||||
structs: boolean,
|
||||
binaries: :infer | :as_binaries | :as_strings,
|
||||
charlists: :infer | :as_lists | :as_charlists,
|
||||
custom_options: keyword,
|
||||
inspect_fun: (any, t -> Inspect.Algebra.t()),
|
||||
limit: non_neg_integer | :infinity,
|
||||
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,
|
||||
printable_limit: non_neg_integer | :infinity,
|
||||
safe: boolean,
|
||||
structs: boolean,
|
||||
syntax_colors: [{color_key, IO.ANSI.ansidata()}],
|
||||
width: non_neg_integer | :infinity
|
||||
inspect_fun: (any, t -> Inspect.Algebra.t()),
|
||||
custom_options: keyword
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds an `Inspect.Opts` struct.
|
||||
defmodule Inspect.Error do
|
||||
@moduledoc """
|
||||
Raised when a struct cannot be inspected.
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec new(keyword()) :: t
|
||||
def new(opts) do
|
||||
struct(%Inspect.Opts{inspect_fun: default_inspect_fun()}, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the default inspect function.
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec default_inspect_fun() :: (term, t -> Inspect.Algebra.t())
|
||||
def default_inspect_fun do
|
||||
:persistent_term.get({__MODULE__, :inspect_fun}, &Inspect.inspect/2)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sets the default inspect function.
|
||||
|
||||
Set this option with care as it will change how all values
|
||||
in the system are inspected. The main use of this functionality
|
||||
is to provide an entry point to filter inspected values,
|
||||
in order for entities to comply with rules and legislations
|
||||
on data security and data privacy.
|
||||
|
||||
It is **extremely discouraged** for libraries to set their own
|
||||
function as this must be controlled by applications. Libraries
|
||||
should instead define their own structs with custom inspect
|
||||
implementations. If a library must change the default inspect
|
||||
function, then it is best to define to ask users of your library
|
||||
to explicitly call `default_inspect_fun/1` with your function of
|
||||
choice.
|
||||
|
||||
The default is `Inspect.inspect/2`.
|
||||
|
||||
## Examples
|
||||
|
||||
previous_fun = Inspect.Opts.default_inspect_fun()
|
||||
|
||||
Inspect.Opts.default_inspect_fun(fn
|
||||
%{address: _} = map, opts ->
|
||||
previous_fun.(%{map | address: "[REDACTED]"}, opts)
|
||||
|
||||
value, opts ->
|
||||
previous_fun.(value, opts)
|
||||
end)
|
||||
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec default_inspect_fun((term, t -> Inspect.Algebra.t())) :: :ok
|
||||
def default_inspect_fun(fun) when is_function(fun, 2) do
|
||||
:persistent_term.put({__MODULE__, :inspect_fun}, fun)
|
||||
end
|
||||
defexception [:message]
|
||||
end
|
||||
|
||||
defmodule Inspect.Algebra do
|
||||
@@ -203,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")
|
||||
@@ -248,29 +191,23 @@ 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_limit
|
||||
| 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
|
||||
quote do: {:doc_string, unquote(string), unquote(length)}
|
||||
end
|
||||
|
||||
@typep doc_limit :: {:doc_limit, t, pos_integer | :infinity}
|
||||
defmacrop doc_limit(doc, limit) do
|
||||
quote do: {:doc_limit, unquote(doc), unquote(limit)}
|
||||
end
|
||||
|
||||
@typep doc_cons :: {:doc_cons, t, t}
|
||||
defmacrop doc_cons(left, right) do
|
||||
quote do: {:doc_cons, unquote(left), unquote(right)}
|
||||
@@ -312,25 +249,21 @@ defmodule Inspect.Algebra do
|
||||
end
|
||||
|
||||
@docs [
|
||||
:doc_break,
|
||||
:doc_collapse,
|
||||
:doc_color,
|
||||
:doc_cons,
|
||||
:doc_fits,
|
||||
:doc_force,
|
||||
:doc_group,
|
||||
:doc_nest,
|
||||
:doc_string,
|
||||
:doc_limit
|
||||
:doc_cons,
|
||||
:doc_nest,
|
||||
: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 """
|
||||
@@ -358,28 +291,19 @@ defmodule Inspect.Algebra do
|
||||
try do
|
||||
Process.put(:inspect_trap, true)
|
||||
|
||||
inspected_struct =
|
||||
struct
|
||||
|> Inspect.Map.inspect(%{
|
||||
opts
|
||||
| syntax_colors: [],
|
||||
inspect_fun: Inspect.Opts.default_inspect_fun()
|
||||
})
|
||||
|> format(opts.width)
|
||||
|> IO.iodata_to_binary()
|
||||
res = Inspect.Map.inspect(struct, %{opts | syntax_colors: []})
|
||||
res = IO.iodata_to_binary(format(res, :infinity))
|
||||
|
||||
inspect_error =
|
||||
Inspect.Error.exception(
|
||||
exception: caught_exception,
|
||||
stacktrace: __STACKTRACE__,
|
||||
inspected_struct: inspected_struct
|
||||
)
|
||||
message =
|
||||
"got #{inspect(caught_exception.__struct__)} with message " <>
|
||||
"#{inspect(Exception.message(caught_exception))} while inspecting #{res}"
|
||||
|
||||
exception = Inspect.Error.exception(message: message)
|
||||
|
||||
if opts.safe do
|
||||
opts = %{opts | inspect_fun: Inspect.Opts.default_inspect_fun()}
|
||||
Inspect.inspect(inspect_error, opts)
|
||||
Inspect.inspect(exception, opts)
|
||||
else
|
||||
reraise(inspect_error, __STACKTRACE__)
|
||||
reraise(exception, __STACKTRACE__)
|
||||
end
|
||||
after
|
||||
Process.delete(:inspect_trap)
|
||||
@@ -471,15 +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
|
||||
new_limit = decrement(limit)
|
||||
doc = fun.(term, %{opts | limit: new_limit})
|
||||
limit = if doc == :doc_nil, do: limit, else: new_limit
|
||||
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})
|
||||
@@ -587,10 +509,6 @@ defmodule Inspect.Algebra do
|
||||
doc_cons(doc1, doc2)
|
||||
end
|
||||
|
||||
def no_limit(doc) do
|
||||
doc_limit(doc, :infinity)
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Concatenates a list of documents returning a new document.
|
||||
|
||||
@@ -610,7 +528,7 @@ defmodule Inspect.Algebra do
|
||||
Colors a document if the `color_key` has a color in the options.
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec color(t, Inspect.Opts.color_key(), Inspect.Opts.t()) :: t
|
||||
@spec color(t, Inspect.Opts.color_key(), Inspect.Opts.t()) :: doc_color
|
||||
def color(doc, color_key, %Inspect.Opts{syntax_colors: syntax_colors}) when is_doc(doc) do
|
||||
if precolor = Keyword.get(syntax_colors, color_key) do
|
||||
postcolor = Keyword.get(syntax_colors, :reset, :reset)
|
||||
@@ -640,7 +558,7 @@ defmodule Inspect.Algebra do
|
||||
["hello", "\n ", "world"]
|
||||
|
||||
"""
|
||||
@spec nest(t, non_neg_integer | :cursor | :reset, :always | :break) :: doc_nest | t
|
||||
@spec nest(t, non_neg_integer | :cursor | :reset, :always | :break) :: doc_nest
|
||||
def nest(doc, level, mode \\ :always)
|
||||
|
||||
def nest(doc, :cursor, mode) when is_doc(doc) and mode in [:always, :break] do
|
||||
@@ -675,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")
|
||||
@@ -964,28 +882,23 @@ 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
|
||||
|
||||
# Type representing the document mode to be rendered:
|
||||
# Type representing the document mode to be rendered
|
||||
#
|
||||
# * flat - represents a document with breaks as flats (a break may fit, as it may break)
|
||||
# * break - represents a document with breaks as breaks (a break always fits, since it breaks)
|
||||
#
|
||||
# The following modes are exclusive to fitting:
|
||||
# The following modes are exclusive to fitting
|
||||
#
|
||||
# * flat_no_break - represents a document with breaks as flat not allowed to enter in break mode
|
||||
# * break_no_flat - represents a document with breaks as breaks not allowed to enter in flat mode
|
||||
#
|
||||
@typep mode :: :flat | :flat_no_break | :break | :break_no_flat
|
||||
|
||||
@spec fits?(
|
||||
width :: non_neg_integer() | :infinity,
|
||||
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} | [])
|
||||
|
||||
@@ -1046,17 +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}])
|
||||
|
||||
defp fits?(w, k, b?, [{i, m, doc_limit(x, :infinity)} | t]) when w != :infinity,
|
||||
do: fits?(:infinity, k, b?, [{i, :flat, x}, {i, m, doc_limit(empty(), w)} | t])
|
||||
|
||||
defp fits?(_w, k, b?, [{i, m, doc_limit(x, w)} | t]),
|
||||
do: fits?(w, k, b?, [{i, m, x} | 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)]
|
||||
@@ -1110,15 +1013,6 @@ defmodule Inspect.Algebra do
|
||||
end
|
||||
end
|
||||
|
||||
# Limit is set to infinity and then reverts
|
||||
defp format(w, k, [{i, m, doc_limit(x, :infinity)} | t]) when w != :infinity do
|
||||
format(:infinity, k, [{i, :flat, x}, {i, m, doc_limit(empty(), w)} | t])
|
||||
end
|
||||
|
||||
defp format(_w, k, [{i, m, doc_limit(x, w)} | t]) do
|
||||
format(w, k, [{i, m, x} | t])
|
||||
end
|
||||
|
||||
defp collapse(["\n" <> _ | t], max, count, i) do
|
||||
collapse(t, max, count + 1, i)
|
||||
end
|
||||
|
||||
+55
-120
@@ -4,11 +4,11 @@ defmodule Integer do
|
||||
|
||||
Some functions that work on integers are found in `Kernel`:
|
||||
|
||||
* `Kernel.abs/1`
|
||||
* `Kernel.div/2`
|
||||
* `Kernel.max/2`
|
||||
* `Kernel.min/2`
|
||||
* `Kernel.rem/2`
|
||||
* `abs/1`
|
||||
* `div/2`
|
||||
* `max/2`
|
||||
* `min/2`
|
||||
* `rem/2`
|
||||
|
||||
"""
|
||||
|
||||
@@ -64,53 +64,10 @@ defmodule Integer do
|
||||
"""
|
||||
defguard is_even(integer) when is_integer(integer) and (integer &&& 1) == 0
|
||||
|
||||
@doc """
|
||||
Computes `base` raised to power of `exponent`.
|
||||
|
||||
Both `base` and `exponent` must be integers.
|
||||
The exponent must be zero or positive.
|
||||
|
||||
See `Float.pow/2` for exponentiation of negative
|
||||
exponents as well as floats.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Integer.pow(2, 0)
|
||||
1
|
||||
iex> Integer.pow(2, 1)
|
||||
2
|
||||
iex> Integer.pow(2, 10)
|
||||
1024
|
||||
iex> Integer.pow(2, 11)
|
||||
2048
|
||||
iex> Integer.pow(2, 64)
|
||||
0x10000000000000000
|
||||
|
||||
iex> Integer.pow(3, 4)
|
||||
81
|
||||
iex> Integer.pow(4, 3)
|
||||
64
|
||||
|
||||
iex> Integer.pow(-2, 3)
|
||||
-8
|
||||
iex> Integer.pow(-2, 4)
|
||||
16
|
||||
|
||||
iex> Integer.pow(2, -2)
|
||||
** (ArithmeticError) bad argument in arithmetic expression
|
||||
|
||||
"""
|
||||
@doc since: "1.12.0"
|
||||
@spec pow(integer, non_neg_integer) :: integer
|
||||
def pow(base, exponent) when is_integer(base) and is_integer(exponent) do
|
||||
if exponent < 0, do: :erlang.error(:badarith, [base, exponent])
|
||||
base ** exponent
|
||||
end
|
||||
|
||||
@doc """
|
||||
Computes the modulo remainder of an integer division.
|
||||
|
||||
This function performs a [floored division](`floor_div/2`), which means that
|
||||
`Integer.mod/2` uses floored division, which means that
|
||||
the result will always have the sign of the `divisor`.
|
||||
|
||||
Raises an `ArithmeticError` exception if one of the arguments is not an
|
||||
@@ -142,8 +99,8 @@ defmodule Integer do
|
||||
Raises an `ArithmeticError` exception if one of the arguments is not an
|
||||
integer, or when the `divisor` is `0`.
|
||||
|
||||
This function performs a *floored* integer division, which means that
|
||||
the result will always be rounded towards negative infinity.
|
||||
`Integer.floor_div/2` performs *floored* integer division. This means that
|
||||
the result is always rounded towards negative infinity.
|
||||
|
||||
If you want to perform truncated integer division (rounding towards zero),
|
||||
use `Kernel.div/2` instead.
|
||||
@@ -269,14 +226,14 @@ defmodule Integer do
|
||||
** (ArgumentError) invalid base 38
|
||||
|
||||
"""
|
||||
@spec parse(binary, 2..36) :: {integer, remainder_of_binary :: binary} | :error
|
||||
@spec parse(binary, 2..36) :: {integer, binary} | :error
|
||||
def parse(binary, base \\ 10)
|
||||
|
||||
def parse(_binary, base) when base not in 2..36 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
|
||||
@@ -287,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
|
||||
|
||||
@@ -304,20 +261,20 @@ 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.
|
||||
# Please reapply commit 2622fd6b0aa419a983a899a1fbdb5deefba3d85d.
|
||||
@doc """
|
||||
Returns a binary which corresponds to the text representation
|
||||
of `integer` in the given `base`.
|
||||
|
||||
`base` can be an integer between 2 and 36. If no `base` is given,
|
||||
it defaults to `10`.
|
||||
of `integer`.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
@@ -335,6 +292,22 @@ defmodule Integer do
|
||||
iex> Integer.to_string(0123)
|
||||
"123"
|
||||
|
||||
"""
|
||||
@spec to_string(integer) :: String.t()
|
||||
def to_string(integer) do
|
||||
:erlang.integer_to_binary(integer)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a binary which corresponds to the text representation
|
||||
of `integer` in the given `base`.
|
||||
|
||||
`base` can be an integer between 2 and 36.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Integer.to_string(100, 16)
|
||||
"64"
|
||||
|
||||
@@ -346,16 +319,15 @@ defmodule Integer do
|
||||
|
||||
"""
|
||||
@spec to_string(integer, 2..36) :: String.t()
|
||||
def to_string(integer, base \\ 10) do
|
||||
def to_string(integer, base) do
|
||||
:erlang.integer_to_binary(integer, base)
|
||||
end
|
||||
|
||||
# TODO: Remove Integer.to_charlist/1 once the minimum supported version is
|
||||
# Erlang/OTP 22, since it is covered by the now BIF Integer.to_charlist/2.
|
||||
# Please reapply commit 2622fd6b0aa419a983a899a1fbdb5deefba3d85d.
|
||||
@doc """
|
||||
Returns a charlist which corresponds to the text representation
|
||||
of `integer` in the given `base`.
|
||||
|
||||
`base` can be an integer between 2 and 36. If no `base` is given,
|
||||
it defaults to `10`.
|
||||
Returns a charlist which corresponds to the text representation of the given `integer`.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
@@ -373,6 +345,21 @@ defmodule Integer do
|
||||
iex> Integer.to_charlist(0123)
|
||||
'123'
|
||||
|
||||
"""
|
||||
@spec to_charlist(integer) :: charlist
|
||||
def to_charlist(integer) do
|
||||
:erlang.integer_to_list(integer)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a charlist which corresponds to the text representation of `integer` in the given `base`.
|
||||
|
||||
`base` can be an integer between 2 and 36.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Integer.to_charlist(100, 16)
|
||||
'64'
|
||||
|
||||
@@ -384,7 +371,7 @@ defmodule Integer do
|
||||
|
||||
"""
|
||||
@spec to_charlist(integer, 2..36) :: charlist
|
||||
def to_charlist(integer, base \\ 10) do
|
||||
def to_charlist(integer, base) do
|
||||
:erlang.integer_to_list(integer, base)
|
||||
end
|
||||
|
||||
@@ -427,58 +414,6 @@ defmodule Integer do
|
||||
defp gcd_positive(integer1, 0), do: integer1
|
||||
defp gcd_positive(integer1, integer2), do: gcd_positive(integer2, rem(integer1, integer2))
|
||||
|
||||
@doc """
|
||||
Returns the extended greatest common divisor of the two given integers.
|
||||
|
||||
This function uses the extended Euclidean algorithm to return a three-element tuple with the `gcd`
|
||||
and the coefficients `m` and `n` of Bézout's identity such that:
|
||||
|
||||
gcd(a, b) = m*a + n*b
|
||||
|
||||
By convention, `extended_gcd(0, 0)` returns `{0, 0, 0}`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Integer.extended_gcd(240, 46)
|
||||
{2, -9, 47}
|
||||
iex> Integer.extended_gcd(46, 240)
|
||||
{2, 47, -9}
|
||||
iex> Integer.extended_gcd(-46, 240)
|
||||
{2, -47, -9}
|
||||
iex> Integer.extended_gcd(-46, -240)
|
||||
{2, -47, 9}
|
||||
|
||||
iex> Integer.extended_gcd(14, 21)
|
||||
{7, -1, 1}
|
||||
|
||||
iex> Integer.extended_gcd(10, 0)
|
||||
{10, 1, 0}
|
||||
iex> Integer.extended_gcd(0, 10)
|
||||
{10, 0, 1}
|
||||
iex> Integer.extended_gcd(0, 0)
|
||||
{0, 0, 0}
|
||||
|
||||
"""
|
||||
@doc since: "1.12.0"
|
||||
@spec extended_gcd(integer, integer) :: {non_neg_integer, integer, integer}
|
||||
def extended_gcd(0, 0), do: {0, 0, 0}
|
||||
def extended_gcd(0, b), do: {b, 0, 1}
|
||||
def extended_gcd(a, 0), do: {a, 1, 0}
|
||||
|
||||
def extended_gcd(integer1, integer2) when is_integer(integer1) and is_integer(integer2) do
|
||||
extended_gcd(integer2, integer1, 0, 1, 1, 0)
|
||||
end
|
||||
|
||||
defp extended_gcd(r1, r0, s1, s0, t1, t0) do
|
||||
div = div(r0, r1)
|
||||
|
||||
case r0 - div * r1 do
|
||||
0 when r1 > 0 -> {r1, s1, t1}
|
||||
0 when r1 < 0 -> {-r1, -s1, -t1}
|
||||
r2 -> extended_gcd(r2, r1, s0 - div * s1, s1, t0 - div * t1, t1)
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use Integer.to_charlist/1 instead"
|
||||
def to_char_list(integer), do: Integer.to_charlist(integer)
|
||||
|
||||
+54
-167
@@ -34,7 +34,7 @@ defmodule IO do
|
||||
IO data is a data type that can be used as a more efficient alternative to binaries
|
||||
in certain situations.
|
||||
|
||||
A term of type **IO data** is a binary or a list containing bytes (integers within the `0..255` range)
|
||||
A term of type **IO data** is a binary or a list containing bytes (integers in `0..255`)
|
||||
or nested IO data. The type is recursive. Let's see an example of one of
|
||||
the possible IO data representing the binary `"hello"`:
|
||||
|
||||
@@ -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,18 +98,18 @@ 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 within the `0..255` range, while Unicode code points
|
||||
(`t:char/0`) are integers within the `0..0x10FFFF` range. The `IO` module provides
|
||||
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:
|
||||
|
||||
IO.iodata_to_binary(["The symbol for pi is: ", ?π])
|
||||
#=> ** (ArgumentError) argument error
|
||||
iex> IO.iodata_to_binary(["The symbol for pi is: ", ?π])
|
||||
** (ArgumentError) argument error
|
||||
|
||||
If we use chardata instead, it will work as expected:
|
||||
|
||||
@@ -122,14 +122,14 @@ defmodule IO do
|
||||
@type nodata :: {:error, term} | :eof
|
||||
@type chardata :: String.t() | maybe_improper_list(char | chardata, String.t() | [])
|
||||
|
||||
defguardp is_device(term) when is_atom(term) or is_pid(term)
|
||||
defguardp is_iodata(data) when is_list(data) or is_binary(data)
|
||||
|
||||
@doc """
|
||||
Reads from the IO `device`.
|
||||
|
||||
The `device` is iterated by the given number of characters, line by line if
|
||||
`:line` is given, or until `:eof`.
|
||||
The `device` is iterated by the given number of characters or line by line if
|
||||
`:line` is given.
|
||||
Alternatively, if `:all` is given, then whole `device` is returned.
|
||||
|
||||
It returns:
|
||||
|
||||
@@ -141,24 +141,14 @@ defmodule IO do
|
||||
for instance, `{:error, :estale}` if reading from an
|
||||
NFS volume
|
||||
|
||||
If `:all` is given, `:eof` is never returned, but an
|
||||
empty string in case the device has reached EOF.
|
||||
"""
|
||||
@spec read(device, :eof | :line | non_neg_integer) :: chardata | nodata
|
||||
@spec read(device, :all | :line | non_neg_integer) :: chardata | nodata
|
||||
def read(device \\ :stdio, line_or_chars)
|
||||
|
||||
# TODO: Deprecate me on v1.17
|
||||
def read(device, :all) do
|
||||
with :eof <- read(device, :eof) do
|
||||
with [_ | _] = opts <- :io.getopts(device),
|
||||
false <- Keyword.get(opts, :binary, true) do
|
||||
''
|
||||
else
|
||||
_ -> ""
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def read(device, :eof) do
|
||||
getn(device, '', :eof)
|
||||
do_read_all(map_dev(device), "")
|
||||
end
|
||||
|
||||
def read(device, :line) do
|
||||
@@ -169,20 +159,20 @@ defmodule IO do
|
||||
:io.get_chars(map_dev(device), '', count)
|
||||
end
|
||||
|
||||
defp do_read_all(mapped_dev, acc) do
|
||||
case :io.get_line(mapped_dev, "") do
|
||||
line when is_binary(line) -> do_read_all(mapped_dev, acc <> line)
|
||||
:eof -> acc
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads from the IO `device`. The operation is Unicode unsafe.
|
||||
|
||||
The `device` is iterated as specified by the `line_or_chars` argument:
|
||||
|
||||
* if `line_or_chars` is an integer, it represents a number of bytes. The device is
|
||||
iterated by that number of bytes.
|
||||
|
||||
* if `line_or_chars` is `:line`, the device is iterated line by line.
|
||||
|
||||
* if `line_or_chars` is `:eof`, the device is iterated until `:eof`. `line_or_chars`
|
||||
can only be `:eof` since Elixir 1.13.0. `:eof` replaces the deprecated `:all`,
|
||||
with the difference that `:all` returns `""` on end of file, while `:eof` returns
|
||||
`:eof` itself.
|
||||
The `device` is iterated by the given number of bytes or line by line if
|
||||
`:line` is given.
|
||||
Alternatively, if `:all` is given, then whole `device` is returned.
|
||||
|
||||
It returns:
|
||||
|
||||
@@ -194,19 +184,17 @@ defmodule IO do
|
||||
for instance, `{:error, :estale}` if reading from an
|
||||
NFS volume
|
||||
|
||||
If `:all` is given, `:eof` is never returned, but an
|
||||
empty string in case the device has reached EOF.
|
||||
|
||||
Note: do not use this function on IO devices in Unicode mode
|
||||
as it will return the wrong result.
|
||||
"""
|
||||
@spec binread(device, :eof | :line | non_neg_integer) :: iodata | nodata
|
||||
@spec binread(device, :all | :line | non_neg_integer) :: iodata | nodata
|
||||
def binread(device \\ :stdio, line_or_chars)
|
||||
|
||||
# TODO: Deprecate me on v1.17
|
||||
def binread(device, :all) do
|
||||
with :eof <- binread(device, :eof), do: ""
|
||||
end
|
||||
|
||||
def binread(device, :eof) do
|
||||
binread_eof(map_dev(device), "")
|
||||
do_binread_all(map_dev(device), "")
|
||||
end
|
||||
|
||||
def binread(device, :line) do
|
||||
@@ -224,10 +212,10 @@ defmodule IO do
|
||||
end
|
||||
|
||||
@read_all_size 4096
|
||||
defp binread_eof(mapped_dev, acc) do
|
||||
defp do_binread_all(mapped_dev, acc) do
|
||||
case :file.read(mapped_dev, @read_all_size) do
|
||||
{:ok, data} -> binread_eof(mapped_dev, acc <> data)
|
||||
:eof -> if acc == "", do: :eof, else: acc
|
||||
{:ok, data} -> do_binread_all(mapped_dev, acc <> data)
|
||||
:eof -> acc
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
@@ -290,29 +278,19 @@ defmodule IO do
|
||||
|
||||
"""
|
||||
@spec puts(device, chardata | String.Chars.t()) :: :ok
|
||||
def puts(device \\ :stdio, item) when is_device(device) do
|
||||
def puts(device \\ :stdio, item) do
|
||||
:io.put_chars(map_dev(device), [to_chardata(item), ?\n])
|
||||
end
|
||||
|
||||
@doc """
|
||||
Writes a `message` to stderr, along with the given `stacktrace_info`.
|
||||
|
||||
The `stacktrace_info` must be one of:
|
||||
|
||||
* a `__STACKTRACE__`, where all entries in the stacktrace will be
|
||||
included in the error message
|
||||
|
||||
* a `Macro.Env` structure (since v1.14.0), where a single stacktrace
|
||||
entry from the compilation environment will be used
|
||||
|
||||
* a keyword list with at least the `:file` option representing
|
||||
a single stacktrace entry (since v1.14.0). The `:line`, `:module`,
|
||||
`:function` options are also supported
|
||||
Writes a `message` to stderr, along with the given `stacktrace`.
|
||||
|
||||
This function also notifies the compiler a warning was printed
|
||||
(in case --warnings-as-errors was enabled). It returns `:ok`
|
||||
if it succeeds.
|
||||
|
||||
An empty list can be passed to avoid stacktrace printing.
|
||||
|
||||
## Examples
|
||||
|
||||
stacktrace = [{MyApp, :main, 1, [file: 'my_app.ex', line: 4]}]
|
||||
@@ -321,34 +299,10 @@ defmodule IO do
|
||||
#=> my_app.ex:4: MyApp.main/1
|
||||
|
||||
"""
|
||||
@spec warn(chardata | String.Chars.t(), Exception.stacktrace() | keyword() | Macro.Env.t()) ::
|
||||
:ok
|
||||
def warn(message, stacktrace_info)
|
||||
|
||||
@spec warn(chardata | String.Chars.t(), Exception.stacktrace()) :: :ok
|
||||
def warn(message, []) do
|
||||
message = [to_chardata(message), ?\n]
|
||||
:elixir_errors.log_and_print_warning(0, nil, message, message)
|
||||
end
|
||||
|
||||
def warn(message, %Macro.Env{} = env) do
|
||||
warn(message, Macro.Env.stacktrace(env))
|
||||
end
|
||||
|
||||
def warn(message, [{_, _} | _] = keyword) do
|
||||
if file = keyword[:file] do
|
||||
warn(
|
||||
message,
|
||||
%{
|
||||
__ENV__
|
||||
| module: keyword[:module],
|
||||
function: keyword[:function],
|
||||
line: keyword[:line],
|
||||
file: file
|
||||
}
|
||||
)
|
||||
else
|
||||
warn(message, [])
|
||||
end
|
||||
:elixir_errors.io_warn(nil, nil, message, message)
|
||||
end
|
||||
|
||||
def warn(message, [{_, _, _, opts} | _] = stacktrace) do
|
||||
@@ -357,36 +311,19 @@ defmodule IO do
|
||||
line = opts[:line]
|
||||
file = opts[:file]
|
||||
|
||||
:elixir_errors.log_and_print_warning(
|
||||
line || 0,
|
||||
:elixir_errors.io_warn(
|
||||
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")
|
||||
@@ -459,9 +396,9 @@ defmodule IO do
|
||||
See `inspect/2` for a full list of options.
|
||||
"""
|
||||
@spec inspect(device, item, keyword) :: item when item: var
|
||||
def inspect(device, item, opts) when is_device(device) and is_list(opts) do
|
||||
def inspect(device, item, opts) when is_list(opts) do
|
||||
label = if label = opts[:label], do: [to_chardata(label), ": "], else: []
|
||||
opts = Inspect.Opts.new(opts)
|
||||
opts = struct(Inspect.Opts, opts)
|
||||
doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(item, opts))
|
||||
chardata = Inspect.Algebra.format(doc, opts.width)
|
||||
puts(device, [label, chardata])
|
||||
@@ -476,17 +413,11 @@ defmodule IO do
|
||||
Otherwise, `count` is the number of raw bytes to be retrieved.
|
||||
|
||||
See `IO.getn/3` for a description of return values.
|
||||
"""
|
||||
@spec getn(
|
||||
device | chardata | String.Chars.t(),
|
||||
pos_integer | :eof | chardata | String.Chars.t()
|
||||
) ::
|
||||
chardata | nodata
|
||||
def getn(prompt, count \\ 1)
|
||||
|
||||
def getn(prompt, :eof) do
|
||||
getn(:stdio, prompt, :eof)
|
||||
end
|
||||
"""
|
||||
@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
|
||||
getn(:stdio, prompt, count)
|
||||
@@ -514,27 +445,11 @@ defmodule IO do
|
||||
NFS volume
|
||||
|
||||
"""
|
||||
@spec getn(device, chardata | String.Chars.t(), pos_integer | :eof) :: chardata | nodata
|
||||
def getn(device, prompt, :eof) do
|
||||
getn_eof(map_dev(device), to_chardata(prompt), [])
|
||||
end
|
||||
|
||||
@spec getn(device, chardata | String.Chars.t(), pos_integer) :: chardata | nodata
|
||||
def getn(device, prompt, count) when is_integer(count) and count > 0 do
|
||||
:io.get_chars(map_dev(device), to_chardata(prompt), count)
|
||||
end
|
||||
|
||||
defp getn_eof(device, prompt, acc) do
|
||||
case :io.get_line(device, prompt) do
|
||||
line when is_binary(line) or is_list(line) -> getn_eof(device, '', [line | acc])
|
||||
:eof -> wrap_eof(:lists.reverse(acc))
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
|
||||
defp wrap_eof([h | _] = acc) when is_binary(h), do: IO.iodata_to_binary(acc)
|
||||
defp wrap_eof([h | _] = acc) when is_list(h), do: :lists.flatten(acc)
|
||||
defp wrap_eof([]), do: :eof
|
||||
|
||||
@doc ~S"""
|
||||
Reads a line from the IO `device`.
|
||||
|
||||
@@ -561,17 +476,6 @@ defmodule IO do
|
||||
:io.get_line(map_dev(device), to_chardata(prompt))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a line-based `IO.Stream` on `:stdio`.
|
||||
|
||||
This is equivalent to:
|
||||
|
||||
IO.stream(:stdio, :line)
|
||||
|
||||
"""
|
||||
@doc since: "1.12.0"
|
||||
def stream, do: stream(:stdio, :line)
|
||||
|
||||
@doc """
|
||||
Converts the IO `device` into an `IO.Stream`.
|
||||
|
||||
@@ -588,9 +492,6 @@ defmodule IO do
|
||||
Note that an IO stream has side effects and every time
|
||||
you go over the stream you may get different results.
|
||||
|
||||
`stream/0` has been introduced in Elixir v1.12.0,
|
||||
while `stream/2` has been available since v1.0.0.
|
||||
|
||||
## Examples
|
||||
|
||||
Here is an example on how we mimic an echo server
|
||||
@@ -600,23 +501,12 @@ defmodule IO do
|
||||
|
||||
"""
|
||||
@spec stream(device, :line | pos_integer) :: Enumerable.t()
|
||||
def stream(device \\ :stdio, line_or_codepoints)
|
||||
def stream(device, line_or_codepoints)
|
||||
when line_or_codepoints == :line
|
||||
when is_integer(line_or_codepoints) and line_or_codepoints > 0 do
|
||||
IO.Stream.__build__(map_dev(device), false, line_or_codepoints)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a raw, line-based `IO.Stream` on `:stdio`. The operation is Unicode unsafe.
|
||||
|
||||
This is equivalent to:
|
||||
|
||||
IO.binstream(:stdio, :line)
|
||||
|
||||
"""
|
||||
@doc since: "1.12.0"
|
||||
def binstream, do: binstream(:stdio, :line)
|
||||
|
||||
@doc """
|
||||
Converts the IO `device` into an `IO.Stream`. The operation is Unicode unsafe.
|
||||
|
||||
@@ -625,7 +515,8 @@ defmodule IO do
|
||||
and write.
|
||||
|
||||
The `device` is iterated by the given number of bytes or line by line if
|
||||
`:line` is given. This reads from the IO device as a raw binary.
|
||||
`:line` is given.
|
||||
This reads from the IO device as a raw binary.
|
||||
|
||||
Note that an IO stream has side effects and every time
|
||||
you go over the stream you may get different results.
|
||||
@@ -633,11 +524,9 @@ defmodule IO do
|
||||
Finally, do not use this function on IO devices in Unicode
|
||||
mode as it will return the wrong result.
|
||||
|
||||
`binstream/0` has been introduced in Elixir v1.12.0,
|
||||
while `binstream/2` has been available since v1.0.0.
|
||||
"""
|
||||
@spec binstream(device, :line | pos_integer) :: Enumerable.t()
|
||||
def binstream(device \\ :stdio, line_or_bytes)
|
||||
def binstream(device, line_or_bytes)
|
||||
when line_or_bytes == :line
|
||||
when is_integer(line_or_bytes) and line_or_bytes > 0 do
|
||||
IO.Stream.__build__(map_dev(device), true, line_or_bytes)
|
||||
@@ -665,8 +554,6 @@ defmodule IO do
|
||||
|
||||
"""
|
||||
@spec chardata_to_string(chardata) :: String.t()
|
||||
def chardata_to_string(chardata)
|
||||
|
||||
def chardata_to_string(string) when is_binary(string) do
|
||||
string
|
||||
end
|
||||
@@ -680,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
|
||||
|
||||
@@ -3,7 +3,6 @@ defmodule IO.ANSI.Sequence do
|
||||
|
||||
defmacro defsequence(name, code, terminator \\ "m") do
|
||||
quote bind_quoted: [name: name, code: code, terminator: terminator] do
|
||||
@spec unquote(name)() :: String.t()
|
||||
def unquote(name)() do
|
||||
"\e[#{unquote(code)}#{unquote(terminator)}"
|
||||
end
|
||||
@@ -22,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
|
||||
@@ -69,34 +43,6 @@ defmodule IO.ANSI do
|
||||
Application.get_env(:elixir, :ansi_enabled, false)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Syntax colors to be used by `Inspect`.
|
||||
|
||||
Those colors are used throughout Elixir's standard library,
|
||||
such as `dbg/2` and `IEx`.
|
||||
|
||||
The colors can be changed by setting the `:ansi_syntax_colors`
|
||||
in the `:elixir` application configuration. Configuration for
|
||||
most built-in data types are supported: `:atom`, `:binary`,
|
||||
`:boolean`, `:charlist`, `:list`, `:map`, `:nil`, `:number`,
|
||||
`:string`, and `:tuple`. The default is:
|
||||
|
||||
[
|
||||
atom: :cyan
|
||||
boolean: :magenta,
|
||||
charlist: :yellow,
|
||||
nil: :magenta,
|
||||
number: :yellow,
|
||||
string: :green
|
||||
]
|
||||
|
||||
"""
|
||||
@doc since: "1.14.0"
|
||||
@spec syntax_colors :: Keyword.t(ansidata)
|
||||
def syntax_colors do
|
||||
Application.fetch_env!(:elixir, :ansi_syntax_colors)
|
||||
end
|
||||
|
||||
@doc "Sets foreground color."
|
||||
@spec color(0..255) :: String.t()
|
||||
def color(code) when code in 0..255, do: "\e[38;5;#{code}m"
|
||||
@@ -271,7 +217,7 @@ defmodule IO.ANSI do
|
||||
performed. If you don't want this behaviour, use `format_fragment/2`.
|
||||
|
||||
An optional boolean parameter can be passed to enable or disable
|
||||
emitting actual ANSI codes. When `false`, no ANSI codes will be emitted.
|
||||
emitting actual ANSI codes. When `false`, no ANSI codes will emitted.
|
||||
By default checks if ANSI is enabled using the `enabled?/0` function.
|
||||
|
||||
## Examples
|
||||
@@ -280,9 +226,8 @@ defmodule IO.ANSI do
|
||||
[[[[[[], "Hello, "] | "\e[31m"] | "\e[1m"], "world!"] | "\e[0m"]
|
||||
|
||||
"""
|
||||
@spec format(ansidata, boolean) :: IO.chardata()
|
||||
def format(ansidata, emit? \\ enabled?()) when is_boolean(emit?) do
|
||||
do_format(ansidata, [], [], emit?, :maybe)
|
||||
def format(chardata, emit? \\ enabled?()) when is_boolean(emit?) do
|
||||
do_format(chardata, [], [], emit?, :maybe)
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
@@ -301,9 +246,8 @@ defmodule IO.ANSI do
|
||||
[[[[[[] | "\e[1m"], 87], 111], 114], 100]
|
||||
|
||||
"""
|
||||
@spec format_fragment(ansidata, boolean) :: IO.chardata()
|
||||
def format_fragment(ansidata, emit? \\ enabled?()) when is_boolean(emit?) do
|
||||
do_format(ansidata, [], [], emit?, false)
|
||||
def format_fragment(chardata, emit? \\ enabled?()) when is_boolean(emit?) do
|
||||
do_format(chardata, [], [], emit?, false)
|
||||
end
|
||||
|
||||
defp do_format([term | rest], rem, acc, emit?, append_reset) do
|
||||
|
||||
+77
-377
@@ -1,8 +1,6 @@
|
||||
defmodule IO.ANSI.Docs do
|
||||
@moduledoc false
|
||||
|
||||
@bullet_text_unicode "• "
|
||||
@bullet_text_ascii "* "
|
||||
@bullets [?*, ?-, ?+]
|
||||
@spaces [" ", "\n", "\t"]
|
||||
|
||||
@@ -16,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)
|
||||
@@ -34,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],
|
||||
@@ -48,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 """
|
||||
@@ -78,20 +69,18 @@ defmodule IO.ANSI.Docs do
|
||||
@metadata_filter [:deprecated, :guard, :since]
|
||||
|
||||
defp print_each_metadata(metadata, options) do
|
||||
metadata
|
||||
|> Enum.sort()
|
||||
|> Enum.reduce(false, fn
|
||||
Enum.reduce(metadata, false, fn
|
||||
{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
|
||||
@@ -99,214 +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({tag, _, entries}, indent, options) when tag in [:strong, :b] 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(options) | 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(options) | 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, :strong, :b, :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
|
||||
@@ -343,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)
|
||||
@@ -383,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(options), 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)
|
||||
@@ -457,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
|
||||
|
||||
@@ -503,7 +253,7 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
end
|
||||
|
||||
### Text
|
||||
## Text
|
||||
|
||||
defp write_text(text, indent, options) do
|
||||
case Enum.reverse(text) do
|
||||
@@ -517,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)
|
||||
@@ -575,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
|
||||
|
||||
@@ -607,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)
|
||||
|
||||
@@ -709,7 +450,7 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp table_line?(line) do
|
||||
line =~ ~r/[:\ -]\|[:\ -]/
|
||||
line =~ " | "
|
||||
end
|
||||
|
||||
## Helpers
|
||||
@@ -726,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
|
||||
@@ -804,14 +532,14 @@ defmodule IO.ANSI.Docs do
|
||||
Regex.replace(~r{\[([^\]]*?)\]\((.*?)\)}, text, "\\1 (\\2)")
|
||||
end
|
||||
|
||||
# We have four entries: **, __, *, _ and `.
|
||||
# We have four entries: **, *, _ and `.
|
||||
#
|
||||
# The first four behave the same while the last one is simpler
|
||||
# The first three behave the same while the last one is simpler
|
||||
# when it comes to delimiters as it ignores spaces and escape
|
||||
# characters. But, since the first two has two characters,
|
||||
# we need to handle 3 cases:
|
||||
# characters. But, since the first has two characters, we need to
|
||||
# handle 3 cases:
|
||||
#
|
||||
# 1. __ and **
|
||||
# 1. **
|
||||
# 2. _ and *
|
||||
# 3. `
|
||||
#
|
||||
@@ -823,10 +551,10 @@ defmodule IO.ANSI.Docs do
|
||||
@delimiters [?\s, ?', ?", ?!, ?@, ?#, ?$, ?%, ?^, ?&] ++
|
||||
[?-, ?+, ?(, ?), ?[, ?], ?{, ?}, ?<, ?>, ?.]
|
||||
|
||||
### Inline start
|
||||
# Inline start
|
||||
|
||||
defp handle_inline(<<mark, mark, rest::binary>>, options) when mark in @single do
|
||||
handle_inline(rest, [mark | mark], [<<mark, mark>>], [], options)
|
||||
defp handle_inline(<<?*, ?*, rest::binary>>, options) do
|
||||
handle_inline(rest, ?d, ["**"], [], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<mark, rest::binary>>, options) when mark in @single do
|
||||
@@ -837,12 +565,11 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(rest, nil, [], [], options)
|
||||
end
|
||||
|
||||
### Inline delimiters
|
||||
# Inline delimiters
|
||||
|
||||
defp handle_inline(<<delimiter, mark, mark, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and delimiter in @delimiters and mark in @single do
|
||||
acc = [delimiter, Enum.reverse(buffer) | acc]
|
||||
handle_inline(rest, [mark | mark], [<<mark, mark>>], acc, options)
|
||||
defp handle_inline(<<delimiter, ?*, ?*, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and delimiter in @delimiters do
|
||||
handle_inline(rest, ?d, ["**"], [delimiter, Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<delimiter, mark, rest::binary>>, nil, buffer, acc, options)
|
||||
@@ -855,12 +582,11 @@ 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(<<?\\, ?\\, mark, mark, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and mark in @single do
|
||||
acc = [?\\, Enum.reverse(buffer) | acc]
|
||||
handle_inline(rest, [mark | mark], [<<mark, mark>>], acc, options)
|
||||
defp handle_inline(<<?\\, ?\\, ?*, ?*, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" do
|
||||
handle_inline(rest, ?d, ["**"], [?\\, Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<?\\, ?\\, mark, rest::binary>>, nil, buffer, acc, options)
|
||||
@@ -877,10 +603,10 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(rest, limit, [mark | buffer], acc, options)
|
||||
end
|
||||
|
||||
### Inline end
|
||||
# Inline end
|
||||
|
||||
defp handle_inline(<<mark, mark, delimiter, rest::binary>>, [mark | mark], buffer, acc, options)
|
||||
when delimiter in @delimiters and mark in @single do
|
||||
defp handle_inline(<<?*, ?*, delimiter, rest::binary>>, ?d, buffer, acc, options)
|
||||
when delimiter in @delimiters do
|
||||
inline_buffer = inline_buffer(buffer, options)
|
||||
handle_inline(<<delimiter, rest::binary>>, nil, [], [inline_buffer | acc], options)
|
||||
end
|
||||
@@ -891,8 +617,8 @@ defmodule IO.ANSI.Docs do
|
||||
handle_inline(<<delimiter, rest::binary>>, nil, [], [inline_buffer | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<mark, mark, rest::binary>>, [mark | mark], buffer, acc, options)
|
||||
when rest == "" and mark in @single do
|
||||
defp handle_inline(<<?*, ?*, rest::binary>>, ?d, buffer, acc, options)
|
||||
when rest == "" do
|
||||
handle_inline(<<>>, nil, [], [inline_buffer(buffer, options) | acc], options)
|
||||
end
|
||||
|
||||
@@ -905,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)
|
||||
@@ -916,49 +642,23 @@ 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
|
||||
case mark do
|
||||
"__" -> color(:doc_bold, colors)
|
||||
"**" -> color(:doc_bold, colors)
|
||||
"_" -> color(:doc_underline, colors)
|
||||
"*" -> color(:doc_underline, colors)
|
||||
"`" -> color(:doc_inline_code, colors)
|
||||
"_" -> color(:doc_underline, colors)
|
||||
"*" -> color(:doc_bold, colors)
|
||||
"**" -> color(:doc_bold, colors)
|
||||
end
|
||||
end
|
||||
|
||||
defp bullet_text(options) do
|
||||
if options[:enabled], do: @bullet_text_unicode, else: @bullet_text_ascii
|
||||
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
|
||||
|
||||
@@ -26,11 +26,7 @@ defmodule IO.Stream do
|
||||
|
||||
defstruct device: nil, raw: true, line_or_bytes: :line
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
device: IO.device(),
|
||||
raw: boolean(),
|
||||
line_or_bytes: :line | non_neg_integer()
|
||||
}
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@doc false
|
||||
def __build__(device, raw, line_or_bytes) do
|
||||
|
||||
+607
-1774
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,13 +10,9 @@ defmodule Kernel.CLI do
|
||||
errors: [],
|
||||
pa: [],
|
||||
pz: [],
|
||||
verbose_compile: false,
|
||||
profile: nil,
|
||||
pry: false
|
||||
verbose_compile: false
|
||||
}
|
||||
|
||||
@standalone_opts ["-h", "--help", "--short-version"]
|
||||
|
||||
@doc """
|
||||
This is the API invoked by Elixir boot process.
|
||||
"""
|
||||
@@ -29,10 +23,6 @@ defmodule Kernel.CLI do
|
||||
System.argv(argv)
|
||||
System.no_halt(config.no_halt)
|
||||
|
||||
if config.pry do
|
||||
Application.put_env(:elixir, :dbg_callback, {IEx.Pry, :dbg, []})
|
||||
end
|
||||
|
||||
fun = fn _ ->
|
||||
errors = process_commands(config)
|
||||
|
||||
@@ -95,7 +85,7 @@ defmodule Kernel.CLI do
|
||||
case blamed do
|
||||
%FunctionClauseError{} ->
|
||||
formatted = Exception.format_banner(kind, reason, stacktrace)
|
||||
padded_blame = pad(FunctionClauseError.blame(blamed, &inspect/1, &blame_match/1))
|
||||
padded_blame = pad(FunctionClauseError.blame(blamed, &inspect/1, &blame_match/2))
|
||||
[formatted, padded_blame]
|
||||
|
||||
_ ->
|
||||
@@ -109,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
|
||||
@@ -183,8 +173,9 @@ defmodule Kernel.CLI do
|
||||
IO.write(:stderr, format_error(kind, reason, stacktrace))
|
||||
end
|
||||
|
||||
defp blame_match(%{match?: true, node: node}), do: blame_ansi(:normal, "+", node)
|
||||
defp blame_match(%{match?: false, node: node}), do: blame_ansi(:red, "-", node)
|
||||
defp blame_match(%{match?: true, node: node}, _), do: blame_ansi(:normal, "+", node)
|
||||
defp blame_match(%{match?: false, node: node}, _), do: blame_ansi(:red, "-", node)
|
||||
defp blame_match(_, string), do: string
|
||||
|
||||
defp blame_ansi(color, no_ansi, node) do
|
||||
if IO.ANSI.enabled?() do
|
||||
@@ -201,9 +192,8 @@ defmodule Kernel.CLI do
|
||||
end
|
||||
|
||||
@elixir_internals [:elixir, :elixir_aliases, :elixir_expand, :elixir_compiler, :elixir_module] ++
|
||||
[:elixir_clauses, :elixir_lexical, :elixir_def, :elixir_map, :elixir_locals] ++
|
||||
[:elixir_erl, :elixir_erl_clauses, :elixir_erl_compiler, :elixir_erl_pass] ++
|
||||
[Kernel.ErrorHandler, Module.ParallelChecker]
|
||||
[:elixir_clauses, :elixir_lexical, :elixir_def, :elixir_map] ++
|
||||
[:elixir_erl, :elixir_erl_clauses, :elixir_erl_pass, Kernel.ErrorHandler]
|
||||
|
||||
defp prune_stacktrace([{mod, _, _, _} | t]) when mod in @elixir_internals do
|
||||
prune_stacktrace(t)
|
||||
@@ -223,16 +213,7 @@ defmodule Kernel.CLI do
|
||||
|
||||
# Parse shared options
|
||||
|
||||
defp halt_standalone(opt) do
|
||||
IO.puts(:stderr, "#{opt} : Standalone options can't be combined with other options")
|
||||
System.halt(1)
|
||||
end
|
||||
|
||||
defp parse_shared([opt | _], _config) when opt in @standalone_opts do
|
||||
halt_standalone(opt)
|
||||
end
|
||||
|
||||
defp parse_shared([opt | t], _config) when opt in ["-v", "--version"] do
|
||||
defp parse_shared([opt | _t], _config) when opt in ["-v", "--version"] do
|
||||
if function_exported?(IEx, :started?, 0) and IEx.started?() do
|
||||
IO.puts("IEx " <> System.build_info()[:build])
|
||||
else
|
||||
@@ -240,11 +221,7 @@ defmodule Kernel.CLI do
|
||||
IO.puts("Elixir " <> System.build_info()[:build])
|
||||
end
|
||||
|
||||
if t != [] do
|
||||
halt_standalone(opt)
|
||||
else
|
||||
System.halt(0)
|
||||
end
|
||||
System.halt(0)
|
||||
end
|
||||
|
||||
defp parse_shared(["-pa", h | t], config) do
|
||||
@@ -280,11 +257,6 @@ defmodule Kernel.CLI do
|
||||
parse_shared(t, %{config | commands: [{:rpc_eval, node, h} | config.commands]})
|
||||
end
|
||||
|
||||
defp parse_shared(["--rpc-eval" | _], config) do
|
||||
new_config = %{config | errors: ["--rpc-eval : wrong number of arguments" | config.errors]}
|
||||
{[], new_config}
|
||||
end
|
||||
|
||||
defp parse_shared(["-r", h | t], config) do
|
||||
parse_shared(t, %{config | commands: [{:require, h} | config.commands]})
|
||||
end
|
||||
@@ -324,7 +296,7 @@ defmodule Kernel.CLI do
|
||||
end
|
||||
|
||||
defp parse_argv(["+iex" | t], config) do
|
||||
parse_iex(t, %{config | pry: true})
|
||||
parse_iex(t, config)
|
||||
end
|
||||
|
||||
defp parse_argv(["-S", h | t], config) do
|
||||
@@ -382,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
|
||||
"-" <> _ ->
|
||||
@@ -409,16 +375,20 @@ defmodule Kernel.CLI do
|
||||
{config, t}
|
||||
end
|
||||
|
||||
# This clause is here so that Kernel.CLI does not
|
||||
# error out with "unknown option"
|
||||
defp parse_iex(["--dot-iex", _ | t], config) do
|
||||
parse_iex(t, config)
|
||||
end
|
||||
|
||||
defp parse_iex([opt, _ | t], config) when opt in ["--remsh"] do
|
||||
parse_iex(t, config)
|
||||
end
|
||||
|
||||
defp parse_iex(["-S", h | t], config) do
|
||||
{%{config | commands: [{:script, h} | config.commands]}, t}
|
||||
end
|
||||
|
||||
# These clauses are here so that Kernel.CLI does not error out with "unknown option"
|
||||
defp parse_iex(["--dot-iex", _ | t], config), do: parse_iex(t, config)
|
||||
defp parse_iex(["--remsh", _ | t], config), do: parse_iex(t, config)
|
||||
|
||||
defp parse_iex(["--no-pry" | t], config), do: parse_iex(t, %{config | pry: false})
|
||||
|
||||
defp parse_iex([h | t] = list, config) do
|
||||
case h do
|
||||
"-" <> _ -> shared_option?(list, config, &parse_iex(&1, &2))
|
||||
@@ -517,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})
|
||||
@@ -549,7 +507,6 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp filter_patterns(pattern) do
|
||||
pattern
|
||||
|> Path.expand()
|
||||
|> Path.wildcard()
|
||||
|> :lists.usort()
|
||||
|> Enum.filter(&File.regular?/1)
|
||||
|
||||
@@ -30,10 +30,10 @@ defmodule Kernel.ErrorHandler do
|
||||
end
|
||||
|
||||
def ensure_compiled(module, kind, deadlock) do
|
||||
{compiler_pid, file_pid} = :erlang.get(:elixir_compiler_info)
|
||||
parent = :erlang.get(:elixir_compiler_pid)
|
||||
ref = :erlang.make_ref()
|
||||
modules = :elixir_module.compiler_modules()
|
||||
send(compiler_pid, {:waiting, kind, self(), ref, file_pid, module, modules, deadlock})
|
||||
send(parent, {:waiting, kind, self(), ref, module, modules, deadlock})
|
||||
:erlang.garbage_collect(self())
|
||||
|
||||
receive do
|
||||
|
||||
@@ -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_export(pid, module) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:add_export, 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,16 +71,6 @@ defmodule Kernel.LexicalTracker do
|
||||
:gen_server.cast(pid, {:alias_dispatch, module})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def import_quoted(pid, module, function, arities) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:import_quoted, module, function, arities})
|
||||
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})
|
||||
@@ -93,28 +95,28 @@ defmodule Kernel.LexicalTracker do
|
||||
|
||||
@doc false
|
||||
def collect_unused_imports(pid) do
|
||||
unused(pid, :unused_imports)
|
||||
unused(pid, :import)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def collect_unused_aliases(pid) do
|
||||
unused(pid, :unused_aliases)
|
||||
unused(pid, :alias)
|
||||
end
|
||||
|
||||
defp unused(pid, tag) do
|
||||
:gen_server.call(pid, tag, @timeout)
|
||||
:gen_server.call(pid, {:unused, tag}, @timeout)
|
||||
end
|
||||
|
||||
# Callbacks
|
||||
|
||||
def init(:ok) do
|
||||
state = %{
|
||||
aliases: %{},
|
||||
imports: %{},
|
||||
directives: %{},
|
||||
references: %{},
|
||||
exports: %{},
|
||||
compile: %{},
|
||||
runtime: %{},
|
||||
structs: %{},
|
||||
cache: %{},
|
||||
compile_env: :ordsets.new(),
|
||||
file: nil
|
||||
}
|
||||
|
||||
@@ -122,21 +124,26 @@ defmodule Kernel.LexicalTracker do
|
||||
end
|
||||
|
||||
@doc false
|
||||
def handle_call(:unused_aliases, _from, state) do
|
||||
{:reply, Enum.sort(state.aliases), state}
|
||||
def handle_call({:unused, tag}, _from, state) do
|
||||
directives =
|
||||
for {{^tag, module_or_mfa}, marker} <- state.directives, is_integer(marker) do
|
||||
{module_or_mfa, marker}
|
||||
end
|
||||
|
||||
{:reply, Enum.sort(directives), state}
|
||||
end
|
||||
|
||||
def handle_call(:unused_imports, _from, state) do
|
||||
{:reply, Enum.sort(state.imports), 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(: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_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
|
||||
@@ -144,53 +151,36 @@ 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
|
||||
%{imports: imports, references: references} = state
|
||||
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)
|
||||
|
||||
imports =
|
||||
case imports do
|
||||
%{^module => modules_and_fas} ->
|
||||
modules_and_fas
|
||||
|> Map.delete(module)
|
||||
|> Map.delete({function, arity})
|
||||
|> then(&Map.put(imports, module, &1))
|
||||
|
||||
%{} ->
|
||||
imports
|
||||
end
|
||||
|
||||
references = add_reference(references, module, mode)
|
||||
{:noreply, %{state | imports: imports, references: references}}
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast({:alias_dispatch, module}, %{aliases: aliases} = state) do
|
||||
{:noreply, %{state | aliases: Map.delete(aliases, module)}}
|
||||
end
|
||||
|
||||
def handle_cast({:import_quoted, module, function, arities}, state) do
|
||||
%{imports: imports} = state
|
||||
|
||||
imports =
|
||||
case imports do
|
||||
%{^module => modules_and_fas} ->
|
||||
arities
|
||||
|> Enum.reduce(modules_and_fas, &Map.delete(&2, {function, &1}))
|
||||
|> Map.delete(module)
|
||||
|> then(&Map.put(imports, module, &1))
|
||||
|
||||
%{} ->
|
||||
imports
|
||||
end
|
||||
|
||||
{:noreply, %{state | imports: imports}}
|
||||
def handle_cast({:alias_dispatch, module}, state) do
|
||||
{:noreply, %{state | directives: add_dispatch(state.directives, module, :alias)}}
|
||||
end
|
||||
|
||||
def handle_cast({:set_file, file}, state) do
|
||||
@@ -201,29 +191,23 @@ 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_export, module}, state) do
|
||||
{:noreply, put_in(state.exports[module], true)}
|
||||
end
|
||||
|
||||
def handle_cast({:add_import, module, fas, line, warn}, state) do
|
||||
if warn do
|
||||
imports = for module_or_fa <- [module | fas], do: {module_or_fa, line}, into: %{}
|
||||
{:noreply, put_in(state.imports[module], imports)}
|
||||
else
|
||||
{:noreply, state}
|
||||
end
|
||||
directives =
|
||||
state.directives
|
||||
|> Enum.reject(&match?({{:import, {^module, _, _}}, _}, &1))
|
||||
|> :maps.from_list()
|
||||
|> add_directive(module, line, warn, :import)
|
||||
|
||||
directives =
|
||||
Enum.reduce(fas, directives, fn {function, arity}, directives ->
|
||||
add_directive(directives, {module, function, arity}, line, warn, :import)
|
||||
end)
|
||||
|
||||
{:noreply, %{state | directives: directives}}
|
||||
end
|
||||
|
||||
def handle_cast({:add_alias, module, line, warn}, state) do
|
||||
if warn do
|
||||
{:noreply, put_in(state.aliases[module], line)}
|
||||
else
|
||||
{:noreply, state}
|
||||
end
|
||||
{:noreply, %{state | directives: add_directive(state.directives, module, line, warn, :alias)}}
|
||||
end
|
||||
|
||||
@doc false
|
||||
@@ -252,12 +236,56 @@ 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 references do
|
||||
%{^module => _} -> references
|
||||
%{} -> Map.put(references, module, :runtime)
|
||||
case :maps.find(module, references) do
|
||||
{:ok, _} -> references
|
||||
:error -> :maps.put(module, :runtime, references)
|
||||
end
|
||||
end
|
||||
|
||||
defp add_remote_dispatch(state, module, fa, line, mode) when is_atom(module) do
|
||||
location = location(state.file, line)
|
||||
|
||||
map_update(mode, %{module => %{fa => [location]}}, state, fn mode_dispatches ->
|
||||
map_update(module, %{fa => [location]}, mode_dispatches, fn module_dispatches ->
|
||||
map_update(fa, [location], module_dispatches, &[location | List.delete(&1, location)])
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
defp location(nil, line), do: line
|
||||
defp location(file, line), do: {file, line}
|
||||
|
||||
defp add_import_dispatch(state, module, function, arity) do
|
||||
directives =
|
||||
add_dispatch(state.directives, module, :import)
|
||||
|> add_dispatch({module, function, arity}, :import)
|
||||
|
||||
# Always compile time because we depend
|
||||
# on the module at compile time
|
||||
references = add_reference(state.references, module, :compile)
|
||||
|
||||
%{state | directives: directives, references: references}
|
||||
end
|
||||
|
||||
# In the map we keep imports and aliases.
|
||||
# If the value is a line, it was imported/aliased and has a pending warning
|
||||
# If the value is true, it was imported/aliased and used
|
||||
defp add_directive(directives, module_or_mfa, line, warn, tag) do
|
||||
marker = if warn, do: line, else: true
|
||||
:maps.put({tag, module_or_mfa}, marker, directives)
|
||||
end
|
||||
|
||||
defp add_dispatch(directives, module_or_mfa, tag) do
|
||||
: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
|
||||
|
||||
@@ -3,12 +3,6 @@ defmodule Kernel.ParallelCompiler do
|
||||
A module responsible for compiling and requiring files in parallel.
|
||||
"""
|
||||
|
||||
@typedoc "The line. 0 indicates no line."
|
||||
@type line() :: non_neg_integer()
|
||||
@type location() :: line() | {pos_integer(), column :: non_neg_integer}
|
||||
@type warning() :: {file :: Path.t(), location(), message :: String.t()}
|
||||
@type error() :: {file :: Path.t(), location(), message :: String.t()}
|
||||
|
||||
@doc """
|
||||
Starts a task for parallel compilation.
|
||||
|
||||
@@ -21,29 +15,24 @@ 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
|
||||
case :erlang.get(:elixir_compiler_info) do
|
||||
{compiler, _} ->
|
||||
file = :erlang.get(:elixir_compiler_file)
|
||||
dest = :erlang.get(:elixir_compiler_dest)
|
||||
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)
|
||||
{:error_handler, error_handler} = :erlang.process_info(self(), :error_handler)
|
||||
|
||||
{:error_handler, error_handler} = :erlang.process_info(self(), :error_handler)
|
||||
{_parent, checker} = Module.ParallelChecker.get()
|
||||
|
||||
Task.async(fn ->
|
||||
send(compiler, {:async, self()})
|
||||
Module.ParallelChecker.put(compiler, checker)
|
||||
:erlang.put(:elixir_compiler_info, {compiler, self()})
|
||||
:erlang.put(:elixir_compiler_file, file)
|
||||
dest != :undefined and :erlang.put(:elixir_compiler_dest, dest)
|
||||
:erlang.process_flag(:error_handler, error_handler)
|
||||
fun.()
|
||||
end)
|
||||
|
||||
:undefined ->
|
||||
raise ArgumentError,
|
||||
"cannot spawn parallel compiler task because " <>
|
||||
"the current file is not being compiled/required"
|
||||
Task.async(fn ->
|
||||
send(parent, {:async, self()})
|
||||
:erlang.put(:elixir_compiler_pid, parent)
|
||||
:erlang.put(:elixir_compiler_file, file)
|
||||
dest != :undefined and :erlang.put(:elixir_compiler_dest, dest)
|
||||
:erlang.process_flag(:error_handler, error_handler)
|
||||
fun.()
|
||||
end)
|
||||
else
|
||||
raise ArgumentError,
|
||||
"cannot spawn parallel compiler task because " <>
|
||||
"the current file is not being compiled/required"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -73,43 +62,23 @@ 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"
|
||||
@spec compile([Path.t()], keyword()) :: {:ok, [atom], [warning]} | {:error, [error], [warning]}
|
||||
def compile(files, options \\ []) when is_list(options) do
|
||||
spawn_workers(files, :compile, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles the given files and writes resulting BEAM files into path.
|
||||
|
||||
See `compile/2` for more information.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec compile_to_path([Path.t()], Path.t(), keyword()) ::
|
||||
{:ok, [atom], [warning]} | {:error, [error], [warning]}
|
||||
def compile_to_path(files, path, options \\ []) when is_binary(path) and is_list(options) do
|
||||
spawn_workers(files, {:compile, path}, options)
|
||||
end
|
||||
@@ -135,21 +104,10 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec require([Path.t()], keyword()) ::
|
||||
{:ok, [atom], [warning]} | {:error, [error], [warning]}
|
||||
def require(files, options \\ []) when is_list(options) do
|
||||
spawn_workers(files, :require, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Prints a warning returned by the compiler.
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec print_warning(warning) :: :ok
|
||||
def print_warning({file, location, warning}) do
|
||||
:elixir_errors.print_warning(location, file, warning)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@deprecated "Use Kernel.ParallelCompiler.compile/2 instead"
|
||||
def files(files, options \\ []) when is_list(options) do
|
||||
@@ -170,62 +128,40 @@ 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)
|
||||
{:ok, checker} = Module.ParallelChecker.start_link(schedulers)
|
||||
|
||||
try do
|
||||
outcome = spawn_workers(schedulers, checker, files, output, options)
|
||||
{outcome, Code.get_compiler_option(:warnings_as_errors)}
|
||||
else
|
||||
{{:ok, _, [_ | _] = warnings}, true} ->
|
||||
result =
|
||||
spawn_workers(files, 0, [], [], %{}, [], %{
|
||||
dest: Keyword.get(options, :dest),
|
||||
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),
|
||||
output: output,
|
||||
long_compilation_threshold: Keyword.get(options, :long_compilation_threshold, 15),
|
||||
schedulers: schedulers
|
||||
})
|
||||
|
||||
# In case --warning-as-errors is enabled and there was a warning,
|
||||
# compilation status will be set to error.
|
||||
compilation_status = :elixir_code_server.call({:compilation_status, compiler_pid})
|
||||
|
||||
case {result, compilation_status} do
|
||||
{{:ok, _, warnings}, :error} ->
|
||||
message = "Compilation failed due to warnings while using the --warnings-as-errors option"
|
||||
IO.puts(:stderr, message)
|
||||
{:error, warnings, []}
|
||||
|
||||
{{:ok, outcome, warnings}, _} ->
|
||||
beam_timestamp = Keyword.get(options, :beam_timestamp)
|
||||
{: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}
|
||||
after
|
||||
Module.ParallelChecker.stop(checker)
|
||||
_ ->
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
defp spawn_workers(schedulers, checker, files, output, options) do
|
||||
threshold = Keyword.get(options, :long_compilation_threshold, 10) * 1000
|
||||
timer_ref = Process.send_after(self(), :threshold_check, threshold)
|
||||
|
||||
{outcome, state} =
|
||||
spawn_workers(files, 0, [], [], %{}, [], %{
|
||||
dest: Keyword.get(options, :dest),
|
||||
each_cycle: Keyword.get(options, :each_cycle, fn -> {:runtime, [], []} 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,
|
||||
schedulers: schedulers,
|
||||
checker: checker
|
||||
})
|
||||
|
||||
Process.cancel_timer(state.timer_ref)
|
||||
|
||||
receive do
|
||||
:threshold_check -> :ok
|
||||
after
|
||||
0 -> :ok
|
||||
end
|
||||
|
||||
outcome
|
||||
end
|
||||
|
||||
defp each_file(fun) when is_function(fun, 1), do: fn file, _ -> fun.(file) end
|
||||
defp each_file(fun) when is_function(fun, 2), do: fun
|
||||
|
||||
@@ -239,60 +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} ->
|
||||
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
|
||||
%{profile: profile, checker: checker} = state
|
||||
|
||||
compiled_modules =
|
||||
for {{:module, module}, _} <- result,
|
||||
do: module
|
||||
|
||||
profile_checker(profile, compiled_modules, runtime_modules, fn ->
|
||||
Module.ParallelChecker.verify(checker, runtime_modules)
|
||||
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,
|
||||
@@ -309,37 +191,52 @@ 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, file_pid, _on, _defining, _deadlock}, waiting} ->
|
||||
{{_kind, pid, ^ref, _on, _defining, _deadlock}, waiting} ->
|
||||
send(pid, {ref, found})
|
||||
{update_timing(files, file_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, checker: checker} = state
|
||||
%{output: output, long_compilation_threshold: threshold, dest: dest} = state
|
||||
parent = self()
|
||||
file = Path.expand(file)
|
||||
|
||||
{pid, ref} =
|
||||
:erlang.spawn_monitor(fn ->
|
||||
Module.ParallelChecker.put(parent, checker)
|
||||
:erlang.put(:elixir_compiler_info, {parent, self()})
|
||||
:erlang.put(:elixir_compiler_pid, parent)
|
||||
:erlang.put(:elixir_compiler_file, file)
|
||||
|
||||
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 ->
|
||||
@@ -349,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
|
||||
|
||||
@@ -386,8 +270,8 @@ defmodule Kernel.ParallelCompiler do
|
||||
defp spawn_workers(
|
||||
[],
|
||||
1,
|
||||
[{_, pid, ref, _, _, _, _}] = waiting,
|
||||
[%{pid: pid}] = files,
|
||||
[{_, pid, ref, _, _, _}] = waiting,
|
||||
[{pid, _, _, _}] = files,
|
||||
result,
|
||||
warnings,
|
||||
state
|
||||
@@ -401,31 +285,24 @@ defmodule Kernel.ParallelCompiler do
|
||||
# There is potentially a deadlock. We will release modules with
|
||||
# the following order:
|
||||
#
|
||||
# 1. Code.ensure_compiled/1 checks without a known definition (deadlock = soft)
|
||||
# 2. Code.ensure_compiled/1 checks with a known definition (deadlock = soft)
|
||||
# 3. Struct/import/require/ensure_compiled! checks without a known definition (deadlock = hard)
|
||||
# 4. Modules without a known definition
|
||||
# 5. Code invocation (deadlock = raise)
|
||||
# 1. Code.ensure_compiled?/1 checks (deadlock = soft)
|
||||
# 2. Struct checks (deadlock = hard)
|
||||
# 3. Modules without a known definition
|
||||
# 4. Code invocation (deadlock = raise)
|
||||
#
|
||||
# The reason for step 3 and 4 is to not treat typos as deadlocks and
|
||||
# help developers handle those sooner. However, this can have false
|
||||
# positives in case multiple modules are defined in the same file
|
||||
# and the module we are waiting for is defined later on.
|
||||
#
|
||||
# Finally, note there is no difference between hard and raise, the
|
||||
# In theory there is no difference between hard and raise, the
|
||||
# difference is where the raise is happening, inside the compiler
|
||||
# or in the caller.
|
||||
cond do
|
||||
deadlocked = deadlocked(waiting, :soft) || deadlocked(waiting, :hard) ->
|
||||
spawn_workers(deadlocked, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
deadlocked =
|
||||
deadlocked(waiting, :soft, false) ||
|
||||
deadlocked(waiting, :soft, true) || deadlocked(waiting, :hard, false) ||
|
||||
without_definition(waiting, files)
|
||||
without_definition = without_definition(waiting, files) ->
|
||||
spawn_workers(without_definition, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
if deadlocked do
|
||||
spawn_workers(deadlocked, spawned, waiting, files, result, warnings, state)
|
||||
else
|
||||
errors = handle_deadlock(waiting, files)
|
||||
{{:error, errors, warnings}, state}
|
||||
true ->
|
||||
errors = handle_deadlock(waiting, files)
|
||||
{:error, errors, warnings}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -434,84 +311,23 @@ 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
|
||||
|
||||
defp each_cycle_return({kind, modules, warnings}), do: {kind, modules, warnings}
|
||||
|
||||
defp each_cycle_return(other) do
|
||||
IO.warn(
|
||||
"the :each_cycle callback must return a tuple of format {:compile | :runtime, modules, warnings}"
|
||||
)
|
||||
|
||||
case other do
|
||||
{kind, modules} -> {kind, modules, []}
|
||||
modules when is_list(modules) -> {:compile, modules, []}
|
||||
end
|
||||
end
|
||||
|
||||
# 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 compiled yet, so they may not be in waiting.
|
||||
defp without_definition(waiting, files) do
|
||||
nilify_empty(
|
||||
for %{pid: pid} <- files,
|
||||
{_, _, ref, ^pid, on, _, _} <- waiting,
|
||||
not defining?(on, waiting),
|
||||
nillify_empty(
|
||||
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, defining?) do
|
||||
nilify_empty(
|
||||
for {_, _, ref, _, on, _, ^type} <- waiting,
|
||||
defining?(on, waiting) == defining?,
|
||||
do: {ref, :deadlock}
|
||||
)
|
||||
defp deadlocked(waiting, type) do
|
||||
nillify_empty(for {_, _, ref, _, _, ^type} <- waiting, do: {ref, :not_found})
|
||||
end
|
||||
|
||||
defp defining?(on, waiting) do
|
||||
Enum.any?(waiting, fn {_, _, _, _, _, defining, _} -> on in defining end)
|
||||
end
|
||||
|
||||
defp nilify_empty([]), do: nil
|
||||
defp nilify_empty([_ | _] = list), do: list
|
||||
defp nillify_empty([]), do: nil
|
||||
defp nillify_empty([_ | _] = list), do: list
|
||||
|
||||
# Wait for messages from child processes
|
||||
defp wait_for_messages(queue, spawned, waiting, files, result, warnings, state) do
|
||||
@@ -524,7 +340,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
{:available, kind, module} ->
|
||||
available =
|
||||
for {^kind, _, ref, _, ^module, _defining, _deadlock} <- waiting,
|
||||
for {^kind, _, ref, ^module, _defining, _deadlock} <- waiting,
|
||||
do: {ref, :found}
|
||||
|
||||
result = Map.put(result, {kind, module}, true)
|
||||
@@ -537,60 +353,53 @@ defmodule Kernel.ParallelCompiler do
|
||||
send(child, {ref, :ack})
|
||||
|
||||
available =
|
||||
for {:module, _, ref, _, ^module, _defining, _deadlock} <- waiting,
|
||||
for {:module, _, ref, ^module, _defining, _deadlock} <- waiting,
|
||||
do: {ref, :found}
|
||||
|
||||
result = Map.put(result, {:module, module}, binary)
|
||||
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.
|
||||
{:waiting, _kind, child, ref, _file_pid, _on, _defining, _deadlock} when output == :require ->
|
||||
{:waiting, _kind, child, ref, _on, _defining, _deadlock} when output == :require ->
|
||||
send(child, {ref, :not_found})
|
||||
spawn_workers(queue, spawned, waiting, files, result, warnings, state)
|
||||
|
||||
{:waiting, kind, child_pid, ref, file_pid, on, defining, deadlock?} ->
|
||||
{: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_pid, {ref, :found})
|
||||
{files, waiting}
|
||||
send(child, {ref, :found})
|
||||
waiting
|
||||
else
|
||||
files = update_timing(files, file_pid, :compiling)
|
||||
{files, [{kind, child_pid, ref, file_pid, 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, location, message} ->
|
||||
{:warning, file, line, message} ->
|
||||
file = file && Path.absname(file)
|
||||
message = :unicode.characters_to_binary(message)
|
||||
warning = {file, location, message}
|
||||
warning = {file, line, message}
|
||||
wait_for_messages(queue, spawned, waiting, files, result, [warning | warnings], state)
|
||||
|
||||
{: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
|
||||
@@ -598,84 +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 = to_padded_ms(data.compiling)
|
||||
waiting = to_padded_ms(data.waiting)
|
||||
relative = Path.relative_to_cwd(data.file)
|
||||
|
||||
IO.puts(
|
||||
:stderr,
|
||||
"[profile] #{compiling}ms compiling + #{waiting}ms waiting for #{relative}"
|
||||
)
|
||||
end
|
||||
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp to_padded_ms(time) do
|
||||
time
|
||||
|> System.convert_time_unit(:native, :millisecond)
|
||||
|> Integer.to_string()
|
||||
|> String.pad_leading(6, " ")
|
||||
end
|
||||
|
||||
defp discard_down(pid) do
|
||||
receive do
|
||||
{:DOWN, _, :process, ^pid, _} -> :ok
|
||||
@@ -687,24 +440,28 @@ 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)
|
||||
|
||||
{kind, ^pid, _, _, on, _, _} = List.keyfind(waiting, pid, 1)
|
||||
{kind, ^pid, _, on, _, _} = List.keyfind(waiting, pid, 1)
|
||||
description = "deadlocked waiting on #{kind} #{inspect(on)}"
|
||||
error = CompileError.exception(description: description, file: nil, line: nil)
|
||||
print_error(file, :error, error, stacktrace)
|
||||
@@ -735,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
|
||||
|
||||
@@ -747,16 +504,27 @@ 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)
|
||||
message = :unicode.characters_to_binary(Kernel.CLI.format_error(kind, reason, stack))
|
||||
{file, line || 0, message}
|
||||
end
|
||||
|
||||
defp get_line(_file, %{line: line, column: column}, _stack)
|
||||
when is_integer(line) and line > 0 and is_integer(column) and column >= 0 do
|
||||
{line, column}
|
||||
{file, line, message}
|
||||
end
|
||||
|
||||
defp get_line(_file, %{line: line}, _stack) when is_integer(line) and line > 0 do
|
||||
@@ -769,13 +537,6 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
end
|
||||
|
||||
defp get_line(file, _reason, [{_, _, _, [file: expanding]}, {_, _, _, info} | _])
|
||||
when expanding in ['expanding macro', 'expanding struct'] 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.
|
||||
@@ -182,12 +175,18 @@ defmodule Kernel.SpecialForms do
|
||||
<<1, 2, 3>>
|
||||
|
||||
Elixir also accepts by default the segment to be a literal
|
||||
string which expands to integers:
|
||||
string or a literal charlist, which are by default expanded to integers:
|
||||
|
||||
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 constructing the binary:
|
||||
|
||||
rest = "oo"
|
||||
<<102, rest>>
|
||||
** (ArgumentError) argument error
|
||||
|
||||
## Options
|
||||
|
||||
Many options can be given by using `-` as separator. Order is
|
||||
@@ -233,9 +226,9 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
Sizes for types are a bit more nuanced. The default size for integers is 8.
|
||||
|
||||
For floats, it is 64. For floats, `size * unit` must result in 16, 32, or 64,
|
||||
For floats, it is 64. For floats, `size * unit` must result in 32 or 64,
|
||||
corresponding to [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point)
|
||||
binary16, binary32, and binary64, respectively.
|
||||
binary32 and binary64, respectively.
|
||||
|
||||
For binaries, the default is the size of the binary. Only the last binary in a
|
||||
match can use the default size. All others must have their size specified
|
||||
@@ -246,20 +239,20 @@ defmodule Kernel.SpecialForms do
|
||||
iex> {name, species}
|
||||
{"Frank", "Walrus"}
|
||||
|
||||
The size can be a variable or any valid guard expression:
|
||||
The size can be a variable:
|
||||
|
||||
iex> name_size = 5
|
||||
iex> <<name::binary-size(name_size), " the ", species::binary>> = <<"Frank the Walrus">>
|
||||
iex> {name, species}
|
||||
{"Frank", "Walrus"}
|
||||
|
||||
The size can access prior variables defined in the binary itself:
|
||||
And the variable can be defined in the match itself (prior to its use):
|
||||
|
||||
iex> <<name_size::size(8), name::binary-size(name_size), " the ", species::binary>> = <<5, "Frank the Walrus">>
|
||||
iex> {name, species}
|
||||
{"Frank", "Walrus"}
|
||||
|
||||
However, it cannot access variables defined in the match outside of the binary/bitstring:
|
||||
However, the size cannot be defined in the match outside the binary/bitstring match:
|
||||
|
||||
{name_size, <<name::binary-size(name_size), _rest::binary>>} = {5, <<"Frank the Walrus">>}
|
||||
** (CompileError): undefined variable "name_size" in bitstring segment
|
||||
@@ -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
|
||||
|
||||
@@ -365,13 +358,13 @@ defmodule Kernel.SpecialForms do
|
||||
ERL_COMPILER_OPTIONS=bin_opt_info mix compile
|
||||
|
||||
To learn more about specific optimizations and performance considerations,
|
||||
check out the
|
||||
["Constructing and matching binaries" chapter of the Erlang's Efficiency Guide](https://www.erlang.org/doc/efficiency_guide/binaryhandling.html).
|
||||
check out
|
||||
[Erlang's Efficiency Guide on handling binaries](http://www.erlang.org/doc/efficiency_guide/binaryhandling.html).
|
||||
"""
|
||||
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,17 +592,16 @@ 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
|
||||
|
||||
A developer can filter to import only functions, macros, or sigils
|
||||
(which can be functions or macros) via the `:only` option:
|
||||
A developer can filter to import only macros or functions via
|
||||
the only option:
|
||||
|
||||
import List, only: :functions
|
||||
import List, only: :macros
|
||||
import Kernel, only: :sigils
|
||||
|
||||
Alternatively, Elixir allows a developer to pass pairs of
|
||||
name/arities to `:only` or `:except` as a fine grained control
|
||||
@@ -618,11 +610,9 @@ defmodule Kernel.SpecialForms do
|
||||
import List, only: [flatten: 1]
|
||||
import String, except: [split: 2]
|
||||
|
||||
Importing the same module again will erase the previous imports,
|
||||
except when the `except` option is used, which is always exclusive
|
||||
on a previously declared `import/2`. If there is no previous import,
|
||||
then it applies to all functions and macros in the module. For
|
||||
example:
|
||||
Notice that calling `except` 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:
|
||||
|
||||
import List, only: [flatten: 1, keyfind: 4]
|
||||
import List, except: [flatten: 1]
|
||||
@@ -640,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
|
||||
@@ -724,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
|
||||
|
||||
@@ -760,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,
|
||||
@@ -779,7 +768,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
<<int::integer-little, rest::bits>> = bits
|
||||
|
||||
Read the documentation on the [Typespecs page](typespecs.md) and
|
||||
Read the documentation on the `Typespec` page and
|
||||
`<<>>/1` for more information on typespecs and
|
||||
bitstrings respectively.
|
||||
"""
|
||||
@@ -809,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
|
||||
@@ -831,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:
|
||||
@@ -861,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,
|
||||
@@ -960,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
|
||||
@@ -1025,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:
|
||||
@@ -1067,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`.
|
||||
|
||||
@@ -1116,7 +1104,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
require Hygiene
|
||||
Hygiene.no_interference()
|
||||
** (UndefinedFunctionError) ...
|
||||
#=> ** (UndefinedFunctionError) ...
|
||||
|
||||
Hygiene.interference()
|
||||
#=> "world"
|
||||
@@ -1203,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
|
||||
@@ -1212,12 +1200,6 @@ defmodule Kernel.SpecialForms do
|
||||
reported to where `defadd` was invoked. `location: :keep` affects
|
||||
only definitions inside the quote.
|
||||
|
||||
> **Important:** do not use location: :keep if the function definition
|
||||
> also `unquote`s some of the macro arguments. If you do so, Elixir
|
||||
> will store the file definition of the current location but the
|
||||
> unquoted arguments may contain line information of the macro caller,
|
||||
> leading to erroneous stacktraces.
|
||||
|
||||
## Binding and unquote fragments
|
||||
|
||||
Elixir quote/unquote mechanisms provide a functionality called
|
||||
@@ -1316,13 +1298,11 @@ defmodule Kernel.SpecialForms do
|
||||
sum(1, value, 3)
|
||||
end
|
||||
|
||||
|
||||
Which the argument for the `:sum` function call is not the
|
||||
expected result:
|
||||
Which would then return:
|
||||
|
||||
{:sum, [], [1, {:value, [], Elixir}, 3]}
|
||||
|
||||
For this, we use `unquote`:
|
||||
Which is not the expected result. For this, we use `unquote`:
|
||||
|
||||
iex> value =
|
||||
...> quote do
|
||||
@@ -1389,10 +1369,6 @@ defmodule Kernel.SpecialForms do
|
||||
iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n
|
||||
[2, 4, 6]
|
||||
|
||||
Filters must evaluate to truthy values (everything but `nil`
|
||||
and `false`). If a filter is falsy, then the current value is
|
||||
discarded.
|
||||
|
||||
Generators can also be used to filter as it removes any value
|
||||
that doesn't match the pattern on the left side of `<-`:
|
||||
|
||||
@@ -1413,35 +1389,6 @@ defmodule Kernel.SpecialForms do
|
||||
filters or inside the block, are not reflected outside of the
|
||||
comprehension.
|
||||
|
||||
Variable assignments inside filters must still return a truthy value,
|
||||
otherwise values are discarded. Let's see an example. Imagine you have
|
||||
a keyword list where the key is a programming language and the value
|
||||
is its direct parent. Then let's try to compute the grandparent of each
|
||||
language. You could try this:
|
||||
|
||||
iex> languages = [elixir: :erlang, erlang: :prolog, prolog: nil]
|
||||
iex> for {language, parent} <- languages, grandparent = languages[parent], do: {language, grandparent}
|
||||
[elixir: :prolog]
|
||||
|
||||
Given the grandparents of Erlang and Prolog were nil, those values were
|
||||
filtered out. If you don't want this behaviour, a simple option is to
|
||||
move the filter inside the do-block:
|
||||
|
||||
iex> languages = [elixir: :erlang, erlang: :prolog, prolog: nil]
|
||||
iex> for {language, parent} <- languages do
|
||||
...> grandparent = languages[parent]
|
||||
...> {language, grandparent}
|
||||
...> end
|
||||
[elixir: :prolog, erlang: nil, prolog: nil]
|
||||
|
||||
However, such option is not always available, as you may have further
|
||||
filters. An alternative is to convert the filter into a generator by
|
||||
wrapping the right side of `=` in a list:
|
||||
|
||||
iex> languages = [elixir: :erlang, erlang: :prolog, prolog: nil]
|
||||
iex> for {language, parent} <- languages, grandparent <- [languages[parent]], do: {language, grandparent}
|
||||
[elixir: :prolog, erlang: nil, prolog: nil]
|
||||
|
||||
## The `:into` and `:uniq` options
|
||||
|
||||
In the examples above, the result returned by the comprehension was
|
||||
@@ -1458,7 +1405,7 @@ defmodule Kernel.SpecialForms do
|
||||
The `IO` module provides streams, that are both `Enumerable` and
|
||||
`Collectable`, here is an upcase echo server using comprehensions:
|
||||
|
||||
for line <- IO.stream(), into: IO.stream() do
|
||||
for line <- IO.stream(:stdio, :line), into: IO.stream(:stdio, :line) do
|
||||
String.upcase(line)
|
||||
end
|
||||
|
||||
@@ -1561,15 +1508,15 @@ defmodule Kernel.SpecialForms do
|
||||
iex> width
|
||||
nil
|
||||
|
||||
The behaviour of any expression in a clause is the same as if it was
|
||||
written outside of `with`. For example, `=` will raise a `MatchError`
|
||||
instead of returning the non-matched value:
|
||||
The behaviour of any expression in a clause is the same as outside.
|
||||
For example, `=` will raise a `MatchError` instead of returning the
|
||||
non-matched value:
|
||||
|
||||
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:
|
||||
also be used around the arguments before the `do`/`end` block:
|
||||
|
||||
iex> opts = %{width: 10, height: 15}
|
||||
iex> with(
|
||||
@@ -1582,8 +1529,6 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
The choice between parens and no parens is a matter of preference.
|
||||
|
||||
## Else clauses
|
||||
|
||||
An `else` option can be given to modify what is being returned from
|
||||
`with` in the case of a failed match:
|
||||
|
||||
@@ -1594,68 +1539,17 @@ defmodule Kernel.SpecialForms do
|
||||
...> else
|
||||
...> :error ->
|
||||
...> {:error, :wrong_data}
|
||||
...>
|
||||
...> _other_error ->
|
||||
...> :unexpected_error
|
||||
...> end
|
||||
{:error, :wrong_data}
|
||||
|
||||
The `else` block works like a `case` clause: it can have multiple clauses,
|
||||
and the first match will be used. Variables bound inside `with` (such as
|
||||
`width` in this example) are not available in the `else` block.
|
||||
|
||||
If an `else` block is used and there are no matching clauses, a `WithClauseError`
|
||||
exception is raised.
|
||||
|
||||
### Beware!
|
||||
|
||||
Keep in mind that, one of potential drawback of `with` is that all
|
||||
failure clauses are flattened into a single `else` block. For example,
|
||||
take this code that checks if a given path points to an Elixir file
|
||||
and that it exists before creating a backup copy:
|
||||
|
||||
with ".ex" <- Path.extname(path),
|
||||
true <- File.exists?(path) do
|
||||
backup_path = path <> ".backup"
|
||||
File.cp!(path, backup_path)
|
||||
{:ok, backup_path}
|
||||
else
|
||||
binary when is_binary(binary) ->
|
||||
{:error, :invalid_extension}
|
||||
|
||||
false ->
|
||||
{:error, :missing_file}
|
||||
end
|
||||
|
||||
Note how we are having to reconstruct the result types of `Path.extname/1`
|
||||
and `File.exists?/1` to build error messages. In this case, it is better
|
||||
to change the with clauses to already return the desired format, like this:
|
||||
|
||||
with :ok <- validate_extension(path),
|
||||
:ok <- validate_exists(path) do
|
||||
backup_path = path <> ".backup"
|
||||
File.cp!(path, backup_path)
|
||||
{:ok, backup_path}
|
||||
end
|
||||
|
||||
defp validate_extension(path) do
|
||||
if Path.extname(path) == ".ex", do: :ok, else: {:error, :invalid_extension}
|
||||
end
|
||||
|
||||
defp validate_exists(path) do
|
||||
if File.exists?(path), do: :ok, else: {:error, :missing_file}
|
||||
end
|
||||
|
||||
Note how the code above is better organized and clearer once we
|
||||
make sure each clause in `with` returns a normalized format.
|
||||
"""
|
||||
defmacro with(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Defines an anonymous function.
|
||||
|
||||
See `Function` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> add = fn a, b -> a + b end
|
||||
@@ -1693,7 +1587,7 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro unquote(:__block__)(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Capture operator. Captures or creates an anonymous function.
|
||||
Captures or creates an anonymous function.
|
||||
|
||||
## Capture
|
||||
|
||||
@@ -1784,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]}, [], []}
|
||||
|
||||
@@ -1816,21 +1710,19 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
## Examples
|
||||
|
||||
case File.read(file) do
|
||||
{:ok, contents} when is_binary(contents) ->
|
||||
String.split(contents, "\n")
|
||||
|
||||
{:error, _reason} ->
|
||||
Logger.warning "could not find #{file}, assuming empty..."
|
||||
[]
|
||||
case thing do
|
||||
{:selector, i, value} when is_integer(i) ->
|
||||
value
|
||||
value ->
|
||||
value
|
||||
end
|
||||
|
||||
In the example above, we match the result of `File.read/1`
|
||||
against each clause "head" and execute the clause "body"
|
||||
corresponding to the first clause that matches.
|
||||
In the example above, we match `thing` against each clause "head"
|
||||
and execute the clause "body" corresponding to the first clause
|
||||
that matches.
|
||||
|
||||
If no clause matches, an error is raised. For this reason,
|
||||
it may be necessary to add a final catch-all clause (like `_`)
|
||||
If no clause matches, an error is raised.
|
||||
For this reason, it may be necessary to add a final catch-all clause (like `_`)
|
||||
which will always match.
|
||||
|
||||
x = 10
|
||||
@@ -1838,7 +1730,6 @@ defmodule Kernel.SpecialForms do
|
||||
case x do
|
||||
0 ->
|
||||
"This clause won't match"
|
||||
|
||||
_ ->
|
||||
"This clause would match any value (x = #{x})"
|
||||
end
|
||||
@@ -1846,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
|
||||
@@ -1856,7 +1748,8 @@ defmodule Kernel.SpecialForms do
|
||||
value
|
||||
#=> unbound variable value
|
||||
|
||||
Variables in the outer context cannot be overridden either:
|
||||
However, variables explicitly bound in the clause "body" are
|
||||
accessible from the outer context:
|
||||
|
||||
value = 7
|
||||
|
||||
@@ -1866,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:
|
||||
@@ -1883,19 +1777,6 @@ defmodule Kernel.SpecialForms do
|
||||
end
|
||||
#=> "Will match"
|
||||
|
||||
## Using guards to match against multiple values
|
||||
|
||||
While it is not possible to match against multiple patterns in a single
|
||||
clause, it's possible to match against multiple values by using guards:
|
||||
|
||||
case data do
|
||||
value when value in [:one, :two] ->
|
||||
"#{value} has been matched"
|
||||
|
||||
:three ->
|
||||
"three has been matched"
|
||||
end
|
||||
|
||||
"""
|
||||
defmacro case(condition, clauses), do: error!([condition, clauses])
|
||||
|
||||
@@ -2093,25 +1974,6 @@ defmodule Kernel.SpecialForms do
|
||||
File.rm("tmp/story.txt")
|
||||
end
|
||||
|
||||
Although `after` clauses are invoked whether or not there was an error, they do not
|
||||
modify the return value. All of the following examples return `:return_me`:
|
||||
|
||||
try do
|
||||
:return_me
|
||||
after
|
||||
IO.puts("I will be printed")
|
||||
:not_returned
|
||||
end
|
||||
|
||||
try do
|
||||
raise "boom"
|
||||
rescue
|
||||
_ -> :return_me
|
||||
after
|
||||
IO.puts("I will be printed")
|
||||
:not_returned
|
||||
end
|
||||
|
||||
## `else` clauses
|
||||
|
||||
`else` clauses allow the result of the body passed to `try/1` to be pattern
|
||||
|
||||
@@ -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)
|
||||
|
||||
_ ->
|
||||
@@ -104,7 +104,7 @@ defmodule Kernel.Typespec do
|
||||
@doc """
|
||||
Defines a typespec.
|
||||
|
||||
Invoked by `@/1` expansion.
|
||||
Invoked by `Kernel.@/1` expansion.
|
||||
"""
|
||||
def deftypespec(:spec, expr, _line, _file, module, pos) do
|
||||
{_set, bag} = :elixir_module.data_tables(module)
|
||||
@@ -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)
|
||||
|
||||
@@ -194,14 +187,14 @@ defmodule Kernel.Typespec do
|
||||
|
||||
defp get_doc_info(set, attr, line) do
|
||||
case :ets.take(set, attr) do
|
||||
[{^attr, {line, doc}, _, _}] -> {line, doc}
|
||||
[{^attr, {line, doc}, _}] -> {line, doc}
|
||||
[] -> {line, nil}
|
||||
end
|
||||
end
|
||||
|
||||
defp get_doc_meta(spec_meta, doc_kind, set) do
|
||||
case :ets.take(set, {doc_kind, :meta}) do
|
||||
[{{^doc_kind, :meta}, metadata}] -> Map.merge(metadata, spec_meta)
|
||||
[{{^doc_kind, :meta}, metadata, _}] -> Map.merge(metadata, spec_meta)
|
||||
[] -> spec_meta
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -553,7 +540,9 @@ defmodule Kernel.Typespec do
|
||||
end
|
||||
|
||||
defp typespec({:%, _, [name, {:%{}, meta, fields}]}, vars, caller, state) do
|
||||
module = Macro.expand(name, %{caller | function: {:__info__, 1}})
|
||||
# We cannot set a function name to avoid tracking
|
||||
# as a compile time dependency, because for structs it actually is one.
|
||||
module = Macro.expand(name, caller)
|
||||
|
||||
struct =
|
||||
module
|
||||
@@ -567,10 +556,7 @@ defmodule Kernel.Typespec do
|
||||
|
||||
types =
|
||||
:lists.map(
|
||||
fn
|
||||
{:__exception__ = field, true} -> {field, Keyword.get(fields, field, true)}
|
||||
{field, _} -> {field, Keyword.get(fields, field, quote(do: term()))}
|
||||
end,
|
||||
fn {field, _} -> {field, Keyword.get(fields, field, quote(do: term()))} end,
|
||||
:lists.sort(struct)
|
||||
)
|
||||
|
||||
@@ -578,7 +564,7 @@ defmodule Kernel.Typespec do
|
||||
unless Keyword.has_key?(struct, field) do
|
||||
compile_error(
|
||||
caller,
|
||||
"undefined field #{inspect(field)} on struct #{inspect(module)}"
|
||||
"undefined field #{inspect(field)} on struct #{Macro.to_string(name)}"
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -644,7 +630,10 @@ defmodule Kernel.Typespec do
|
||||
end
|
||||
|
||||
defp typespec({:__aliases__, _, _} = alias, vars, caller, state) do
|
||||
typespec(expand_remote(alias, caller), vars, caller, state)
|
||||
# We set a function name to avoid tracking
|
||||
# aliases in typespecs as compile time dependencies.
|
||||
atom = Macro.expand(alias, %{caller | function: {:typespec, 0}})
|
||||
typespec(atom, vars, caller, state)
|
||||
end
|
||||
|
||||
# Handle funs
|
||||
@@ -672,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}
|
||||
|
||||
@@ -681,27 +670,17 @@ defmodule Kernel.Typespec do
|
||||
end
|
||||
end
|
||||
|
||||
defp typespec({:"::", meta, [left, right]}, vars, caller, state) do
|
||||
defp typespec({:"::", meta, [left, right]} = expr, vars, caller, state) do
|
||||
message =
|
||||
"invalid type annotation. The left side of :: must be a variable, got: #{Macro.to_string(left)}"
|
||||
|
||||
message =
|
||||
case left do
|
||||
{:|, _, _} ->
|
||||
message <>
|
||||
". Note \"left | right :: ann\" is the same as \"(left | right) :: ann\". " <>
|
||||
"To solve this, use parentheses around the union operands: \"left | (right :: ann)\""
|
||||
|
||||
_ ->
|
||||
message
|
||||
end
|
||||
"invalid type annotation. When using the | operator to represent the union of types, " <>
|
||||
"make sure to wrap type annotations in parentheses: #{Macro.to_string(expr)}"
|
||||
|
||||
# TODO: Make this an error on v2.0, and remove the code below and
|
||||
# the :undefined_type_error_enabled? key from the state
|
||||
: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}
|
||||
@@ -742,21 +721,18 @@ defmodule Kernel.Typespec do
|
||||
|
||||
# Handle remote calls
|
||||
defp typespec({{:., meta, [remote, name]}, _, args} = orig, vars, caller, state) do
|
||||
remote = expand_remote(remote, caller)
|
||||
# We set a function name to avoid tracking
|
||||
# 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
|
||||
@@ -852,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 =
|
||||
@@ -913,25 +886,6 @@ defmodule Kernel.Typespec do
|
||||
|
||||
## Helpers
|
||||
|
||||
# This is a backport of Macro.expand/2 because we want to expand
|
||||
# aliases but we don't them to become compile-time references.
|
||||
defp expand_remote({:__aliases__, _, _} = alias, env) do
|
||||
case :elixir_aliases.expand(alias, env) do
|
||||
receiver when is_atom(receiver) ->
|
||||
receiver
|
||||
|
||||
aliases ->
|
||||
aliases = :lists.map(&Macro.expand_once(&1, env), aliases)
|
||||
|
||||
case :lists.all(&is_atom/1, aliases) do
|
||||
true -> :elixir_aliases.concat(aliases)
|
||||
false -> alias
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp expand_remote(other, env), do: Macro.expand(other, env)
|
||||
|
||||
defp compile_error(caller, desc) do
|
||||
raise CompileError, file: caller.file, line: caller.line, description: desc
|
||||
end
|
||||
@@ -1033,11 +987,7 @@ defmodule Kernel.Typespec do
|
||||
:elixir_errors.erl_warn(caller.line, caller.file, warning)
|
||||
|
||||
{_, :used_once} ->
|
||||
compile_error(
|
||||
caller,
|
||||
"type variable #{name} is used only once. Type variables in typespecs " <>
|
||||
"must be referenced at least twice, otherwise it is equivalent to term()"
|
||||
)
|
||||
compile_error(caller, "type variable #{name} is unused")
|
||||
|
||||
_ ->
|
||||
:ok
|
||||
|
||||
+17
-149
@@ -22,52 +22,16 @@ defmodule Kernel.Utils do
|
||||
defp destructure_nil(count), do: [nil | destructure_nil(count - 1)]
|
||||
|
||||
@doc """
|
||||
Callback for defdelegate entry point.
|
||||
Callback for defdelegate.
|
||||
"""
|
||||
def defdelegate_all(funs, opts, env) do
|
||||
to = Keyword.get(opts, :to) || raise ArgumentError, "expected to: to be given as argument"
|
||||
as = Keyword.get(opts, :as)
|
||||
|
||||
if to == env.module and is_nil(as) do
|
||||
raise ArgumentError,
|
||||
"defdelegate function is calling itself, which will lead to an infinite loop. You should either change the value of the :to option or specify the :as option"
|
||||
end
|
||||
|
||||
if is_list(funs) do
|
||||
IO.warn(
|
||||
"passing a list to Kernel.defdelegate/2 is deprecated, please define each delegate separately",
|
||||
Macro.Env.stacktrace(env)
|
||||
)
|
||||
end
|
||||
|
||||
if Keyword.has_key?(opts, :append_first) do
|
||||
IO.warn(
|
||||
"Kernel.defdelegate/2 :append_first option is deprecated",
|
||||
Macro.Env.stacktrace(env)
|
||||
)
|
||||
end
|
||||
|
||||
to
|
||||
end
|
||||
|
||||
@doc """
|
||||
Callback for each function in defdelegate.
|
||||
"""
|
||||
def defdelegate_each(fun, opts) when is_list(opts) do
|
||||
def defdelegate(fun, opts) when is_list(opts) do
|
||||
# TODO: Remove on v2.0
|
||||
append_first? = Keyword.get(opts, :append_first, false)
|
||||
|
||||
{name, args} =
|
||||
case fun do
|
||||
{:when, _, [_left, right]} ->
|
||||
raise ArgumentError,
|
||||
"guards are not allowed in defdelegate/2, got: when #{Macro.to_string(right)}"
|
||||
|
||||
_ ->
|
||||
case Macro.decompose_call(fun) do
|
||||
{_, _} = pair -> pair
|
||||
_ -> raise ArgumentError, "invalid syntax in defdelegate #{Macro.to_string(fun)}"
|
||||
end
|
||||
case Macro.decompose_call(fun) do
|
||||
{_, _} = pair -> pair
|
||||
_ -> raise ArgumentError, "invalid syntax in defdelegate #{Macro.to_string(fun)}"
|
||||
end
|
||||
|
||||
as = Keyword.get(opts, :as, name)
|
||||
@@ -100,15 +64,7 @@ defmodule Kernel.Utils do
|
||||
@doc """
|
||||
Callback for defstruct.
|
||||
"""
|
||||
def defstruct(module, fields, bootstrapped?) do
|
||||
{set, bag} = :elixir_module.data_tables(module)
|
||||
|
||||
if :ets.member(set, :__struct__) do
|
||||
raise ArgumentError,
|
||||
"defstruct has already been called for " <>
|
||||
"#{Kernel.inspect(module)}, defstruct can only be called once per module"
|
||||
end
|
||||
|
||||
def defstruct(module, fields) do
|
||||
case fields do
|
||||
fs when is_list(fs) ->
|
||||
:ok
|
||||
@@ -120,7 +76,7 @@ defmodule Kernel.Utils do
|
||||
mapper = fn
|
||||
{key, val} when is_atom(key) ->
|
||||
try do
|
||||
:elixir_quote.escape(val, false, :none)
|
||||
Macro.escape(val)
|
||||
rescue
|
||||
e in [ArgumentError] ->
|
||||
raise ArgumentError, "invalid value for struct field #{key}, " <> Exception.message(e)
|
||||
@@ -136,23 +92,7 @@ defmodule Kernel.Utils do
|
||||
end
|
||||
|
||||
fields = :lists.map(mapper, fields)
|
||||
|
||||
enforce_keys =
|
||||
case :ets.lookup(set, :enforce_keys) do
|
||||
[{_, enforce_keys, _, _}] when is_list(enforce_keys) ->
|
||||
:ets.update_element(set, :enforce_keys, {3, :used})
|
||||
enforce_keys
|
||||
|
||||
[{_, enforce_key, _, _}] ->
|
||||
:ets.update_element(set, :enforce_keys, {3, :used})
|
||||
[enforce_key]
|
||||
|
||||
[] ->
|
||||
[]
|
||||
end
|
||||
|
||||
# TODO: Make it raise on v2.0
|
||||
warn_on_duplicate_struct_key(:lists.keysort(1, fields))
|
||||
enforce_keys = List.wrap(Module.get_attribute(module, :enforce_keys))
|
||||
|
||||
foreach = fn
|
||||
key when is_atom(key) ->
|
||||
@@ -163,90 +103,18 @@ defmodule Kernel.Utils do
|
||||
end
|
||||
|
||||
:lists.foreach(foreach, enforce_keys)
|
||||
|
||||
struct = :maps.put(:__struct__, module, :maps.from_list(fields))
|
||||
|
||||
body =
|
||||
case bootstrapped? do
|
||||
true ->
|
||||
case enforce_keys do
|
||||
[] ->
|
||||
quote do
|
||||
Enum.reduce(kv, @__struct__, fn {key, val}, map ->
|
||||
%{map | key => val}
|
||||
end)
|
||||
end
|
||||
|
||||
_ ->
|
||||
quote do
|
||||
{map, keys} =
|
||||
Enum.reduce(kv, {@__struct__, unquote(enforce_keys)}, fn
|
||||
{key, val}, {map, keys} ->
|
||||
{%{map | key => val}, List.delete(keys, key)}
|
||||
end)
|
||||
|
||||
case keys do
|
||||
[] ->
|
||||
map
|
||||
|
||||
_ ->
|
||||
raise ArgumentError,
|
||||
"the following keys must also be given when building " <>
|
||||
"struct #{inspect(__MODULE__)}: #{inspect(keys)}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
false ->
|
||||
quote do
|
||||
:lists.foldl(
|
||||
fn {key, val}, acc -> %{acc | key => val} end,
|
||||
@__struct__,
|
||||
kv
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
case enforce_keys -- :maps.keys(struct) do
|
||||
[] ->
|
||||
# The __struct__ field is used for expansion and for loading remote structs
|
||||
:ets.insert(set, {:__struct__, struct, nil, []})
|
||||
|
||||
# Store all field metadata to go into __info__(:struct)
|
||||
mapper = fn {key, val} ->
|
||||
%{field: key, default: val, required: :lists.member(key, enforce_keys)}
|
||||
end
|
||||
|
||||
:ets.insert(set, {{:elixir, :struct}, :lists.map(mapper, fields)})
|
||||
derive = :lists.map(fn {_, value} -> value end, :ets.take(bag, {:accumulate, :derive}))
|
||||
{struct, :lists.reverse(derive), quote(do: kv), body}
|
||||
|
||||
error_keys ->
|
||||
raise ArgumentError,
|
||||
"@enforce_keys required keys (#{inspect(error_keys)}) that are not defined in defstruct: " <>
|
||||
"#{inspect(fields)}"
|
||||
end
|
||||
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)
|
||||
{struct, enforce_keys, Module.get_attribute(module, :derive)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Announcing callback for defstruct.
|
||||
"""
|
||||
def announce_struct(module) do
|
||||
case :erlang.get(:elixir_compiler_info) do
|
||||
case :erlang.get(:elixir_compiler_pid) do
|
||||
:undefined -> :ok
|
||||
{pid, _} -> send(pid, {:available, :struct, module})
|
||||
pid -> send(pid, {:available, :struct, module})
|
||||
end
|
||||
end
|
||||
|
||||
@@ -326,12 +194,12 @@ defmodule Kernel.Utils do
|
||||
def defguard(args, expr, env) do
|
||||
{^args, vars} = extract_refs_from_args(args)
|
||||
env = :elixir_env.with_vars(%{env | context: :guard}, vars)
|
||||
{expr, _, _} = :elixir_expand.expand(expr, :elixir_env.env_to_ex(env), env)
|
||||
{expr, _scope} = :elixir_expand.expand(expr, env)
|
||||
|
||||
quote do
|
||||
case Macro.Env.in_guard?(__CALLER__) do
|
||||
true -> unquote(literal_quote(unquote_every_ref(expr, vars)))
|
||||
false -> unquote(literal_quote(unquote_refs_once(expr, vars, env.module)))
|
||||
false -> unquote(literal_quote(unquote_refs_once(expr, vars)))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -361,7 +229,7 @@ defmodule Kernel.Utils do
|
||||
end
|
||||
|
||||
# Prefaces `guard` with unquoted versions of `refs`.
|
||||
defp unquote_refs_once(guard, refs, module) do
|
||||
defp unquote_refs_once(guard, refs) do
|
||||
{guard, used_refs} =
|
||||
Macro.postwalk(guard, %{}, fn
|
||||
{ref, meta, context} = var, acc when is_atom(ref) and is_atom(context) ->
|
||||
@@ -374,8 +242,8 @@ defmodule Kernel.Utils do
|
||||
{new_var, acc}
|
||||
|
||||
%{} ->
|
||||
generated = String.to_atom("arg" <> Integer.to_string(map_size(acc) + 1))
|
||||
new_var = Macro.unique_var(generated, module)
|
||||
generated = String.to_atom("arg" <> Integer.to_string(map_size(acc)))
|
||||
new_var = Macro.var(generated, Elixir)
|
||||
{new_var, Map.put(acc, pair, {new_var, var})}
|
||||
end
|
||||
|
||||
|
||||
+210
-600
File diff suppressed because it is too large
Load Diff
+52
-224
@@ -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:
|
||||
|
||||
@@ -8,20 +21,13 @@ defmodule List do
|
||||
[1, "two", 3, :four]
|
||||
|
||||
Two lists can be concatenated and subtracted using the
|
||||
`++/2` and `--/2` operators:
|
||||
`Kernel.++/2` and `Kernel.--/2` operators:
|
||||
|
||||
iex> [1, 2, 3] ++ [4, 5, 6]
|
||||
[1, 2, 3, 4, 5, 6]
|
||||
iex> [1, true, 2, false, 3, true] -- [true, false]
|
||||
[1, 2, 3, true]
|
||||
|
||||
An element can be prepended to a list using `|`:
|
||||
|
||||
iex> new = 0
|
||||
iex> list = [1, 2, 3]
|
||||
iex> [new | list]
|
||||
[0, 1, 2, 3]
|
||||
|
||||
Lists in Elixir are effectively linked lists, which means
|
||||
they are internally represented in pairs containing the
|
||||
head and the tail of a list:
|
||||
@@ -63,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
|
||||
@@ -95,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()
|
||||
#=> [
|
||||
@@ -230,7 +212,7 @@ defmodule List do
|
||||
|
||||
@doc """
|
||||
Folds (reduces) the given list from the left with
|
||||
a function. Requires an accumulator, which can be any value.
|
||||
a function. Requires an accumulator.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -240,9 +222,6 @@ defmodule List do
|
||||
iex> List.foldl([1, 2, 3, 4], 0, fn x, acc -> x - acc end)
|
||||
2
|
||||
|
||||
iex> List.foldl([1, 2, 3], {0, 0}, fn x, {a1, a2} -> {a1 + x, a2 - x} end)
|
||||
{6, -6}
|
||||
|
||||
"""
|
||||
@spec foldl([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
|
||||
def foldl(list, acc, fun) when is_list(list) and is_function(fun) do
|
||||
@@ -251,16 +230,13 @@ defmodule List do
|
||||
|
||||
@doc """
|
||||
Folds (reduces) the given list from the right with
|
||||
a function. Requires an accumulator, which can be any value.
|
||||
a function. Requires an accumulator.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.foldr([1, 2, 3, 4], 0, fn x, acc -> x - acc end)
|
||||
-2
|
||||
|
||||
iex> List.foldr([1, 2, 3, 4], %{sum: 0, product: 1}, fn x, %{sum: a1, product: a2} -> %{sum: a1 + x, product: a2 * x} end)
|
||||
%{product: 24, sum: 10}
|
||||
|
||||
"""
|
||||
@spec foldr([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
|
||||
def foldr(list, acc, fun) when is_list(list) and is_function(fun) do
|
||||
@@ -268,18 +244,13 @@ defmodule List do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the first element in `list` or `default` if `list` is empty.
|
||||
|
||||
`first/2` has been introduced in Elixir v1.12.0, while `first/1` has been available since v1.0.0.
|
||||
Returns the first element in `list` or `nil` if `list` is empty.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.first([])
|
||||
nil
|
||||
|
||||
iex> List.first([], 1)
|
||||
1
|
||||
|
||||
iex> List.first([1])
|
||||
1
|
||||
|
||||
@@ -287,25 +258,19 @@ defmodule List do
|
||||
1
|
||||
|
||||
"""
|
||||
@spec first([], any) :: any
|
||||
@spec first([elem, ...], any) :: elem when elem: var
|
||||
def first(list, default \\ nil)
|
||||
def first([], default), do: default
|
||||
def first([head | _], _default), do: head
|
||||
@spec first([]) :: nil
|
||||
@spec first([elem, ...]) :: elem when elem: var
|
||||
def first([]), do: nil
|
||||
def first([head | _]), do: head
|
||||
|
||||
@doc """
|
||||
Returns the last element in `list` or `default` if `list` is empty.
|
||||
|
||||
`last/2` has been introduced in Elixir v1.12.0, while `last/1` has been available since v1.0.0.
|
||||
Returns the last element in `list` or `nil` if `list` is empty.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.last([])
|
||||
nil
|
||||
|
||||
iex> List.last([], 1)
|
||||
1
|
||||
|
||||
iex> List.last([1])
|
||||
1
|
||||
|
||||
@@ -313,13 +278,11 @@ defmodule List do
|
||||
3
|
||||
|
||||
"""
|
||||
@spec last([], any) :: any
|
||||
@spec last([elem, ...], any) :: elem when elem: var
|
||||
@compile {:inline, last: 2}
|
||||
def last(list, default \\ nil)
|
||||
def last([], default), do: default
|
||||
def last([head], _default), do: head
|
||||
def last([_ | tail], default), do: last(tail, default)
|
||||
@spec last([]) :: nil
|
||||
@spec last([elem, ...]) :: elem when elem: var
|
||||
def last([]), do: nil
|
||||
def last([head]), do: head
|
||||
def last([_ | tail]), do: last(tail)
|
||||
|
||||
@doc """
|
||||
Receives a list of tuples and returns the first tuple
|
||||
@@ -339,52 +302,12 @@ defmodule List do
|
||||
iex> List.keyfind([a: 1, b: 2], :c, 0)
|
||||
nil
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keyfind([{22, "SSH"}, {80, "HTTP"}], 22, 0)
|
||||
{22, "SSH"}
|
||||
|
||||
"""
|
||||
@spec keyfind([tuple], any, non_neg_integer, any) :: any
|
||||
def keyfind(list, key, position, default \\ nil) when is_integer(position) do
|
||||
def keyfind(list, key, position, default \\ nil) do
|
||||
:lists.keyfind(key, position + 1, list) || default
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives a list of tuples and returns the first tuple
|
||||
where the element at `position` in the tuple matches the
|
||||
given `key`.
|
||||
|
||||
If no matching tuple is found, an error is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.keyfind!([a: 1, b: 2], :a, 0)
|
||||
{:a, 1}
|
||||
|
||||
iex> List.keyfind!([a: 1, b: 2], 2, 1)
|
||||
{:b, 2}
|
||||
|
||||
iex> List.keyfind!([a: 1, b: 2], :c, 0)
|
||||
** (KeyError) key :c at position 0 not found in: [a: 1, b: 2]
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keyfind!([{22, "SSH"}, {80, "HTTP"}], 22, 0)
|
||||
{22, "SSH"}
|
||||
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec keyfind!([tuple], any, non_neg_integer) :: any
|
||||
def keyfind!(list, key, position) when is_integer(position) do
|
||||
:lists.keyfind(key, position + 1, list) ||
|
||||
raise KeyError,
|
||||
key: key,
|
||||
term: list,
|
||||
message:
|
||||
"key #{inspect(key)} at position #{inspect(position)} not found in: #{inspect(list)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives a list of tuples and returns `true` if there is
|
||||
a tuple where the element at `position` in the tuple matches
|
||||
@@ -401,14 +324,9 @@ defmodule List do
|
||||
iex> List.keymember?([a: 1, b: 2], :c, 0)
|
||||
false
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keymember?([{22, "SSH"}, {80, "HTTP"}], 22, 0)
|
||||
true
|
||||
|
||||
"""
|
||||
@spec keymember?([tuple], any, non_neg_integer) :: boolean
|
||||
def keymember?(list, key, position) when is_integer(position) do
|
||||
def keymember?(list, key, position) do
|
||||
:lists.keymember(key, position + 1, list)
|
||||
end
|
||||
|
||||
@@ -424,26 +342,15 @@ defmodule List do
|
||||
iex> List.keyreplace([a: 1, b: 2], :a, 1, {:a, 3})
|
||||
[a: 1, b: 2]
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keyreplace([{22, "SSH"}, {80, "HTTP"}], 22, 0, {22, "Secure Shell"})
|
||||
[{22, "Secure Shell"}, {80, "HTTP"}]
|
||||
|
||||
"""
|
||||
@spec keyreplace([tuple], any, non_neg_integer, tuple) :: [tuple]
|
||||
def keyreplace(list, key, position, new_tuple) when is_integer(position) do
|
||||
def keyreplace(list, key, position, new_tuple) do
|
||||
:lists.keyreplace(key, position + 1, list, new_tuple)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives a list of tuples and sorts the elements
|
||||
at `position` of the tuples.
|
||||
|
||||
The sort is stable.
|
||||
|
||||
A `sorter` argument is available since Elixir v1.14.0. Similar to
|
||||
`Enum.sort/2`, the sorter can be an anonymous function, the atoms
|
||||
`:asc` or `:desc`, or module that implements a compare function.
|
||||
at `position` of the tuples. The sort is stable.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -453,69 +360,12 @@ defmodule List do
|
||||
iex> List.keysort([a: 5, c: 1, b: 3], 0)
|
||||
[a: 5, b: 3, c: 1]
|
||||
|
||||
To sort in descending order:
|
||||
|
||||
iex> List.keysort([a: 5, c: 1, b: 3], 0, :desc)
|
||||
[c: 1, b: 3, a: 5]
|
||||
|
||||
As in `Enum.sort/2`, avoid using the default sorting function to sort
|
||||
structs, as by default it performs structural comparison instead of a
|
||||
semantic one. In such cases, you shall pass a sorting function as third
|
||||
element or any module that implements a `compare/2` function. For example,
|
||||
if you have tuples with user names and their birthday, and you want to
|
||||
sort on their birthday, in both ascending and descending order, you should
|
||||
do:
|
||||
|
||||
iex> users = [
|
||||
...> {"Ellis", ~D[1943-05-11]},
|
||||
...> {"Lovelace", ~D[1815-12-10]},
|
||||
...> {"Turing", ~D[1912-06-23]}
|
||||
...> ]
|
||||
iex> List.keysort(users, 1, Date)
|
||||
[
|
||||
{"Lovelace", ~D[1815-12-10]},
|
||||
{"Turing", ~D[1912-06-23]},
|
||||
{"Ellis", ~D[1943-05-11]}
|
||||
]
|
||||
iex> List.keysort(users, 1, {:desc, Date})
|
||||
[
|
||||
{"Ellis", ~D[1943-05-11]},
|
||||
{"Turing", ~D[1912-06-23]},
|
||||
{"Lovelace", ~D[1815-12-10]}
|
||||
]
|
||||
|
||||
"""
|
||||
@doc since: "1.14.0"
|
||||
@spec keysort(
|
||||
[tuple],
|
||||
non_neg_integer,
|
||||
(any, any -> boolean) | :asc | :desc | module() | {:asc | :desc, module()}
|
||||
) :: [tuple]
|
||||
def keysort(list, position, sorter \\ :asc)
|
||||
|
||||
def keysort(list, position, :asc) when is_list(list) and is_integer(position) do
|
||||
@spec keysort([tuple], non_neg_integer) :: [tuple]
|
||||
def keysort(list, position) do
|
||||
:lists.keysort(position + 1, list)
|
||||
end
|
||||
|
||||
def keysort(list, position, sorter) when is_list(list) and is_integer(position) do
|
||||
:lists.sort(keysort_fun(sorter, position + 1), list)
|
||||
end
|
||||
|
||||
defp keysort_fun(sorter, position) when is_function(sorter, 2),
|
||||
do: &sorter.(:erlang.element(position, &1), :erlang.element(position, &2))
|
||||
|
||||
defp keysort_fun(:desc, position),
|
||||
do: &(:erlang.element(position, &1) >= :erlang.element(position, &2))
|
||||
|
||||
defp keysort_fun(module, position) when is_atom(module),
|
||||
do: &(module.compare(:erlang.element(position, &1), :erlang.element(position, &2)) != :gt)
|
||||
|
||||
defp keysort_fun({:asc, module}, position) when is_atom(module),
|
||||
do: &(module.compare(:erlang.element(position, &1), :erlang.element(position, &2)) != :gt)
|
||||
|
||||
defp keysort_fun({:desc, module}, position) when is_atom(module),
|
||||
do: &(module.compare(:erlang.element(position, &1), :erlang.element(position, &2)) != :lt)
|
||||
|
||||
@doc """
|
||||
Receives a `list` of tuples and replaces the element
|
||||
identified by `key` at `position` with `new_tuple`.
|
||||
@@ -530,14 +380,9 @@ defmodule List do
|
||||
iex> List.keystore([a: 1, b: 2], :c, 0, {:c, 3})
|
||||
[a: 1, b: 2, c: 3]
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keystore([{22, "SSH"}], 80, 0, {80, "HTTP"})
|
||||
[{22, "SSH"}, {80, "HTTP"}]
|
||||
|
||||
"""
|
||||
@spec keystore([tuple], any, non_neg_integer, tuple) :: [tuple, ...]
|
||||
def keystore(list, key, position, new_tuple) when is_integer(position) do
|
||||
def keystore(list, key, position, new_tuple) do
|
||||
:lists.keystore(key, position + 1, list, new_tuple)
|
||||
end
|
||||
|
||||
@@ -557,14 +402,9 @@ defmodule List do
|
||||
iex> List.keydelete([a: 1, b: 2], :c, 0)
|
||||
[a: 1, b: 2]
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keydelete([{22, "SSH"}, {80, "HTTP"}], 80, 0)
|
||||
[{22, "SSH"}]
|
||||
|
||||
"""
|
||||
@spec keydelete([tuple], any, non_neg_integer) :: [tuple]
|
||||
def keydelete(list, key, position) when is_integer(position) do
|
||||
def keydelete(list, key, position) do
|
||||
:lists.keydelete(key, position + 1, list)
|
||||
end
|
||||
|
||||
@@ -586,14 +426,9 @@ defmodule List do
|
||||
iex> List.keytake([a: 1, b: 2], :c, 0)
|
||||
nil
|
||||
|
||||
This function works for any list of tuples:
|
||||
|
||||
iex> List.keytake([{22, "SSH"}, {80, "HTTP"}], 80, 0)
|
||||
{{80, "HTTP"}, [{22, "SSH"}]}
|
||||
|
||||
"""
|
||||
@spec keytake([tuple], any, non_neg_integer) :: {tuple, [tuple]} | nil
|
||||
def keytake(list, key, position) when is_integer(position) do
|
||||
def keytake(list, key, position) do
|
||||
case :lists.keytake(key, position + 1, list) do
|
||||
{:value, element, list} -> {element, list}
|
||||
false -> nil
|
||||
@@ -947,22 +782,14 @@ defmodule List do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a charlist to an existing atom.
|
||||
Converts a charlist to an existing atom. Raises an `ArgumentError`
|
||||
if the atom does not exist.
|
||||
|
||||
Elixir supports conversions from charlists which contains any Unicode
|
||||
code point. Raises an `ArgumentError` if the atom does not exist.
|
||||
code point.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
> #### Atoms and modules {: .info}
|
||||
>
|
||||
> Since Elixir is a compiled language, the atoms defined in a module
|
||||
> will only exist after said module is loaded, which typically happens
|
||||
> whenever a function in the module is executed. Therefore, it is
|
||||
> generally recommended to call `List.to_existing_atom/1` only to
|
||||
> convert atoms defined within the module making the function call
|
||||
> to `to_existing_atom/1`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> _ = :my_atom
|
||||
@@ -973,6 +800,9 @@ defmodule List do
|
||||
iex> List.to_existing_atom('🌢 Elixir')
|
||||
:"🌢 Elixir"
|
||||
|
||||
iex> List.to_existing_atom('this_atom_will_never_exist')
|
||||
** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec to_existing_atom(charlist) :: atom
|
||||
def to_existing_atom(charlist) do
|
||||
@@ -1016,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)
|
||||
@@ -1056,9 +884,9 @@ 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
|
||||
the [`:binary` module](`:binary`).
|
||||
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
|
||||
|
||||
@@ -1108,12 +936,12 @@ 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
|
||||
the [`:binary` module](`:binary`).
|
||||
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
|
||||
|
||||
|
||||
+182
-1268
File diff suppressed because it is too large
Load Diff
+89
-192
@@ -21,97 +21,106 @@ defmodule Macro.Env do
|
||||
|
||||
It contains the following fields:
|
||||
|
||||
* `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
|
||||
* `file` - the current absolute file name as a binary
|
||||
* `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
|
||||
* `line` - the current line as an integer
|
||||
* `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`:
|
||||
|
||||
* `aliases`
|
||||
* `functions`
|
||||
* `macro_aliases`
|
||||
* `macros`
|
||||
* `lexical_tracker`
|
||||
* `requires`
|
||||
* `tracers`
|
||||
* `versioned_vars`
|
||||
* `current_vars`
|
||||
* `unused_vars`
|
||||
* `prematch_vars`
|
||||
* `contextual_vars`
|
||||
|
||||
The following fields are deprecated and must not be accessed or relied on:
|
||||
|
||||
* `vars` - a list keeping all defined variables as `{var, context}`
|
||||
|
||||
"""
|
||||
|
||||
@type context :: :match | :guard | nil
|
||||
@type context_modules :: [module]
|
||||
@type name_arity :: {atom, arity}
|
||||
@type file :: binary
|
||||
@type line :: non_neg_integer
|
||||
@type name_arity :: {atom, arity}
|
||||
@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 aliases :: [{module, module}]
|
||||
@typep functions :: [{module, [name_arity]}]
|
||||
@typep lexical_tracker :: pid | nil
|
||||
@typep macro_aliases :: [{module, {term, module}}]
|
||||
@typep macros :: [{module, [name_arity]}]
|
||||
@typep requires :: [module]
|
||||
@typep tracers :: [module]
|
||||
@typep versioned_vars :: %{optional(variable) => var_version :: non_neg_integer}
|
||||
@typep vars :: [variable]
|
||||
@typep var_type :: :term
|
||||
@typep var_version :: non_neg_integer
|
||||
@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,
|
||||
module: atom,
|
||||
file: file,
|
||||
function: name_arity | nil,
|
||||
functions: functions,
|
||||
lexical_tracker: lexical_tracker,
|
||||
line: line,
|
||||
macro_aliases: macro_aliases,
|
||||
macros: macros,
|
||||
module: module,
|
||||
function: name_arity | nil,
|
||||
context: context,
|
||||
requires: requires,
|
||||
tracers: tracers,
|
||||
versioned_vars: versioned_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
|
||||
}
|
||||
|
||||
fields = [
|
||||
aliases: [],
|
||||
context: nil,
|
||||
context_modules: [],
|
||||
file: "nofile",
|
||||
function: nil,
|
||||
functions: [],
|
||||
lexical_tracker: nil,
|
||||
line: 0,
|
||||
macro_aliases: [],
|
||||
macros: [],
|
||||
module: nil,
|
||||
requires: [],
|
||||
tracers: [],
|
||||
versioned_vars: %{}
|
||||
]
|
||||
# TODO: Remove :vars field on v2.0
|
||||
def __struct__ do
|
||||
%{
|
||||
__struct__: __MODULE__,
|
||||
module: nil,
|
||||
file: "nofile",
|
||||
line: 0,
|
||||
function: nil,
|
||||
context: nil,
|
||||
requires: [],
|
||||
aliases: [],
|
||||
functions: [],
|
||||
macros: [],
|
||||
macro_aliases: [],
|
||||
context_modules: [],
|
||||
vars: [],
|
||||
unused_vars: %{},
|
||||
current_vars: %{},
|
||||
prematch_vars: :warn,
|
||||
lexical_tracker: nil,
|
||||
contextual_vars: []
|
||||
}
|
||||
end
|
||||
|
||||
# Define the __struct__ callbacks by hand for bootstrap reasons.
|
||||
{struct, [], kv, body} = Kernel.Utils.defstruct(__MODULE__, fields, false)
|
||||
def __struct__(), do: unquote(:elixir_quote.escape(struct, false, :none))
|
||||
def __struct__(unquote(kv)), do: unquote(body)
|
||||
|
||||
@doc """
|
||||
Prunes compile information from the environment.
|
||||
|
||||
This happens when the environment is captured at compilation
|
||||
time, for example, in the module body, and then used to
|
||||
evaluate code after the module has been defined.
|
||||
"""
|
||||
@doc since: "1.14.0"
|
||||
@spec prune_compile_info(t) :: t
|
||||
def prune_compile_info(env) do
|
||||
%{env | lexical_tracker: nil, tracers: []}
|
||||
def __struct__(kv) do
|
||||
Enum.reduce(kv, __struct__(), fn {k, v}, acc -> :maps.update(k, v, acc) end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -126,30 +135,19 @@ defmodule Macro.Env do
|
||||
@spec vars(t) :: [variable]
|
||||
def vars(env)
|
||||
|
||||
def vars(%{__struct__: Macro.Env, versioned_vars: vars}) do
|
||||
Map.keys(vars)
|
||||
def vars(%{__struct__: Macro.Env, current_vars: current_vars}) do
|
||||
Map.keys(current_vars)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if a variable belongs to the environment.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> x = 13
|
||||
iex> x
|
||||
13
|
||||
iex> Macro.Env.has_var?(__ENV__, {:x, nil})
|
||||
true
|
||||
iex> Macro.Env.has_var?(__ENV__, {:unknown, nil})
|
||||
false
|
||||
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec has_var?(t, variable) :: boolean()
|
||||
def has_var?(env, var)
|
||||
|
||||
def has_var?(%{__struct__: Macro.Env, versioned_vars: vars}, var) do
|
||||
Map.has_key?(vars, var)
|
||||
def has_var?(%{__struct__: Macro.Env, current_vars: current_vars}, var) do
|
||||
Map.has_key?(current_vars, var)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -163,117 +161,16 @@ defmodule Macro.Env do
|
||||
[file: file, line: line]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Fetches the alias for the given atom.
|
||||
|
||||
Returns `{:ok, alias}` if the alias exists, `:error`
|
||||
otherwise.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> alias Foo.Bar, as: Baz
|
||||
iex> Baz
|
||||
Foo.Bar
|
||||
iex> Macro.Env.fetch_alias(__ENV__, :Baz)
|
||||
{:ok, Foo.Bar}
|
||||
iex> Macro.Env.fetch_alias(__ENV__, :Unknown)
|
||||
:error
|
||||
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec fetch_alias(t, atom) :: {:ok, atom} | :error
|
||||
def fetch_alias(%{__struct__: Macro.Env, aliases: aliases}, atom) when is_atom(atom),
|
||||
do: Keyword.fetch(aliases, :"Elixir.#{atom}")
|
||||
|
||||
@doc """
|
||||
Fetches the macro alias for the given atom.
|
||||
|
||||
Returns `{:ok, macro_alias}` if the alias exists, `:error`
|
||||
otherwise.
|
||||
|
||||
A macro alias is only used inside quoted expansion. See
|
||||
`fetch_alias/2` for a more general example.
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec fetch_macro_alias(t, atom) :: {:ok, atom} | :error
|
||||
def fetch_macro_alias(%{__struct__: Macro.Env, macro_aliases: aliases}, atom)
|
||||
when is_atom(atom),
|
||||
do: Keyword.fetch(aliases, :"Elixir.#{atom}")
|
||||
|
||||
@doc """
|
||||
Returns the modules from which the given `{name, arity}` was
|
||||
imported.
|
||||
|
||||
It returns a list of two element tuples in the shape of
|
||||
`{:function | :macro, module}`. The elements in the list
|
||||
are in no particular order and the order is not guaranteed.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Macro.Env.lookup_import(__ENV__, {:duplicate, 2})
|
||||
[]
|
||||
iex> import Tuple, only: [duplicate: 2], warn: false
|
||||
iex> Macro.Env.lookup_import(__ENV__, {:duplicate, 2})
|
||||
[{:function, Tuple}]
|
||||
iex> import List, only: [duplicate: 2], warn: false
|
||||
iex> Macro.Env.lookup_import(__ENV__, {:duplicate, 2})
|
||||
[{:function, List}, {:function, Tuple}]
|
||||
|
||||
iex> Macro.Env.lookup_import(__ENV__, {:def, 1})
|
||||
[{:macro, Kernel}]
|
||||
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec lookup_import(t, name_arity) :: [{:function | :macro, module}]
|
||||
def lookup_import(
|
||||
%{__struct__: Macro.Env, functions: functions, macros: macros},
|
||||
{name, arity} = pair
|
||||
)
|
||||
when is_atom(name) and is_integer(arity) do
|
||||
f = for {mod, pairs} <- functions, :ordsets.is_element(pair, pairs), do: {:function, mod}
|
||||
m = for {mod, pairs} <- macros, :ordsets.is_element(pair, pairs), do: {:macro, mod}
|
||||
f ++ m
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns true if the given module has been required.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Macro.Env.required?(__ENV__, Integer)
|
||||
false
|
||||
iex> require Integer
|
||||
iex> Macro.Env.required?(__ENV__, Integer)
|
||||
true
|
||||
|
||||
iex> Macro.Env.required?(__ENV__, Kernel)
|
||||
true
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec required?(t, module) :: boolean
|
||||
def required?(%{__struct__: Macro.Env, requires: requires}, mod) when is_atom(mod),
|
||||
do: mod in requires
|
||||
|
||||
@doc """
|
||||
Prepend a tracer to the list of tracers in the environment.
|
||||
|
||||
## Examples
|
||||
|
||||
Macro.Env.prepend_tracer(__ENV__, MyCustomTracer)
|
||||
|
||||
"""
|
||||
@doc since: "1.13.0"
|
||||
@spec prepend_tracer(t, module) :: t
|
||||
def prepend_tracer(%{__struct__: Macro.Env, tracers: tracers} = env, tracer) do
|
||||
%{env | tracers: [tracer | tracers]}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a `Macro.Env` in the match context.
|
||||
"""
|
||||
@spec to_match(t) :: t
|
||||
def to_match(%{__struct__: Macro.Env} = env) do
|
||||
%{env | context: :match}
|
||||
def to_match(%{__struct__: Macro.Env, context: :match} = env) do
|
||||
env
|
||||
end
|
||||
|
||||
def to_match(%{__struct__: Macro.Env, current_vars: vars} = env) do
|
||||
%{env | context: :match, prematch_vars: vars}
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user