Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98485daab0 | ||
|
|
59f47949a9 | ||
|
|
fca5f1cf73 | ||
|
|
153ec434de | ||
|
|
061a989935 | ||
|
|
21f10f7296 | ||
|
|
336452f81b | ||
|
|
511a51ba89 | ||
|
|
7e4f9c5647 | ||
|
|
b37ecb0f8e | ||
|
|
ac947a5d1d | ||
|
|
82a511aafe | ||
|
|
7c2e65f418 | ||
|
|
3d04cb0aa0 | ||
|
|
8fa9d728f1 | ||
|
|
2eee2fc6a4 | ||
|
|
b1a10f2bb8 | ||
|
|
dcb4f22af2 | ||
|
|
6ba4cf00ab | ||
|
|
3eeded089d | ||
|
|
f4c827b68c | ||
|
|
9ef89241ed | ||
|
|
49351886cf | ||
|
|
9c7edf3117 | ||
|
|
32825ebaa0 | ||
|
|
5e715aa16e | ||
|
|
9b54efb9dd | ||
|
|
82182818cb | ||
|
|
53f16f5a82 | ||
|
|
d86751501f | ||
|
|
906df8c981 | ||
|
|
04717e4c19 | ||
|
|
a3e313b582 | ||
|
|
a4044d898d | ||
|
|
b932a52d55 | ||
|
|
8d269932a6 | ||
|
|
c1c4b1ace9 | ||
|
|
e284007968 | ||
|
|
b6ef2bd656 | ||
|
|
12b0906d61 | ||
|
|
2b59405756 | ||
|
|
4231a62c67 | ||
|
|
35e7c8c38c | ||
|
|
8e4d718b93 | ||
|
|
3ad9193b4b | ||
|
|
d655a2884e | ||
|
|
5529c5fa4e | ||
|
|
2d139352bb | ||
|
|
5ce4b61991 | ||
|
|
bd6f2ebe9a | ||
|
|
7634f3f4c9 | ||
|
|
6322c38918 | ||
|
|
d48207555a | ||
|
|
da561ca876 | ||
|
|
f702f932a2 | ||
|
|
b3f59d9f9c | ||
|
|
24ff3df592 | ||
|
|
fb97713bce | ||
|
|
3f6dd0b321 | ||
|
|
ec2e092fdd | ||
|
|
649540193b | ||
|
|
dadb412cef | ||
|
|
93ceb95e76 | ||
|
|
85ca87f1ed | ||
|
|
f244ee310f | ||
|
|
bd37919247 | ||
|
|
60b16a56fe | ||
|
|
151c7fc459 | ||
|
|
31e177d0aa | ||
|
|
b6b99ea2ef | ||
|
|
bb5a66698c | ||
|
|
1492ceb27f | ||
|
|
55ead12b0a | ||
|
|
95934e56c4 | ||
|
|
51187a3acb | ||
|
|
f43d9095e9 | ||
|
|
5c35c37768 | ||
|
|
4e7c652db3 | ||
|
|
1752db52c3 | ||
|
|
886f871afb | ||
|
|
f7935d9351 | ||
|
|
d5c5e7eb5f | ||
|
|
94252f7f63 | ||
|
|
9e3903e293 | ||
|
|
eec32b45d1 | ||
|
|
499446737e | ||
|
|
ca1bc6c3da | ||
|
|
f55ce7c39e | ||
|
|
7e5d20ac05 | ||
|
|
f2d1b4209b | ||
|
|
a6139bc2c0 | ||
|
|
5378cf21ef | ||
|
|
1c03026d80 | ||
|
|
af3203cb26 | ||
|
|
ee5a7fa0a4 | ||
|
|
7c2f4663b0 | ||
|
|
9950587f19 | ||
|
|
0cc21e36b2 | ||
|
|
5f3e1217bf | ||
|
|
80e0a95f8f | ||
|
|
ec61cdbf0b | ||
|
|
f905d98a3f | ||
|
|
2e576f67a0 | ||
|
|
ddac6057c6 | ||
|
|
1904fe0fb0 | ||
|
|
c8c3314338 | ||
|
|
23259a2f1e | ||
|
|
1af53ac3f8 | ||
|
|
aa111f806d | ||
|
|
dde98ccd86 | ||
|
|
55954483d5 | ||
|
|
39ed9a3ae0 | ||
|
|
ebf7177438 | ||
|
|
fad027f029 | ||
|
|
2b55113978 | ||
|
|
b8a09a5c4d | ||
|
|
00a67e3eea | ||
|
|
edd2c6f780 | ||
|
|
74d23f2a38 | ||
|
|
ca003415f2 | ||
|
|
badc709713 | ||
|
|
e1b84b4cfe | ||
|
|
f83fb2e7e3 | ||
|
|
7d969b975a | ||
|
|
1c502f9f4d | ||
|
|
0424431e55 | ||
|
|
9d9d730f5f | ||
|
|
c9ef9333df | ||
|
|
becd5d3aab | ||
|
|
b14dee3d6e | ||
|
|
bb09c7fef3 | ||
|
|
122dcbe90c | ||
|
|
db9314374d | ||
|
|
123cc6f884 | ||
|
|
ae644808dd | ||
|
|
29d775dfa7 | ||
|
|
718263f823 | ||
|
|
456aae7b63 | ||
|
|
515e98fc8b | ||
|
|
741ff046b7 | ||
|
|
690bc55f31 | ||
|
|
d5294657c4 | ||
|
|
f15e0556f3 | ||
|
|
94ae99a811 | ||
|
|
9ff2a51f49 | ||
|
|
721358cef0 | ||
|
|
8e08b3c16e | ||
|
|
f75b3dc846 | ||
|
|
a725b39c72 | ||
|
|
918c7cea5d | ||
|
|
0fe1964898 | ||
|
|
e89e9d874b | ||
|
|
d993efe4bd | ||
|
|
5c45c222a8 | ||
|
|
83c0075201 | ||
|
|
0e8cd17043 | ||
|
|
32920f5d2e | ||
|
|
63fabc44b5 | ||
|
|
e3ec5c3c36 | ||
|
|
bfb27257e7 | ||
|
|
d1e3e4dafd | ||
|
|
e1ee8d134e | ||
|
|
e1c5b2a71f | ||
|
|
d58340d7ab | ||
|
|
3a3d68385e | ||
|
|
6bc8d50e57 | ||
|
|
aef81d1aad | ||
|
|
7f4756d401 | ||
|
|
6c132b9078 | ||
|
|
08b807f7e2 | ||
|
|
725a36f14d | ||
|
|
40a589af9d | ||
|
|
6c2dfed036 | ||
|
|
774a9baa93 | ||
|
|
b8b1a4ba8a | ||
|
|
929e58ca0e | ||
|
|
b8e71290d3 | ||
|
|
43a4dca94a | ||
|
|
6988f05180 | ||
|
|
28522ccb89 | ||
|
|
485c1efef0 | ||
|
|
616263f9de | ||
|
|
7f771a4f3d | ||
|
|
592c9ca9fb | ||
|
|
c47168948b | ||
|
|
1c914f13f3 | ||
|
|
ac24df8625 | ||
|
|
7f820b2bb3 | ||
|
|
9610b2bd46 | ||
|
|
2d97460ef8 | ||
|
|
8ed9910b2a | ||
|
|
84056459f7 | ||
|
|
1967a06abe | ||
|
|
e0ae5fba53 | ||
|
|
20d6f3d053 | ||
|
|
ac9e64382a | ||
|
|
38aaa43cfe | ||
|
|
d14f04c950 | ||
|
|
95bf439828 | ||
|
|
53efdd48a6 | ||
|
|
0e103381db | ||
|
|
eafb85eb90 | ||
|
|
38f35fd448 | ||
|
|
f63e7200a6 | ||
|
|
d24ff660cd | ||
|
|
17212e5867 | ||
|
|
8e73f5e03d | ||
|
|
bbaf2c513c | ||
|
|
e78f4e9a65 | ||
|
|
795dc44b29 | ||
|
|
687c50c42a | ||
|
|
2d19ae4640 | ||
|
|
4e8b13e15b | ||
|
|
2e5b941a34 | ||
|
|
749d89139c | ||
|
|
64adfcce6e | ||
|
|
d955fcf518 | ||
|
|
0afc3dde2a | ||
|
|
04372bf118 | ||
|
|
f01de95cb2 | ||
|
|
37149511c3 | ||
|
|
3e0f3b47cf | ||
|
|
6c4d359b1a | ||
|
|
a0b3c08eb8 | ||
|
|
cfeb0c9bc9 | ||
|
|
94d736d064 | ||
|
|
b598afa769 | ||
|
|
5396a8b6b6 | ||
|
|
74f864dd3c | ||
|
|
c5a5079337 | ||
|
|
865064fbdd | ||
|
|
30a3fe7783 | ||
|
|
9f2a2c0042 | ||
|
|
e4a6784cb2 | ||
|
|
6b99ed9d00 | ||
|
|
3b61d2dd9d | ||
|
|
de9207895b | ||
|
|
7aa3918885 | ||
|
|
f9b9aaae9a | ||
|
|
2a2efb6fe0 | ||
|
|
bd9ac87d07 | ||
|
|
0f2c3a62fa | ||
|
|
5a973b92b0 | ||
|
|
b95cea5345 | ||
|
|
a9db45208b | ||
|
|
2ccd487bcf | ||
|
|
796d90ee25 | ||
|
|
6ad2109a6c | ||
|
|
9e8c4f472b | ||
|
|
9abc570d59 | ||
|
|
c190f09d5c | ||
|
|
9adf48aa62 | ||
|
|
8048877b04 | ||
|
|
83519a33cd | ||
|
|
382cde475b | ||
|
|
4bceca4583 | ||
|
|
f702b0dc4f | ||
|
|
65d2e033fa | ||
|
|
8c373044dc | ||
|
|
82e225060a | ||
|
|
8daec24b8f | ||
|
|
2f71726757 | ||
|
|
278993ee0a | ||
|
|
91a4f2bae9 | ||
|
|
8eca8d3900 | ||
|
|
a9b6543e5b | ||
|
|
4e3e6428b5 | ||
|
|
955285e99d | ||
|
|
7cab1564bf | ||
|
|
52ac93dbf5 | ||
|
|
1a7df52c4d | ||
|
|
6a9dd90bfb | ||
|
|
d774250579 | ||
|
|
a92391d4e5 | ||
|
|
4b62a8695b | ||
|
|
53ebafb8a4 | ||
|
|
94e5c42a77 | ||
|
|
4a5bcaaa8e | ||
|
|
ca8ce9201a | ||
|
|
2c83d31c9b | ||
|
|
68b3a58d75 | ||
|
|
b20bf5a0d4 | ||
|
|
4f5be0072b | ||
|
|
e5001a297b | ||
|
|
68c45f806a | ||
|
|
a344b5c9f5 | ||
|
|
ef723285d5 | ||
|
|
c88137330e | ||
|
|
5ff092afea | ||
|
|
c483c9c0ab | ||
|
|
1ca25436be | ||
|
|
a35609bbb9 | ||
|
|
67b7ffce61 | ||
|
|
159e9655d5 | ||
|
|
aa15ccd9fa | ||
|
|
2122babdcb | ||
|
|
741dfda9f4 | ||
|
|
58fb5c122c | ||
|
|
57b71953c1 | ||
|
|
2e073f6ad3 | ||
|
|
1c77a05027 | ||
|
|
afdd94d254 | ||
|
|
e1e096ab2e | ||
|
|
97ac0e6a9f | ||
|
|
3fcc9241db | ||
|
|
caeda3d14b | ||
|
|
f1c8eb8f34 | ||
|
|
25873f0f29 | ||
|
|
bbcc42c5cf | ||
|
|
76ea515fd2 | ||
|
|
eb069dd43b | ||
|
|
e6bd1adaf2 | ||
|
|
d6b4a6aca9 | ||
|
|
4d2f4865fe | ||
|
|
4385ae9df1 | ||
|
|
e0d1c2e4ca | ||
|
|
9e302cbd01 | ||
|
|
7e0960b37e | ||
|
|
80ce444194 | ||
|
|
355b2ce349 | ||
|
|
9f8f5d533d | ||
|
|
0d449ad364 | ||
|
|
a71f8311cb | ||
|
|
de89e2d027 | ||
|
|
13ced80fcd | ||
|
|
7b17320f10 | ||
|
|
1ca791fa86 | ||
|
|
40180f0f4a | ||
|
|
979969c9a5 | ||
|
|
f332273228 | ||
|
|
57c2912809 | ||
|
|
a80b4f1edd | ||
|
|
050f10e849 | ||
|
|
fad27bacab | ||
|
|
582108e17a | ||
|
|
7ff04105b7 | ||
|
|
268bd890d6 | ||
|
|
d612f20c7d | ||
|
|
bd7f914075 | ||
|
|
d3daa11a11 | ||
|
|
dae654b30b | ||
|
|
0429cdd95f | ||
|
|
ca1c178612 | ||
|
|
6b5c167d23 | ||
|
|
398a39edb6 | ||
|
|
2ea8a7d1f8 | ||
|
|
967fba4f79 | ||
|
|
1f8474f23d | ||
|
|
81141d4527 | ||
|
|
786fcff385 | ||
|
|
8c5b5bd0fb | ||
|
|
a40d86f51d | ||
|
|
cf5707b9cf | ||
|
|
92a6ceafab | ||
|
|
9a8df5326d | ||
|
|
cd439540fc | ||
|
|
fbb41695d7 | ||
|
|
3d9d799a91 | ||
|
|
e54a23494b | ||
|
|
5f81bead72 | ||
|
|
f7184fbfe4 | ||
|
|
f99fa2fefc | ||
|
|
67dbfe39d1 | ||
|
|
ae108c110a | ||
|
|
624608e775 | ||
|
|
ee8bac10b1 | ||
|
|
2c5b3c8c36 | ||
|
|
b6fa56061a | ||
|
|
595171d2cf | ||
|
|
463ae2d827 | ||
|
|
c5a22aced0 | ||
|
|
704ecfd468 | ||
|
|
b59d280a79 | ||
|
|
bab91a7857 | ||
|
|
f103853f43 | ||
|
|
9d105ba4d6 | ||
|
|
8b101aeb4f | ||
|
|
de42c4cf20 | ||
|
|
af15f85bde | ||
|
|
ac4bb894f2 | ||
|
|
3c8466dee5 | ||
|
|
746e959b24 | ||
|
|
52016d806f | ||
|
|
cdd9dae8b4 | ||
|
|
3879ef03d0 | ||
|
|
c76c5d6d18 | ||
|
|
59cc525db4 | ||
|
|
ea76fe8224 | ||
|
|
fa2fda8462 | ||
|
|
a18f7df758 | ||
|
|
ba0ef91ea9 | ||
|
|
9f266be993 | ||
|
|
e4e4972238 | ||
|
|
73c59a079d | ||
|
|
81fa99d1bf | ||
|
|
938acec95f | ||
|
|
10ceadb448 | ||
|
|
8b7640fdae | ||
|
|
39ea08c487 | ||
|
|
23c1f49579 | ||
|
|
a4ab18831b | ||
|
|
2cb058ba32 | ||
|
|
1ec33d9119 | ||
|
|
f59712d330 | ||
|
|
ffe8272839 | ||
|
|
434aaa8c7d | ||
|
|
c744d0be1c | ||
|
|
caf62d5355 | ||
|
|
831d4fb8f0 | ||
|
|
36718cb41b | ||
|
|
93a3699451 | ||
|
|
43f641aa76 | ||
|
|
f3c610e921 | ||
|
|
804a5f04a6 | ||
|
|
2e863c1d89 | ||
|
|
ee737d5426 | ||
|
|
19464f0c8a | ||
|
|
caced90f52 | ||
|
|
5e16150b88 | ||
|
|
6d4c581cf2 | ||
|
|
df683c1d72 | ||
|
|
495d1646b2 | ||
|
|
4f84f1bf2f | ||
|
|
34677c657f | ||
|
|
258962fc1c | ||
|
|
1a787b5e2d | ||
|
|
2e222ee724 | ||
|
|
9e8ea409a9 | ||
|
|
f07e08c3b1 | ||
|
|
caf670b4e8 | ||
|
|
78ed8a55a3 | ||
|
|
5866b9da5c | ||
|
|
27371bcbf7 | ||
|
|
f9d9a60bc6 | ||
|
|
043ff05493 | ||
|
|
827f86b19c | ||
|
|
b37220ccfa | ||
|
|
d0f65af870 | ||
|
|
d440cebbed | ||
|
|
1c9be51dc3 | ||
|
|
7fba39dfe0 | ||
|
|
52f1069d91 | ||
|
|
4db416097d | ||
|
|
28b3b23b45 | ||
|
|
ae6668f846 | ||
|
|
ee05f3fce6 | ||
|
|
6cf4d8b447 | ||
|
|
1e9446a2bb | ||
|
|
c4427d725b | ||
|
|
261b124c6b | ||
|
|
91027cd925 | ||
|
|
a2d81db23b | ||
|
|
887e8f2633 | ||
|
|
84ab680704 | ||
|
|
7a3cf8551f | ||
|
|
74b6e2b9ff | ||
|
|
c40c56cf43 | ||
|
|
3f941139c4 | ||
|
|
d76f150274 | ||
|
|
f2415dd06c | ||
|
|
9196078b5c | ||
|
|
068ce0b89b | ||
|
|
02d9b4fbcc | ||
|
|
ef1091b116 | ||
|
|
b60df31267 | ||
|
|
c096508f37 | ||
|
|
ce625fec42 | ||
|
|
bd3aaa6933 | ||
|
|
c7ee3edfcb | ||
|
|
103502354c | ||
|
|
f40f21195a | ||
|
|
f40b705db4 | ||
|
|
90858867e7 | ||
|
|
9c3f23be36 | ||
|
|
2d7bd055ed | ||
|
|
c9a3c6ca6d | ||
|
|
9ad0438b9f | ||
|
|
f9d139872d | ||
|
|
76c144aa26 | ||
|
|
5b45b704ce | ||
|
|
0f60d8a4bb | ||
|
|
d4fbff4dd5 | ||
|
|
b321995265 | ||
|
|
0eb47ecf46 | ||
|
|
f45d4eb116 | ||
|
|
34aa35d016 | ||
|
|
fa60b71783 | ||
|
|
2aec8e7059 | ||
|
|
a4d1e651a5 | ||
|
|
233341699d | ||
|
|
a515478b4f | ||
|
|
489f202938 | ||
|
|
36d446a8b5 | ||
|
|
ffb931a5ac | ||
|
|
72e642634d | ||
|
|
c6c508a99a | ||
|
|
e7b6a3e020 | ||
|
|
791e69aa34 | ||
|
|
4d7003e760 | ||
|
|
c85419fda7 | ||
|
|
ae9a5ce261 | ||
|
|
6d0f78d3bd | ||
|
|
cf0a5df7a7 | ||
|
|
b49d7c6d0b | ||
|
|
72d9f79e42 | ||
|
|
691460a6e6 | ||
|
|
3803712e0a | ||
|
|
656ecdf5ef | ||
|
|
335cfdbcad | ||
|
|
f04f46c49d | ||
|
|
0b816eb4e1 | ||
|
|
4229536799 | ||
|
|
2d14323b71 | ||
|
|
9bc852b95c | ||
|
|
9cf118bd12 | ||
|
|
7ea56bc09c | ||
|
|
8459675cc7 | ||
|
|
59f9f6d08d | ||
|
|
7d0cf9d6c7 | ||
|
|
4b26ea9831 | ||
|
|
2adfdeb98b | ||
|
|
4e0967f3a9 | ||
|
|
4d5110afa3 | ||
|
|
b230541fae | ||
|
|
36e5083fe2 | ||
|
|
4b329bd0df | ||
|
|
2acf2ea1e8 | ||
|
|
7279269ba5 | ||
|
|
dae526c83a | ||
|
|
ab31e6ae43 | ||
|
|
6618d91e74 | ||
|
|
8a569cf04a | ||
|
|
24ef77966d | ||
|
|
3c58cc47bb | ||
|
|
813b0fdbb1 | ||
|
|
5018eee3e4 | ||
|
|
34befaaa36 | ||
|
|
f82f0632a6 | ||
|
|
3c46104dd0 | ||
|
|
1e4efc179a | ||
|
|
321f4d87ca | ||
|
|
c114300727 | ||
|
|
70117c97c2 | ||
|
|
63999b961a | ||
|
|
ba328be2c3 | ||
|
|
772d7011f1 | ||
|
|
f3ef799d3d | ||
|
|
4197a3d9b4 | ||
|
|
67ea35724b | ||
|
|
4da19c1623 | ||
|
|
51cec36427 | ||
|
|
d72727629a | ||
|
|
95ec1be78a | ||
|
|
2ff3266814 | ||
|
|
dc25bb8e14 | ||
|
|
c5e0704916 | ||
|
|
3b030b009e | ||
|
|
14e4c49b76 | ||
|
|
6d8ebd4327 | ||
|
|
ff364ff5bd | ||
|
|
16e6aa6ca0 | ||
|
|
495fcbd8cb | ||
|
|
ae15d1822f | ||
|
|
6229c4907c | ||
|
|
dc87bcb4b5 | ||
|
|
a0ebef6080 | ||
|
|
7098204b5a | ||
|
|
4dd2f25fa8 | ||
|
|
840cda7cff | ||
|
|
92439f637f | ||
|
|
25d1470227 | ||
|
|
9bcfdcb7fd | ||
|
|
894ce4e305 | ||
|
|
a54a1c6f3d | ||
|
|
fb071c93e3 | ||
|
|
6b156cb9b1 | ||
|
|
1887f9e307 | ||
|
|
cfe39dd77d | ||
|
|
7d16cca501 | ||
|
|
56858a130e | ||
|
|
205204d04b | ||
|
|
36643e21ac | ||
|
|
a3541dcea6 | ||
|
|
ea3ee48a5f | ||
|
|
fc7064233a | ||
|
|
165048513d | ||
|
|
f5e887be6b | ||
|
|
5f3ad5d09b | ||
|
|
935d446afa | ||
|
|
7ea42588ce | ||
|
|
0429ce83a3 | ||
|
|
658b90c399 | ||
|
|
142f060117 | ||
|
|
7ba5d1c0a0 | ||
|
|
d7ea4ae448 | ||
|
|
b58724b515 | ||
|
|
1abb35360d | ||
|
|
06b5eae89f | ||
|
|
fdb9f792e9 | ||
|
|
c49e379824 | ||
|
|
e5e03ff588 | ||
|
|
27e1bc0d51 | ||
|
|
15fd691a88 | ||
|
|
54cb02c240 | ||
|
|
028033cdad | ||
|
|
3dc40c9c4d | ||
|
|
94f3d60a26 | ||
|
|
6023568bcf | ||
|
|
35ac568044 | ||
|
|
7b9cb85646 |
+1
-4
@@ -5,15 +5,12 @@ env:
|
||||
global:
|
||||
- ELIXIR_ASSERT_TIMEOUT=2000
|
||||
matrix:
|
||||
- OTP_RELEASE=OTP-19.0
|
||||
- OTP_RELEASE=OTP-19.1
|
||||
- OTP_RELEASE=OTP-19.2
|
||||
- OTP_RELEASE=OTP-19.3
|
||||
- OTP_RELEASE=OTP-20.0
|
||||
- OTP_RELEASE=OTP-20.1
|
||||
- OTP_RELEASE=OTP-20.2
|
||||
- OTP_RELEASE=OTP-20.3
|
||||
- OTP_RELEASE=OTP-21.0
|
||||
- OTP_RELEASE=OTP-21.1
|
||||
- OTP_RELEASE=maint
|
||||
- OTP_RELEASE=master
|
||||
|
||||
|
||||
+152
-166
@@ -1,228 +1,214 @@
|
||||
# Changelog for Elixir v1.7
|
||||
# Changelog for Elixir v1.8
|
||||
|
||||
Elixir v1.7 is the last release to support Erlang/OTP 19. We recommend everyone to migrate to Erlang/OTP 20+.
|
||||
Elixir v1.8 comes with many improvements at the infrastructure level, improving compilation time, speeding up common patterns, and adding features around introspection of the system.
|
||||
|
||||
## The `__STACKTRACE__` construct
|
||||
## Custom struct inspections
|
||||
|
||||
Erlang/OTP 21.0 introduces a new way to retrieve the stacktrace that is lexically scoped and no longer relies on side-effects like `System.stacktrace/0` does. Before one would write:
|
||||
Elixir now provides a derivable implementation of the `Inspect` protocol. In a nutshell, this means it is really easy to filter data from your data structures whenever they are inspected. For example, imagine you have a user struct with security and privacy sensitive information:
|
||||
|
||||
```elixir
|
||||
try do
|
||||
... something that may fail ...
|
||||
rescue
|
||||
e ->
|
||||
log(e, System.stacktrace())
|
||||
reraise(e, System.stacktrace())
|
||||
defmodule User do
|
||||
defstruct [:id, :name, :age, :email, :encrypted_password]
|
||||
end
|
||||
```
|
||||
|
||||
In Elixir v1.7, this can be written as:
|
||||
By default, if you inspect a user via `inspect(user)`, it will include all fields. This can cause fields such as `:email` and `:encrypted_password` to appear in logs, error reports, etc. You could always define a custom implementation of the `Inspect` protocol for such cases but Elixir v1.8 makes it simpler by allowing you to derive the `Inspect` protocol:
|
||||
|
||||
```elixir
|
||||
try do
|
||||
... something that may fail ...
|
||||
rescue
|
||||
e ->
|
||||
log(e, __STACKTRACE__)
|
||||
reraise(e, __STACKTRACE__)
|
||||
defmodule User do
|
||||
@derive {Inspect, only: [:id, :name, :age]}
|
||||
defstruct [:id, :name, :age, :email, :encrypted_password]
|
||||
end
|
||||
```
|
||||
|
||||
This change may also yield performance improvements in the future, since the lexical scope allows us to track precisely when a stacktrace is used and we no longer need to keep references to stacktrace entries after the `try` construct finishes.
|
||||
Now all user structs will be printed with all remaining fields collapsed:
|
||||
|
||||
Other parts of the exception system have been improved. For example, more information is provided in certain occurrences of `ArgumentError`, `ArithmeticError` and `KeyError` messages.
|
||||
#User<id: 1, name: "Jane", age: 33, ...>
|
||||
|
||||
## Erlang/OTP logger integration
|
||||
You can also pass `@derive {Inspect, except: [...]}` in case you want to keep all fields by default and exclude only some.
|
||||
|
||||
Erlang/OTP 21 includes a new `:logger` module. Elixir v1.7 fully integrates with the new `:logger` and leverages its metadata system. The `Logger.Translator` mechanism has also been improved to export metadata, allowing custom Logger backends to leverage information such as:
|
||||
## Time zone database support
|
||||
|
||||
* `:crash_reason` - a two-element tuple with the throw/error/exit reason as first argument and the stacktrace as second
|
||||
In Elixir v1.3, Elixir added four types, known as Calendar types, to work with dates and times: `Time`, `Date`, `NaiveDateTime` (without time zone) and `DateTime` (with time zone). Over the last releases we have added many enhancements to the Calendar types but the `DateTime` module always evolved at a slower pace since Elixir did not provide support for a time zone database.
|
||||
|
||||
* `:initial_call` - the initial call that started the process
|
||||
Elixir v1.8 now defines a `Calendar.TimeZoneDatabase` behaviour, allowing developers to bring in their own time zone databases. By defining an explicit contract for time zone behaviours, Elixir can now extend the `DateTime` API, adding functions such as `DateTime.shift_zone/3`. By default, Elixir ships with a time zone database called `Calendar.UTCOnlyTimeZoneDatabase` that only handles UTC.
|
||||
|
||||
* `:registered_name` - the process registered name as an atom
|
||||
Other Calendar related improvements include the addition of `Date.day_of_year/1`, `Date.quarter_of_year/1`, `Date.year_of_era/1`, and `Date.day_of_era/1`.
|
||||
|
||||
We recommend Elixir libraries that previously hooked into Erlang's `:error_logger` to hook into `Logger` instead, in order to support all current and future Erlang/OTP versions.
|
||||
## Faster compilation and other performance improvements
|
||||
|
||||
## Other Logger improvements
|
||||
Due to improvements to the compiler made over the last year, Elixir v1.8 should compile code about 5% faster on average. This is yet another release where we have been able to reduce compilation times and provide a more joyful development experience to everyone.
|
||||
|
||||
Previously, Logger macros such as `debug`, `info`, and so on would always evaluate their arguments, even when nothing would be logged. From Elixir v1.7, the arguments are only evaluated when the message is logged.
|
||||
The compiler also emits more efficient code for range checks in guards (such as `x in y..z`), for charlists with interpolation (such as `'foo #{bar} baz'`), and when working with records via the `Record` module.
|
||||
|
||||
The Logger configuration system also accepts a new option called `:compile_time_purge_matching` that allows you to remove log calls with specific compile-time metadata. For example, to remove all logger calls from application `:foo` with level lower than `:info`, as well as remove all logger calls from `Bar.foo/3`, you can use the following configuration:
|
||||
Finally, EEx templates got their own share of optimizations, emitting more compact code that runs faster.
|
||||
|
||||
```elixir
|
||||
config :logger,
|
||||
compile_time_purge_matching: [
|
||||
[application: :foo, level_lower_than: :info],
|
||||
[module: Bar, function: "foo/3"]
|
||||
]
|
||||
```
|
||||
## Improved instrumentation and ownership with `$callers`
|
||||
|
||||
## ExUnit improvements
|
||||
The `Task` module is one of the most common ways to spawn light-weight processes to perform work concurrently. Whenever you spawn a new process, Elixir annotates the parent of that process through the `$ancestors` key. This information can be used by instrumentation tools to track the relationship between events occurring within multiple processes. However, many times, tracking only the `$ancestors` is not enough.
|
||||
|
||||
ExUnit has also seen its own share of improvements. Assertions such as `assert some_fun(arg1, arg2, arg3)` will now include the value of each argument in the failure report:
|
||||
For example, we recommend developers to always start tasks under a supervisor. This provides more visibility and allows us to control how those tasks are terminated when a node shuts down. In your code, this can be done by invoking something like: `Task.Supervisor.start_child(MySupervisor, task_specification)`. This means that, although your code is the one who invokes the task, the actual parent of the task would be the supervisor, as the supervisor is the one spawning it. We would list the supervisor as one of the `$ancestors` for the task, but the relationship between your code and the task is lost.
|
||||
|
||||
```
|
||||
1) test function call arguments (TestOneOfEach)
|
||||
lib/ex_unit/examples/one_of_each.exs:157
|
||||
Expected truthy, got false
|
||||
code: assert some_vars(1 + 2, 3 + 4)
|
||||
arguments:
|
||||
In Elixir v1.8, we now track the relationship between your code and the task via the `$callers` key in the process dictionary, which aligns well with the existing `$ancestors` key. Therefore, assuming the `Task.Supervisor` call above, we have:
|
||||
|
||||
# 1
|
||||
3
|
||||
[your code] -- calls --> [supervisor] ---- spawns --> [task]
|
||||
|
||||
# 2
|
||||
7
|
||||
which means we store the following relationships:
|
||||
|
||||
stacktrace:
|
||||
lib/ex_unit/examples/one_of_each.exs:158: (test)
|
||||
```
|
||||
[your code] [supervisor] <-- ancestor -- [task]
|
||||
^ |
|
||||
|--------------------- caller ---------------------|
|
||||
|
||||
Furthermore, failures in doctests are now colored and diffed.
|
||||
When a task is spawned directly from your code, without a supervisor, then the process running your code will be listed under both `$ancestors` and `$callers`.
|
||||
|
||||
On the `mix test` side of things, there is a new `--failed` flag that runs all tests that failed in the previous run. Finally, coverage reports generated with `mix test --cover` include a summary out of the box:
|
||||
This small feature is very powerful. It allows instrumentation and monitoring tools to better track and relate the events happening in your system. This feature can also be used by tools like the "Ecto Sandbox". The "Ecto Sandbox" allows developers to run tests concurrently against the database, by using transactions and an ownership mechanism where each process explicitly gets a connection assigned to it. Without `$callers`, every time you spawned a task that queries the database, the task would not know its caller, and therefore it would be unable to know which connection was assigned to it. This often meant features that relies on tasks could not be tested concurrently. With `$callers`, figuring out this relationship is trivial and you have more tests using the full power of your machine.
|
||||
|
||||
```
|
||||
Generating cover results ...
|
||||
## v1.8.2 (2019-05-11)
|
||||
|
||||
Percentage | Module
|
||||
-----------|--------------------------
|
||||
100.00% | Plug.Exception.Any
|
||||
100.00% | Plug.Adapters.Cowboy2.Stream
|
||||
100.00% | Collectable.Plug.Conn
|
||||
100.00% | Plug.Crypto.KeyGenerator
|
||||
100.00% | Plug.Parsers
|
||||
100.00% | Plug.Head
|
||||
100.00% | Plug.Router.Utils
|
||||
100.00% | Plug.RequestId
|
||||
... | ...
|
||||
-----------|--------------------------
|
||||
77.19% | Total
|
||||
```
|
||||
### 1. Bug fixes
|
||||
|
||||
## v1.7.0-dev
|
||||
#### EEx
|
||||
|
||||
### 1. Enhancements
|
||||
* [EEx] Raise readable error message on bad EEx state
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Calendar.ISO] Support negative dates in `Calendar.ISO`
|
||||
* [Calendar] Add `Calendar.months_in_year/1` callback
|
||||
* [Code] Add `Code.compile_file/2` that compiles files without leaving footprints on the system
|
||||
* [Code] Add `Code.purge_compiler_modules/0` that purges any compiler module left behind. This is useful for live systems dynamically compiling code
|
||||
* [Code] Add `Code.fetch_docs/1` that returns docs in the [EEP 48](http://erlang.org/eep/eeps/eep-0048.html) format
|
||||
* [Date] Add `Date.months_in_year/1` function
|
||||
* [DynamicSupervisor] Use the name of the `DynamicSupervisor` as the ID whenever possible
|
||||
* [Exception] Provide "did you mean" suggestions on KeyError
|
||||
* [Exception] Provide more information on ArithmeticError on Erlang/OTP 21+
|
||||
* [Function] Add `Function` module with `capture/3`, `info/1` and `info/2` functions
|
||||
* [GenServer] Support the new `handle_continue/2` callback on Erlang/OTP 21+
|
||||
* [IO.ANSI] Add cursor movement to `IO.ANSI`
|
||||
* [Kernel] Introduce `__STACKTRACE__` to retrieve the current stacktrace inside `catch`/`rescue` (this will be a requirement for Erlang/OTP 21+)
|
||||
* [Kernel] Raise on unsafe variables in order to allow us to better track unused variables
|
||||
* [Kernel] Warn when using `length` to check if a list is not empty on guards
|
||||
* [Kernel] Add hints on mismatched `do`/`end` and others pairs
|
||||
* [Kernel] Warn when comparing structs using the `>`, `<`, `>=` and `<=` operators
|
||||
* [Kernel] Warn on unsupported nested comparisons such as `x < y < z`
|
||||
* [Kernel] Warn if redefining documentation across clauses of the same definition
|
||||
* [Kernel] Warn on unnecessary quotes around atoms, keywords and calls
|
||||
* [Macro] Add `Macro.special_form?/2` and `Macro.operator?/2` that returns `true` if the given name/arity is a special form or operator respectively
|
||||
* [Macro.Env] Add `Macro.Env.vars/1` and `Macro.Env.has_var?/2` that gives access to environment data without accessing private fields
|
||||
* [Regex] Include endianness in the regex version. This allows regexes to be recompiled when an archive is installed in a system with a different endianness
|
||||
* [Registry] Add `Registry.count/1` and `Registry.count_match/4`
|
||||
* [String] Update to Unicode 11
|
||||
* [System] Use ISO 8601 in `System.build_info/0`
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.Assertion] Print the arguments in error reports when asserting on a function call. For example, if `assert is_list(arg)` fails, the argument will be shown in the report
|
||||
* [ExUnit.Diff] Improve diffing of lists when one list is a subset of the other
|
||||
* [ExUnit.DocTest] Show colored diffs on failed doctests
|
||||
* [ExUnit.Formatter] Excluded tests, via the `--exclude` and `--only` flags, are now shown as "Excluded" in reports. Tests skipped via `@tag :skip` are now exclusively shown as "Skipped" and in yellow
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx.Helpers] Add `use_if_available/2`
|
||||
* [IEx.Helpers] Allow `force: true` option in `recompile/1`
|
||||
* [IEx.Helpers] Add `:allocators` pane to `runtime_info/1`
|
||||
* [Protocol] Ensure `:debug_info` is kept in protocols
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Only evaluate Logger macro arguments when the message will be logged
|
||||
* [Logger] Add `:compile_time_purge_matching` to purge logger calls that match certain compile time metadata, such as module names and application names
|
||||
* [Logger] Log to `:stderr` if a backend fails and there are no other backends
|
||||
* [Logger] Allow translators to return custom metadata
|
||||
* [Logger] Return `:crash_reason`, `:initial_call` and `:registered_name` as metadata in crash reports coming from Erlang/OTP
|
||||
* [Logger] Make sure Logger v1.8 does not get stuck in discard mode
|
||||
* [Logger.Translator] Translate remote process crash in Logger
|
||||
|
||||
## v1.8.1 (2019-01-30)
|
||||
|
||||
### 1. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Float] Fix rounding for subnormal floats
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx] Fix `IEx.pry` crash when IEx isn't running
|
||||
* [IEx.CLI] Add IEx warning when using `--remsh` with dumb terminal
|
||||
* [IEx.Helpers] Sort results by arity on `h` helper
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix archive.install] Add support for the Hex organization via `--organization`
|
||||
* [mix archive.uninstall] Support `--force` flag
|
||||
* [mix compile] Improve support for external build tools such as `rebar`
|
||||
* [mix deps] Include `override: true` in rebar dependencies to make the behaviour closer to how rebar3 works (although diverged deps are still marked as diverged)
|
||||
* [mix escript.install] Add support for the Hex organization via `--organization`
|
||||
* [mix escript.uninstall] Support `--force` flag
|
||||
* [mix help] Also list aliases
|
||||
* [mix local] Use ipv6 with auto fallback to ipv4 when downloading data
|
||||
* [mix profile] Allow all profiling tasks to run programatically
|
||||
* [mix test] Add `--failed` option that only runs previously failed tests
|
||||
* [mix test] Print coverage summary by default when the `--cover` flag is given
|
||||
* [Mix.Project] Add `Mix.Project.clear_deps_cache/0`
|
||||
* [Mix.Project] Add `Mix.Project.config_mtime/0` that caches the config mtime values to avoid filesystem access
|
||||
* [mix compile] Do not include optional dependencies in extra applications as it is incompatible with shared deps in umbrellas
|
||||
|
||||
## v1.8.0 (2019-01-14)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### EEx
|
||||
|
||||
* [EEx] Optimize the default template engine to compile and execute more efficiently
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Calendar] Add `Calendar.TimeZoneDatabase` and a `Calendar.UTCOnlyTimeZoneDatabase` implementation
|
||||
* [Calendar] Add callbacks `day_of_year/3`, `quarter_of_year/3`, `year_of_era/1`, and `day_of_era/3`
|
||||
* [Code.Formatter] Preserve user's choice of new line after most operators
|
||||
* [Date] Add `Date.day_of_year/1`, `Date.quarter_of_year/1`, `Date.year_of_era/1`, and `Date.day_of_era/1`
|
||||
* [DateTime] Add `DateTime.from_naive/3`, `DateTime.now/1`, and `DateTime.shift_zone/3`
|
||||
* [File] Allow `:raw` option in `File.exists?/2`, `File.regular?/2`, and `File.dir?/2`
|
||||
* [File] Allow POSIX time as an integer in `File.touch/2` and `File.touch!/2`
|
||||
* [Inspect] Allow `Inspect` protocol to be derivable with the `:only`/`:except` options
|
||||
* [Kernel] Do not propagate counters to variables in quote inside another quote
|
||||
* [Kernel] Warn on ambiguous use of `::` and `|` in typespecs
|
||||
* [Kernel] Add `:delegate_to` `@doc` metadata tag when using `defdelegate`
|
||||
* [Kernel] Improve compile-time building of ranges via the `..` operator
|
||||
* [Kernel] Compile charlist interpolation more efficiently
|
||||
* [Kernel] Add `floor/1` and `ceil/1` guards
|
||||
* [Kernel.SpecialForms] Add `:reduce` option to `for` comprehensions
|
||||
* [List] Add `List.myers_difference/3` and `List.improper?/1`
|
||||
* [Macro] Add `Macro.struct!/2` for proper struct resolution during compile time
|
||||
* [Map] Optimize and merge nested maps `put` and `merge` operations
|
||||
* [Range] Add `Range.disjoint?/2`
|
||||
* [Record] Reduce memory allocation when updating multiple fields in a record
|
||||
* [Registry] Allow associating a value on `:via` tuple
|
||||
* [String] Add `String.bag_distance/2`
|
||||
* [Task] Add `$callers` tracking to `Task` - this makes it easier to find which process spawned a task and use it for tracking ownership and monitoring
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit] Add `ExUnit.after_suite/1` callback
|
||||
* [ExUnit.Assertions] Show last N messages (instead of first N) from mailbox on `assert_receive` fail
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx.Helpers] Add `port/1` and `port/2`
|
||||
* [IEx.Server] Expose `IEx.Server.run/1` for custom IEx sessions with the ability to broker pry sessions
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix] Add `Mix.target/0` and `Mix.target/1` to control dependency management per target
|
||||
* [Mix.Project] Add `:depth` and `:parents` options to `deps_paths/1`
|
||||
* [mix archive.install] Add a timeout when installing archives
|
||||
* [mix compile] Include optional dependencies in `:extra_applications`
|
||||
* [mix escript.install] Add a timeout when installing escripts
|
||||
* [mix format] Warn when the same file may be formatted by multiple `.formatter.exs`
|
||||
* [mix test] Allow setting the maximum number of failures via `--max-failures`
|
||||
* [mix test] Print a message instead of raising on unmatched tests inside umbrella projects
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [IO.ANSI.Docs] Fix table column alignment when converting docs to ANSI escapes
|
||||
* [Code] Ensure `string_to_quoted` returns error tuples instead of raising in certain constructs
|
||||
* [Code.Formatter] Consistently format keyword lists in function calls with and without parens
|
||||
* [Code.Formatter] Do not break after `->` when there are only comments and one-line clauses
|
||||
* [Kernel] Raise on unsafe variables as some of the code emitted with unsafe variables would not correctly propagate variables or would disable tail call optimization semantics
|
||||
* [Kernel] Do not crash on dynamic sizes in binary generators with collectable into in comprehensions
|
||||
* [Kernel] Do not crash on literals with non-unary size in binary generators with collectable into in comprehensions
|
||||
* [Task] Improve error reports and exit reasons for failed tasks on Erlang/OTP 20+
|
||||
* [Calendar] Allow printing dates with more than 9999 years
|
||||
* [Exception] Exclude deprecated functions in "did you mean?" hints
|
||||
* [Float] Handle subnormal floats in `Float.ratio/1`
|
||||
* [Kernel] Remove `Guard test tuple_size(...) can never succeed` Dialyzer warning on `try`
|
||||
* [Kernel] Expand operands in `size*unit` bitstring modifier instead of expecting `size` and `unit` to be literal integers
|
||||
* [Kernel] Do not deadlock on circular struct dependencies in typespecs
|
||||
* [Kernel] Raise proper error message when passing flags to the Erlang compiler that Elixir cannot handle
|
||||
* [Kernel] Do not leak variables in `cond` clauses with a single matching at compile-time clause
|
||||
* [NaiveDateTime] Do not accept leap seconds in builder and parsing functions
|
||||
* [String] Fix ZWJ handling in Unicode grapheme clusters
|
||||
* [StringIO] Handle non-printable args in StringIO gracefully
|
||||
|
||||
#### ExUnit
|
||||
#### IEx
|
||||
|
||||
* [ExUnit.Case] Raise proper error if `@tag` and `@moduletag` are used before `use ExUnit.Case`
|
||||
* [ExUnit.Case] Raise proper error if `@describetag` is used outside of `describe/2` blocks
|
||||
* [ExUnit.DocTest] Emit proper assertion error on doctests with invalid UTF-8
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix archive.install] Fetch optional dependencies when installing an archive from Git/Hex
|
||||
* [mix compile] Properly track config files in umbrella projects and recompile when any relevant umbrella configuration changes
|
||||
* [mix deps] Ensure the same dependency from different SCMs are tagged as diverged when those SCMs are remote and non-remote
|
||||
* [mix deps] Ensure we re-run dependency resolution when overriding a skipped dep in umbrella
|
||||
* [mix deps.compile] Perform clean builds for dependencies on outdated locks to avoid old modules from affecting future compilation
|
||||
* [mix escript.install] Fetch optional dependencies when installing an escript from Git/Hex
|
||||
|
||||
### 3. Soft-deprecations (no warnings emitted)
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Deprecate `Code.load_file/2` in favor of `Code.compile_file/2`
|
||||
* [Code] Deprecate `Code.loaded_files/0` in favor of `Code.required_files/0`
|
||||
* [Code] Deprecate `Code.unload_files/1` in favor of `Code.unrequire_files/1`
|
||||
* [IEx.Helpers] Use typespec info (instead of docs chunk) and properly format callbacks in `b/1`
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] `compile_time_purge_level` is deprecated in favor of `compile_time_purge_matching`
|
||||
* [Logger] Allow Logger backends to be dynamically removed when an application is shutting down
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix compile] Ensure changes in deps propagate to all umbrella children - this fix a long standing issue where updating a dependency would not recompile all projects accordingly, requiring a complete removal of `_build`
|
||||
* [mix compile] Avoid time drift when checking and updating compiler manifest files
|
||||
* [mix compile.app] Respect the `:only` option between umbrella siblings
|
||||
* [mix compile.protocols] Reconsolidate protocols if local dependencies are stale
|
||||
* [mix deps] Properly mark dependencies with different `:system_env` as diverged
|
||||
* [mix new] Use `--module` value when setting up filenames
|
||||
|
||||
### 3. Soft-deprecations (no warnings emitted)
|
||||
|
||||
None.
|
||||
|
||||
### 4. Hard-deprecations
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] `Code.get_docs/2` is deprecated in favor of `Code.fetch_docs/1`
|
||||
* [Enum] `Enum.chunk/2/3/4` is deprecated in favor of `Enum.chunk_every/2/3/4` - notice `chunk_every` does not discard incomplete chunks by default
|
||||
* [GenServer] Warn if `super` is used in any of the GenServer callbacks
|
||||
* [Kernel] `not left in right` is ambiguous and is deprecated in favor of `left not in right`
|
||||
* [Kernel] Warn on confusing operator sequences, such as `1+++1` meaning `1 ++ +1` or `........` meaning `... .. ...`
|
||||
* [OptionParser] Deprecate dynamic option parser mode that depended on atoms to be previously loaded and therefore behaved inconsistently
|
||||
* [Stream] `Stream.chunk/2/3/4` is deprecated in favor of `Stream.chunk_every/2/3/4` - notice `chunk_every` does not discard incomplete chunks by default
|
||||
* [Enum] Passing a non-empty list to `Enum.into/2` was inconsistent with maps and is deprecated in favor of `Kernel.++/2` or `Keyword.merge/2`
|
||||
* [Inspect.Algebra] `surround/3` is deprecated in favor of `Inspect.Algebra.concat/2` and `Inspect.Algebra.nest/2`
|
||||
* [Inspect.Algebra] `surround_many/6` is deprecated in favor of `container_doc/6`
|
||||
* [Kernel] Using `@since` will now emit a unused attribute warning. Use `@doc since: "1.7.2"` instead
|
||||
* [Kernel] Passing a non-empty list as `:into` in `for` comprehensions was inconsistent with maps and is deprecated in favor of `Kernel.++/2` or `Keyword.merge/2`
|
||||
* [Kernel.ParallelCompiler] `files/2` is deprecated in favor of `compile/2`
|
||||
* [Kernel.ParallelCompiler] `files_to_path/2` is deprecated in favor of `compile_to_path/2`
|
||||
* [Kernel.ParallelRequire] `files/2` is deprecated in favor of `Kernel.ParallelCompiler.require/2`
|
||||
* [System] `:seconds`, `:milliseconds`, etc. as time units is deprecated in favor of `:second`, `:millisecond`, etc.
|
||||
* [System] `System.cwd/0` and `System.cwd!/0` are deprecated in favor of `File.cwd/0` and `File.cwd!/0`
|
||||
|
||||
## v1.6
|
||||
#### Mix
|
||||
|
||||
The CHANGELOG for v1.6 releases can be found [in the v1.6 branch](https://github.com/elixir-lang/elixir/blob/v1.6/CHANGELOG.md).
|
||||
* [mix compile.erlang] Returning `{:ok, contents}` or `:error` as the callback in `Mix.Compilers.Erlang.compile/6` is deprecated in favor of returning `{:ok, contents, warnings}` or `{:error, errors, warnings}`
|
||||
|
||||
## v1.7
|
||||
|
||||
The CHANGELOG for v1.7 releases can be found [in the v1.7 branch](https://github.com/elixir-lang/elixir/blob/v1.7/CHANGELOG.md).
|
||||
|
||||
+3
-1
@@ -1,8 +1,9 @@
|
||||
### Precheck
|
||||
|
||||
* Do not use the issues tracker for help or support (try Elixir Forum, Stack Overflow, IRC, etc.)
|
||||
* For proposing a new feature, please start a discussion on the Elixir Core mailing list
|
||||
* 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
|
||||
@@ -16,3 +17,4 @@ Include code samples, errors and stacktraces if appropriate.
|
||||
|
||||
### Expected behavior
|
||||
|
||||
A short description on how you expect the code to behave.
|
||||
|
||||
@@ -174,28 +174,3 @@
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2012 Plataformatec
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
PREFIX ?= /usr/local
|
||||
SHARE_PREFIX ?= $(PREFIX)/share
|
||||
CANONICAL := master/
|
||||
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict
|
||||
ERLC := erlc -I lib/elixir/include
|
||||
MAN_PREFIX ?= $(SHARE_PREFIX)/man
|
||||
CANONICAL := v1.8/ # master/ or vMAJOR.MINOR/
|
||||
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict --warnings-as-errors
|
||||
ERLC := erlc -I lib/elixir/include +warnings_as_errors
|
||||
ERL := erl -I lib/elixir/include -noshell -pa lib/elixir/ebin
|
||||
GENERATE_APP := $(CURDIR)/lib/elixir/generate_app.escript
|
||||
VERSION := $(strip $(shell cat VERSION))
|
||||
@@ -22,9 +23,9 @@ GIT_TAG = $(strip $(shell head="$(call GIT_REVISION)"; git tag --points-at $$hea
|
||||
#==> Functions
|
||||
|
||||
define CHECK_ERLANG_RELEASE
|
||||
erl -noshell -eval '{V,_} = string:to_integer(erlang:system_info(otp_release)), io:fwrite("~s", [is_integer(V) and (V >= 19)])' -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 19.0 is required to build Elixir"; \
|
||||
echo "At least Erlang/OTP 20.0 is required to build Elixir"; \
|
||||
exit 1; \
|
||||
fi
|
||||
endef
|
||||
@@ -33,11 +34,7 @@ define APP_TEMPLATE
|
||||
$(1): lib/$(1)/ebin/Elixir.$(2).beam lib/$(1)/ebin/$(1).app
|
||||
|
||||
lib/$(1)/ebin/$(1).app: lib/$(1)/mix.exs
|
||||
$(Q) mkdir -p lib/$(1)/_build/shared/lib/$(1)
|
||||
$(Q) cp -R lib/$(1)/ebin lib/$(1)/_build/shared/lib/$(1)/
|
||||
$(Q) cd lib/$(1) && ../../bin/elixir -e 'Mix.start(:permanent, [])' -r mix.exs -e 'Mix.Task.run("compile.app")'
|
||||
$(Q) cp lib/$(1)/_build/shared/lib/$(1)/ebin/$(1).app lib/$(1)/ebin/$(1).app
|
||||
$(Q) rm -rf lib/$(1)/_build
|
||||
$(Q) cd lib/$(1) && ../../bin/elixir -e 'Mix.start(:permanent, [])' -r mix.exs -e 'Mix.Task.run("compile.app", ~w[--compile-path ebin])'
|
||||
|
||||
lib/$(1)/ebin/Elixir.$(2).beam: $(wildcard lib/$(1)/lib/*.ex) $(wildcard lib/$(1)/lib/*/*.ex) $(wildcard lib/$(1)/lib/*/*/*.ex)
|
||||
@ echo "==> $(1) (compile)"
|
||||
@@ -45,7 +42,7 @@ lib/$(1)/ebin/Elixir.$(2).beam: $(wildcard lib/$(1)/lib/*.ex) $(wildcard lib/$(1
|
||||
$(Q) cd lib/$(1) && ../../$$(ELIXIRC) "lib/**/*.ex" -o ebin
|
||||
|
||||
test_$(1): compile $(1)
|
||||
@ echo "==> $(1) (exunit)"
|
||||
@ echo "==> $(1) (ex_unit)"
|
||||
$(Q) cd lib/$(1) && ../../bin/elixir -r "test/test_helper.exs" -pr "test/**/*_test.exs";
|
||||
endef
|
||||
|
||||
@@ -141,7 +138,7 @@ clean_residual_files:
|
||||
LOGO_PATH = $(shell test -f ../docs/logo.png && echo "--logo ../docs/logo.png")
|
||||
SOURCE_REF = $(shell tag="$(call GIT_TAG)" revision="$(call GIT_REVISION)"; echo "$${tag:-$$revision}\c")
|
||||
DOCS_FORMAT = html
|
||||
COMPILE_DOCS = bin/elixir ../ex_doc/bin/ex_doc "$(1)" "$(VERSION)" "lib/$(2)/ebin" -m "$(3)" -u "https://github.com/elixir-lang/elixir" --source-ref "$(call SOURCE_REF)" $(call LOGO_PATH) -o doc/$(2) -n https://hexdocs.pm/$(2)/$(CANONICAL) -p http://elixir-lang.org/docs.html -f "$(DOCS_FORMAT)" $(4)
|
||||
COMPILE_DOCS = bin/elixir ../ex_doc/bin/ex_doc "$(1)" "$(VERSION)" "lib/$(2)/ebin" -m "$(3)" -u "https://github.com/elixir-lang/elixir" --source-ref "$(call SOURCE_REF)" $(call LOGO_PATH) -o doc/$(2) -n https://hexdocs.pm/$(2)/$(CANONICAL) -p 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
|
||||
|
||||
@@ -192,6 +189,14 @@ Precompiled.zip: build_man compile
|
||||
@ 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
|
||||
|
||||
@@ -222,7 +227,7 @@ $(TEST_EBIN)/%.beam: $(TEST_ERL)/%.erl
|
||||
test_elixir: test_stdlib test_ex_unit test_logger test_mix test_eex test_iex
|
||||
|
||||
test_stdlib: compile
|
||||
@ echo "==> elixir (exunit)"
|
||||
@ 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.exs"; \
|
||||
@@ -246,7 +251,7 @@ build_plt: clean_plt $(PLT)
|
||||
|
||||
dialyze: compile $(PLT)
|
||||
@ echo "==> Dialyzing Elixir..."
|
||||
$(Q) dialyzer --plt $(PLT) $(DIALYZER_OPTS) lib/*/ebin
|
||||
$(Q) dialyzer -pa lib/elixir/ebin --plt $(PLT) $(DIALYZER_OPTS) lib/*/ebin
|
||||
|
||||
#==> Man page tasks
|
||||
|
||||
@@ -271,9 +276,9 @@ clean_man:
|
||||
rm -f man/iex.1.bak
|
||||
|
||||
install_man: build_man
|
||||
$(Q) mkdir -p $(DESTDIR)$(SHARE_PREFIX)/man/man1
|
||||
$(Q) $(INSTALL_DATA) man/elixir.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
|
||||
$(Q) $(INSTALL_DATA) man/elixirc.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
|
||||
$(Q) $(INSTALL_DATA) man/iex.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
|
||||
$(Q) $(INSTALL_DATA) man/mix.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
|
||||
$(Q) mkdir -p $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(Q) $(INSTALL_DATA) man/elixir.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(Q) $(INSTALL_DATA) man/elixirc.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(Q) $(INSTALL_DATA) man/iex.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(Q) $(INSTALL_DATA) man/mix.1 $(DESTDIR)$(MAN_PREFIX)/man1
|
||||
$(MAKE) clean_man
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
LEGAL NOTICE INFORMATION
|
||||
------------------------
|
||||
|
||||
All the files in this distribution are copyright (c) 2012 Plataformatec
|
||||
covered under Elixir's license (see the file LICENSE) except the cases
|
||||
below.
|
||||
All the files in this distribution are copyright to the terms below.
|
||||
|
||||
== lib/elixir/src/elixir_parser.erl (generated by build scripts)
|
||||
|
||||
@@ -20,3 +18,19 @@ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
== All other files
|
||||
|
||||
Copyright 2012 Plataformatec
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -3,10 +3,15 @@
|
||||
[](https://travis-ci.org/elixir-lang/elixir)
|
||||
|
||||
Elixir is a dynamic, functional language designed for building scalable and maintainable applications.
|
||||
Elixir is a dynamic, functional language designed for building scalable
|
||||
and maintainable applications.
|
||||
|
||||
For more about Elixir, installation and documentation,
|
||||
[check Elixir's website](http://elixir-lang.org/).
|
||||
[check Elixir's website](https://elixir-lang.org/).
|
||||
|
||||
## Announcements
|
||||
|
||||
New releases are announced in the [announcements mailing list](https://groups.google.com/group/elixir-lang-ann). All security releases [will be tagged with `[security]`](https://groups.google.com/forum/#!searchin/elixir-lang-ann/%5Bsecurity%5D%7Csort:date).
|
||||
|
||||
## Compiling from source
|
||||
|
||||
@@ -30,10 +35,10 @@ If tests pass, you are ready to move on to the [Getting Started guide][1]
|
||||
or to try Interactive Elixir by running `bin/iex` in your terminal.
|
||||
|
||||
However, if tests fail, it is likely you have an outdated Erlang/OTP version
|
||||
(Elixir requires Erlang/OTP 19.0 or later). You can check your 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 19 [erts-8.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
|
||||
Erlang/OTP 20 [erts-9.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
|
||||
|
||||
If you have properly set up your dependencies and tests still fail,
|
||||
you may want to open up a bug report, as explained next.
|
||||
@@ -41,8 +46,8 @@ you may want to open up a bug report, as explained next.
|
||||
## Bug reports
|
||||
|
||||
For reporting bugs, [visit our issues tracker][2] and follow the steps
|
||||
for reporting a new issue. Please disclose security vulnerabilities
|
||||
privately at elixir-security@googlegroups.com.
|
||||
for reporting a new issue. **Please disclose security vulnerabilities
|
||||
privately at elixir-security@googlegroups.com**.
|
||||
|
||||
## Proposing new features
|
||||
|
||||
@@ -101,9 +106,9 @@ To recompile (including Erlang modules):
|
||||
make compile
|
||||
```
|
||||
|
||||
After your changes are done, please remember to run the full suite with
|
||||
`make test` and then `mix format` to guarantee all files are properly
|
||||
formatted.
|
||||
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`.
|
||||
|
||||
If your contribution fails during the bootstrapping of the language,
|
||||
you can rebuild the language from scratch with:
|
||||
@@ -122,9 +127,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
|
||||
|
||||
@@ -179,7 +184,7 @@ the `doc` directory. If you are planning to contribute documentation,
|
||||
[3]: https://groups.google.com/group/elixir-lang-core
|
||||
[4]: https://webchat.freenode.net/?channels=#elixir-lang
|
||||
[5]: http://www.freenode.net
|
||||
[6]: http://elixir-lang.org/docs.html
|
||||
[6]: https://elixir-lang.org/docs.html
|
||||
[7]: CODE_OF_CONDUCT.md
|
||||
|
||||
## License
|
||||
@@ -188,5 +193,4 @@ the `doc` directory. If you are planning to contribute documentation,
|
||||
|
||||
Elixir source code is released under Apache 2 License.
|
||||
|
||||
Check [NOTICE](NOTICE) and [LICENSE](LICENSE) files for more
|
||||
information.
|
||||
Check [NOTICE](NOTICE) and [LICENSE](LICENSE) files for more information.
|
||||
|
||||
+7
-3
@@ -20,7 +20,9 @@
|
||||
|
||||
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` and `_data/elixir-versions.yml` files in `elixir-lang/elixir-lang.github.com`
|
||||
10. Add the release to `elixir.csv` (all releases) and `_data/elixir-versions.yml` (except for RCs) files in `elixir-lang/elixir-lang.github.com`
|
||||
|
||||
11. Send an e-mail to elixir-lang-ann@googlegroups.com with title "Elixir vVERSION released". The body should be a link to the Release page on GitHub and the checksums. If it is a security release, prefix the title with the `[security]` tag
|
||||
|
||||
## Creating a new vMAJOR.MINOR branch
|
||||
|
||||
@@ -28,7 +30,7 @@
|
||||
|
||||
1. Set `CANONICAL=` in /Makefile
|
||||
|
||||
2. Update **all** tables in "Compatibility and Deprecations"
|
||||
2. Update tables in "Compatibility and Deprecations"
|
||||
|
||||
3. Commit "Prepare vMAJOR.MINOR for release"
|
||||
|
||||
@@ -38,4 +40,6 @@
|
||||
|
||||
2. Start new /CHANGELOG.md
|
||||
|
||||
3. Commit "Start vMAJOR.MINOR+1"
|
||||
3. Update tables in "Compatibility and Deprecations"
|
||||
|
||||
4. Commit "Start vMAJOR.MINOR+1"
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ set originPath=%~dp0
|
||||
rem Optional parameters before the "-extra" parameter
|
||||
set beforeExtra=
|
||||
|
||||
rem Flag which determines whether or not to use werl vs erl
|
||||
rem Option which determines whether or not to use werl vs erl
|
||||
set useWerl=0
|
||||
|
||||
rem Designates which mode / Elixir component to run as
|
||||
|
||||
+2
-2
@@ -167,7 +167,7 @@ defmodule EEx do
|
||||
Gets a string `source` and generate a quoted expression
|
||||
that can be evaluated by Elixir or compiled to a function.
|
||||
"""
|
||||
@spec compile_string(String.t(), keyword) :: Macro.t() | no_return
|
||||
@spec compile_string(String.t(), keyword) :: Macro.t()
|
||||
def compile_string(source, options \\ []) when is_binary(source) and is_list(options) do
|
||||
EEx.Compiler.compile(source, options)
|
||||
end
|
||||
@@ -176,7 +176,7 @@ defmodule EEx do
|
||||
Gets a `filename` and generate a quoted expression
|
||||
that can be evaluated by Elixir or compiled to a function.
|
||||
"""
|
||||
@spec compile_file(String.t(), keyword) :: Macro.t() | no_return
|
||||
@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)
|
||||
|
||||
@@ -9,7 +9,7 @@ defmodule EEx.Compiler do
|
||||
and the engine together by handling the tokens and invoking
|
||||
the engine every time a full expression or text is received.
|
||||
"""
|
||||
@spec compile(String.t(), keyword) :: Macro.t() | no_return
|
||||
@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
|
||||
|
||||
+114
-97
@@ -2,58 +2,70 @@ defmodule EEx.Engine do
|
||||
@moduledoc ~S"""
|
||||
Basic EEx engine that ships with Elixir.
|
||||
|
||||
An engine needs to implement six functions:
|
||||
An engine needs to implement all callbacks below.
|
||||
|
||||
* `init(opts)` - called at the beginning of every text
|
||||
and it must return the initial state.
|
||||
|
||||
* `handle_body(state)` - receives the state of the document
|
||||
and it must return a quoted expression.
|
||||
|
||||
* `handle_text(state, text)` - it receives the state,
|
||||
the text and must return a new quoted expression.
|
||||
|
||||
* `handle_expr(state, marker, expr)` - it receives the state,
|
||||
the marker, the expr and must return a new state.
|
||||
|
||||
* `handle_begin(state)` - called every time there a new state
|
||||
is needed with an empty buffer. Typically called for do/end
|
||||
blocks, case expressions, anonymous functions, etc
|
||||
|
||||
* `handle_end(state)` - opposite of `handle_begin(state)` and
|
||||
it must return quoted expression
|
||||
|
||||
The marker is what follows exactly after `<%`. For example,
|
||||
`<% foo %>` has an empty marker, but `<%= foo %>` has `"="`
|
||||
as marker. The allowed markers so far are:
|
||||
|
||||
* `""`
|
||||
* `"="`
|
||||
* `"/"`
|
||||
* `"|"`
|
||||
|
||||
Markers `"/"` and `"|"` are only for use in custom EEx engines
|
||||
and are not implemented by default. Using them without the
|
||||
implementation raises `EEx.SyntaxError`.
|
||||
|
||||
If your engine does not implement all markers, please ensure that
|
||||
`handle_expr/3` falls back to `EEx.Engine.handle_expr/3`
|
||||
to raise the proper error message.
|
||||
|
||||
Read `handle_expr/3` below for more information about the markers
|
||||
implemented by default by this engine.
|
||||
|
||||
`EEx.Engine` can be used directly if one desires to use the
|
||||
default implementations for the functions above.
|
||||
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
|
||||
|
||||
@doc """
|
||||
Called at the beginning of every template.
|
||||
|
||||
It must return the initial state.
|
||||
"""
|
||||
@callback init(opts :: keyword) :: state
|
||||
|
||||
@doc """
|
||||
Called at the end of every template.
|
||||
|
||||
It must return Elixir's quoted expressions for the template.
|
||||
"""
|
||||
@callback handle_body(state) :: Macro.t()
|
||||
|
||||
@doc """
|
||||
Called for the text/static parts of a template.
|
||||
|
||||
It must return the updated state.
|
||||
"""
|
||||
@callback handle_text(state, text :: String.t()) :: state
|
||||
|
||||
@doc """
|
||||
Called for the dynamic/code parts of a template.
|
||||
|
||||
The marker is what follows exactly after `<%`. For example,
|
||||
`<% foo %>` has an empty marker, but `<%= foo %>` has `"="`
|
||||
as marker. The allowed markers so far are:
|
||||
|
||||
* `""`
|
||||
* `"="`
|
||||
* `"/"`
|
||||
* `"|"`
|
||||
|
||||
Markers `"/"` and `"|"` are only for use in custom EEx engines
|
||||
and are not implemented by default. Using them without an
|
||||
appropriate implementation raises `EEx.SyntaxError`.
|
||||
|
||||
It must return the updated state.
|
||||
"""
|
||||
@callback handle_expr(state, marker :: String.t(), expr :: Macro.t()) :: state
|
||||
|
||||
@doc """
|
||||
Invoked at the beginning of every nesting.
|
||||
|
||||
It must return a new state that is used only inside the nesting.
|
||||
Once the nesting terminates, the current `state` is resumed.
|
||||
"""
|
||||
@callback handle_begin(state) :: state
|
||||
|
||||
@doc """
|
||||
Invokes at the end of a nesting.
|
||||
|
||||
It must return Elixir's quoted expressions for the nesting.
|
||||
"""
|
||||
@callback handle_end(state) :: Macro.t()
|
||||
|
||||
@doc false
|
||||
@@ -65,24 +77,24 @@ defmodule EEx.Engine do
|
||||
EEx.Engine.init(opts)
|
||||
end
|
||||
|
||||
def handle_body(quoted) do
|
||||
EEx.Engine.handle_body(quoted)
|
||||
def handle_body(state) do
|
||||
EEx.Engine.handle_body(state)
|
||||
end
|
||||
|
||||
def handle_begin(quoted) do
|
||||
EEx.Engine.handle_begin(quoted)
|
||||
def handle_begin(state) do
|
||||
EEx.Engine.handle_begin(state)
|
||||
end
|
||||
|
||||
def handle_end(quoted) do
|
||||
EEx.Engine.handle_end(quoted)
|
||||
def handle_end(state) do
|
||||
EEx.Engine.handle_end(state)
|
||||
end
|
||||
|
||||
def handle_text(buffer, text) do
|
||||
EEx.Engine.handle_text(buffer, text)
|
||||
def handle_text(state, text) do
|
||||
EEx.Engine.handle_text(state, text)
|
||||
end
|
||||
|
||||
def handle_expr(buffer, marker, expr) do
|
||||
EEx.Engine.handle_expr(buffer, marker, expr)
|
||||
def handle_expr(state, marker, expr) do
|
||||
EEx.Engine.handle_expr(state, marker, expr)
|
||||
end
|
||||
|
||||
defoverridable EEx.Engine
|
||||
@@ -98,9 +110,9 @@ defmodule EEx.Engine do
|
||||
This can be added to any custom engine by invoking
|
||||
`handle_assign/1` with `Macro.prewalk/2`:
|
||||
|
||||
def handle_expr(buffer, token, expr) do
|
||||
def handle_expr(state, token, expr) do
|
||||
expr = Macro.prewalk(expr, &EEx.Engine.handle_assign/1)
|
||||
EEx.Engine.handle_expr(buffer, token, expr)
|
||||
super(state, token, expr)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -135,68 +147,73 @@ defmodule EEx.Engine do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an empty string as initial buffer.
|
||||
"""
|
||||
@doc false
|
||||
def init(_opts) do
|
||||
""
|
||||
%{
|
||||
binary: [],
|
||||
dynamic: [],
|
||||
vars_count: 0
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an empty string as the new buffer.
|
||||
"""
|
||||
def handle_begin(_previous) do
|
||||
""
|
||||
@doc false
|
||||
def handle_begin(state) do
|
||||
check_state!(state)
|
||||
%{state | binary: [], dynamic: []}
|
||||
end
|
||||
|
||||
@doc """
|
||||
End of the new buffer.
|
||||
"""
|
||||
@doc false
|
||||
def handle_end(quoted) do
|
||||
quoted
|
||||
handle_body(quoted)
|
||||
end
|
||||
|
||||
@doc """
|
||||
The default implementation simply returns the given expression.
|
||||
"""
|
||||
def handle_body(quoted) do
|
||||
quoted
|
||||
@doc false
|
||||
def handle_body(state) do
|
||||
check_state!(state)
|
||||
%{binary: binary, dynamic: dynamic} = state
|
||||
binary = {:<<>>, [], Enum.reverse(binary)}
|
||||
dynamic = [binary | dynamic]
|
||||
{:__block__, [], Enum.reverse(dynamic)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
The default implementation simply concatenates text to the buffer.
|
||||
"""
|
||||
def handle_text(buffer, text) do
|
||||
quote(do: unquote(buffer) <> unquote(text))
|
||||
@doc false
|
||||
def handle_text(state, text) do
|
||||
%{binary: binary} = state
|
||||
%{state | binary: [text | binary]}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Implements expressions according to the markers.
|
||||
@doc false
|
||||
def handle_expr(state, "=", ast) do
|
||||
%{binary: binary, dynamic: dynamic, vars_count: vars_count} = state
|
||||
var = Macro.var(:"arg#{vars_count}", __MODULE__)
|
||||
|
||||
<% Elixir expression - inline with output %>
|
||||
<%= Elixir expression - replace with result %>
|
||||
<%/ Elixir expression - raise EEx.SyntaxError, to be implemented by custom engines %>
|
||||
<%| Elixir expression - raise EEx.SyntaxError, to be implemented by custom engines %>
|
||||
ast =
|
||||
quote do
|
||||
unquote(var) = String.Chars.to_string(unquote(ast))
|
||||
end
|
||||
|
||||
All other markers are not implemented by this engine.
|
||||
"""
|
||||
def handle_expr(buffer, "=", expr) do
|
||||
quote do
|
||||
tmp1 = unquote(buffer)
|
||||
tmp1 <> String.Chars.to_string(unquote(expr))
|
||||
end
|
||||
segment =
|
||||
quote do
|
||||
unquote(var) :: binary
|
||||
end
|
||||
|
||||
%{state | dynamic: [ast | dynamic], binary: [segment | binary], vars_count: vars_count + 1}
|
||||
end
|
||||
|
||||
def handle_expr(buffer, "", expr) do
|
||||
quote do
|
||||
tmp2 = unquote(buffer)
|
||||
unquote(expr)
|
||||
tmp2
|
||||
end
|
||||
def handle_expr(state, "", ast) do
|
||||
%{dynamic: dynamic} = state
|
||||
%{state | dynamic: [ast | dynamic]}
|
||||
end
|
||||
|
||||
def handle_expr(_buffer, marker, _expr) when marker in ["/", "|"] do
|
||||
def handle_expr(_state, marker, _ast) when marker in ["/", "|"] do
|
||||
raise EEx.SyntaxError,
|
||||
"unsupported EEx syntax <%#{marker} %> (the syntax is valid but not supported by the current EEx engine)"
|
||||
end
|
||||
|
||||
defp check_state!(%{binary: _, dynamic: _, vars_count: _}), do: :ok
|
||||
|
||||
defp check_state!(state) do
|
||||
raise "unexpected EEx.Engine state: #{inspect(state)}. " <>
|
||||
"This typically means a bug or an outdated EEx.Engine or tool"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -501,7 +501,7 @@ defmodule EExTest do
|
||||
|
||||
test "begin/end" do
|
||||
assert_eval(
|
||||
~s[BODY(INIT:TEXT(foo):EQUAL(if() do\n "BEGIN:TEXT(this):END"\nelse\n "BEGIN:TEXT(that):END"\nend))],
|
||||
~s[BODY(INIT:TEXT(foo):EQUAL(if do\n "BEGIN:TEXT(this):END"\nelse\n "BEGIN:TEXT(that):END"\nend))],
|
||||
"foo <%= if do %>this<% else %>that<% end %>",
|
||||
[],
|
||||
engine: TestEngine
|
||||
@@ -519,7 +519,7 @@ defmodule EExTest do
|
||||
end
|
||||
|
||||
defp assert_eval(expected, actual, binding \\ [], opts \\ []) do
|
||||
opts = Enum.into([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
|
||||
opts = Keyword.merge([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
|
||||
result = EEx.eval_string(actual, binding, opts)
|
||||
assert result == expected
|
||||
end
|
||||
|
||||
@@ -8,12 +8,10 @@
|
||||
warn_unused_record,
|
||||
warn_deprecated_function,
|
||||
warn_obsolete_guard,
|
||||
strict_validation,
|
||||
warn_exported_vars,
|
||||
%% warn_export_vars,
|
||||
%% warn_missing_spec,
|
||||
%% warn_untyped_record,
|
||||
%% warnings_as_errors,
|
||||
warnings_as_errors,
|
||||
debug_info,
|
||||
{outdir, "ebin/"}
|
||||
]}.
|
||||
|
||||
+11
-2
@@ -1,6 +1,10 @@
|
||||
# Returns config for Elixir docs
|
||||
[
|
||||
extras: Path.wildcard("lib/elixir/pages/*.md"),
|
||||
groups_for_functions: [
|
||||
Guards: & &1[:guard] == true
|
||||
],
|
||||
skip_undefined_reference_warnings_on: ["compatibility-and-deprecations"],
|
||||
groups_for_modules: [
|
||||
# [Kernel, Kernel.SpecialForms],
|
||||
|
||||
@@ -8,12 +12,11 @@
|
||||
Atom,
|
||||
Base,
|
||||
Bitwise,
|
||||
Calendar,
|
||||
Calendar.ISO,
|
||||
Date,
|
||||
DateTime,
|
||||
Exception,
|
||||
Float,
|
||||
Function,
|
||||
Integer,
|
||||
NaiveDateTime,
|
||||
Record,
|
||||
@@ -48,6 +51,12 @@
|
||||
StringIO,
|
||||
System
|
||||
],
|
||||
"Calendar": [
|
||||
Calendar,
|
||||
Calendar.ISO,
|
||||
Calendar.TimeZoneDatabase,
|
||||
Calendar.UTCOnlyTimeZoneDatabase
|
||||
],
|
||||
"Modules & Code": [
|
||||
Code,
|
||||
Kernel.ParallelCompiler,
|
||||
|
||||
@@ -105,7 +105,7 @@ defmodule Access do
|
||||
### Summing up
|
||||
|
||||
The bracket-based syntax, `user[:name]`, is used by dynamic structures,
|
||||
is extensible and returns nil on misisng keys.
|
||||
is extensible and returns nil on missing keys.
|
||||
|
||||
The dot-based syntax, `user.name`, is used exclusively to access atom
|
||||
keys in maps and structs, and it raises on missing keys.
|
||||
@@ -118,9 +118,9 @@ defmodule Access do
|
||||
|
||||
For example, to update a map inside another map:
|
||||
|
||||
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
|
||||
iex> put_in(users["john"].age, 28)
|
||||
%{"john" => %{age: 28}, "meg" => %{age: 23}}
|
||||
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
|
||||
iex> put_in(users["john"].age, 28)
|
||||
%{"john" => %{age: 28}, "meg" => %{age: 23}}
|
||||
|
||||
This module provides convenience functions for traversing other
|
||||
structures, like tuples and lists. These functions can be used
|
||||
@@ -132,13 +132,17 @@ defmodule Access do
|
||||
|
||||
iex> languages = [
|
||||
...> %{name: "elixir", type: :functional},
|
||||
...> %{name: "c", type: :procedural},
|
||||
...> %{name: "c", type: :procedural}
|
||||
...> ]
|
||||
iex> user = %{name: "john", languages: languages}
|
||||
iex> update_in(user, [:languages, Access.all(), :name], &String.upcase/1)
|
||||
%{name: "john",
|
||||
languages: [%{name: "ELIXIR", type: :functional},
|
||||
%{name: "C", type: :procedural}]}
|
||||
%{
|
||||
name: "john",
|
||||
languages: [
|
||||
%{name: "ELIXIR", type: :functional},
|
||||
%{name: "C", type: :procedural}
|
||||
]
|
||||
}
|
||||
|
||||
See the functions `key/1`, `key!/1`, `elem/1`, and `all/0` for some of the
|
||||
available accessors.
|
||||
@@ -611,7 +615,7 @@ defmodule Access do
|
||||
numbers and multiplying odd numbers by 2:
|
||||
|
||||
iex> require Integer
|
||||
iex> get_and_update_in([1, 2, 3, 4, 5], [Access.all], fn num ->
|
||||
iex> get_and_update_in([1, 2, 3, 4, 5], [Access.all()], fn num ->
|
||||
...> if Integer.is_even(num), do: :pop, else: {num, num * 2}
|
||||
...> end)
|
||||
{[1, 2, 3, 4, 5], [2, 6, 10]}
|
||||
|
||||
+84
-42
@@ -11,44 +11,42 @@ defmodule Agent do
|
||||
|
||||
## Examples
|
||||
|
||||
For example, in the Mix tool that ships with Elixir, we need
|
||||
to keep a set of all tasks executed by a given project. Since
|
||||
this set is shared, we can implement it with an agent:
|
||||
For example, the following agent implements a counter:
|
||||
|
||||
defmodule Mix.TasksServer do
|
||||
defmodule Counter do
|
||||
use Agent
|
||||
|
||||
def start_link(_) do
|
||||
Agent.start_link(fn -> MapSet.new end, name: __MODULE__)
|
||||
def start_link(initial_value) do
|
||||
Agent.start_link(fn -> initial_value end, name: __MODULE__)
|
||||
end
|
||||
|
||||
@doc "Checks if the task has already executed"
|
||||
def executed?(task, project) do
|
||||
item = {task, project}
|
||||
Agent.get(__MODULE__, fn set ->
|
||||
item in set
|
||||
end)
|
||||
def value do
|
||||
Agent.get(__MODULE__, & &1)
|
||||
end
|
||||
|
||||
@doc "Marks a task as executed"
|
||||
def put_task(task, project) do
|
||||
item = {task, project}
|
||||
Agent.update(__MODULE__, &MapSet.put(&1, item))
|
||||
end
|
||||
|
||||
@doc "Resets the executed tasks and returns the previous list of tasks"
|
||||
def take_all() do
|
||||
Agent.get_and_update(__MODULE__, fn set ->
|
||||
{Enum.into(set, []), MapSet.new}
|
||||
end)
|
||||
def increment do
|
||||
Agent.update(__MODULE__, &(&1 + 1))
|
||||
end
|
||||
end
|
||||
|
||||
Agents provide a segregation between the client and server APIs (similar
|
||||
to GenServers). In particular, the anonymous functions given to the `Agent`
|
||||
are executed inside the agent (the server). This distinction is important
|
||||
because you may want to avoid expensive operations inside the agent,
|
||||
as they will effectively block the agent until the request is fulfilled.
|
||||
Usage would be:
|
||||
|
||||
Counter.start_link(0)
|
||||
|
||||
Counter.value #=> 0
|
||||
Counter.increment #=> :ok
|
||||
Counter.increment #=> :ok
|
||||
Counter.value #=> 2
|
||||
|
||||
Thanks to the agent server process, the counter can be safely incremented
|
||||
concurrently.
|
||||
|
||||
Agents provide a segregation between the client and server APIs (similar to
|
||||
`GenServer`s). In particular, the functions passed as arguments to the calls to
|
||||
`Agent` functions are invoked inside the agent (the server). This distinction
|
||||
is important because you may want to avoid expensive operations inside the
|
||||
agent, as they will effectively block the agent until the request is
|
||||
fulfilled.
|
||||
|
||||
Consider these two examples:
|
||||
|
||||
@@ -59,7 +57,7 @@ defmodule Agent do
|
||||
|
||||
# Compute in the agent/client
|
||||
def get_something(agent) do
|
||||
Agent.get(agent, &(&1)) |> do_something_expensive()
|
||||
Agent.get(agent, & &1) |> do_something_expensive()
|
||||
end
|
||||
|
||||
The first function blocks the agent. The second function copies all the state
|
||||
@@ -73,20 +71,61 @@ defmodule Agent do
|
||||
than in the server can lead to race conditions if multiple clients are trying
|
||||
to update the same state to different values.
|
||||
|
||||
Finally note `use Agent` defines a `child_spec/1` function, allowing the
|
||||
defined module to be put under a supervision tree. The generated
|
||||
`child_spec/1` can be customized with the following options:
|
||||
## How to supervise
|
||||
|
||||
An `Agent` is most commonly started under a supervision tree.
|
||||
When we invoke `use Agent`, it automatically defines a `child_spec/1`
|
||||
function that allows us to start the agent directly under a supervisor.
|
||||
To start an agent under a supervisor with an initial counter of 0,
|
||||
one may do:
|
||||
|
||||
children = [
|
||||
{Counter, 0}
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_all)
|
||||
|
||||
While one could also simply pass the `Counter` as a child to the supervisor,
|
||||
such as:
|
||||
|
||||
children = [
|
||||
Counter # Same as {Counter, []}
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_all)
|
||||
|
||||
The definition above wouldn't work for this particular example,
|
||||
as it would attempt to start the counter with an initial value
|
||||
of an empty list. However, this may be a viable option in your
|
||||
own agents. A common approach is to use a keyword list, as that
|
||||
would allow setting the initial value and giving a name to the
|
||||
counter process, for example:
|
||||
|
||||
def start_link(opts) do
|
||||
{initial_value, opts} = Keyword.pop(opts, :initial_value, 0)
|
||||
Agent.start_link(fn -> initial_value end, opts)
|
||||
end
|
||||
|
||||
and then you can use `Counter`, `{Counter, name: :my_counter}` or
|
||||
even `{Counter, initial_value: 0, name: :my_counter}` as a child
|
||||
specification.
|
||||
|
||||
`use Agent` also accepts a list of options which configures the
|
||||
child specification and therefore how it runs under a supervisor.
|
||||
The generated `child_spec/1` can be customized with the following options:
|
||||
|
||||
* `:id` - the child specification identifier, defaults to the current module
|
||||
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
|
||||
* `:restart` - when the child should be restarted, defaults to `:permanent`
|
||||
* `:shutdown` - how to shut down the child
|
||||
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
|
||||
|
||||
For example:
|
||||
|
||||
use Agent, restart: :transient, shutdown: 10_000
|
||||
|
||||
See the `Supervisor` docs for more information.
|
||||
See the "Child specification" section in the `Supervisor` module for more
|
||||
detailed information. The `@doc` annotation immediately preceding
|
||||
`use Agent` will be attached to the generated `child_spec/1` function.
|
||||
|
||||
## Name registration
|
||||
|
||||
@@ -142,7 +181,7 @@ defmodule Agent do
|
||||
@doc """
|
||||
Returns a specification to start an agent under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
See the "Child specification" section in the `Supervisor` module for more detailed information.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
def child_spec(arg) do
|
||||
@@ -155,11 +194,14 @@ defmodule Agent do
|
||||
@doc false
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
end
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
@@ -178,9 +220,9 @@ defmodule Agent do
|
||||
|
||||
This is often used to start the agent as part of a supervision tree.
|
||||
|
||||
Once the agent is spawned, the given function `fun` is invoked and its return
|
||||
value is used as the agent state. Note that `start_link/2` does not return
|
||||
until the given function has returned.
|
||||
Once the agent is spawned, the given function `fun` is invoked in the server
|
||||
process, and should return the initial agent state. Note that `start_link/2`
|
||||
does not return until the given function has returned.
|
||||
|
||||
## Options
|
||||
|
||||
|
||||
@@ -23,8 +23,8 @@ defmodule Application do
|
||||
`mix.exs`, and others are generated by Mix itself.
|
||||
|
||||
You can learn more about the generation of application resource files in the
|
||||
documentation of `Mix.Tasks.Compile.App`, available as well by running `mix
|
||||
help compile.app`.
|
||||
documentation of `Mix.Tasks.Compile.App`, available as well by running
|
||||
`mix help compile.app`.
|
||||
|
||||
## The application environment
|
||||
|
||||
@@ -66,8 +66,8 @@ defmodule Application do
|
||||
own environment. Please do not use the functions in this module for directly
|
||||
accessing or modifying the environment of other applications.
|
||||
|
||||
The application environment can be overriden via the `-config` option of
|
||||
`erl`, as well as command-line flags, as we are going to see below.
|
||||
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
|
||||
|
||||
@@ -135,7 +135,7 @@ defmodule Application do
|
||||
is merged with any overrides from config files passed to `erl` via the
|
||||
`-config` option. It is worth highlighting that releases pass `sys.config`
|
||||
this way. The resulting environment can still be overridden again via specific
|
||||
`-Application` flags passed to `erl`.
|
||||
`-Application` options passed to `erl`.
|
||||
|
||||
Loading an application *does not* load its modules.
|
||||
|
||||
@@ -197,9 +197,9 @@ defmodule Application do
|
||||
Shutting down a live system cleanly can be done by calling `System.stop/1`. It
|
||||
will shut down every application in the opposite order they had been started.
|
||||
|
||||
From Erlang/OTP 19.1, a SIGTERM from the operating system will automatically
|
||||
translate to `System.stop/0`. Erlang/OTP 20 gives user more explicit control
|
||||
over OS signals via the `:os.set_signal/2` function.
|
||||
By default, a SIGTERM from the operating system will automatically translate to
|
||||
`System.stop/0`. You can also have more explicit control over OS signals via the
|
||||
`:os.set_signal/2` function.
|
||||
|
||||
## Tooling
|
||||
|
||||
@@ -296,7 +296,7 @@ defmodule Application do
|
||||
@callback stop(state) :: term
|
||||
|
||||
@doc """
|
||||
Start an application in synchronous phases.
|
||||
Starts an application in synchronous phases.
|
||||
|
||||
This function is called after `start/2` finishes but before
|
||||
`Application.start/2` returns. It will be called once for every start phase
|
||||
@@ -306,7 +306,18 @@ defmodule Application do
|
||||
@callback start_phase(phase :: term, start_type, phase_args :: term) ::
|
||||
:ok | {:error, reason :: term}
|
||||
|
||||
@optional_callbacks start_phase: 3, prep_stop: 1
|
||||
@doc """
|
||||
Callback invoked after code upgrade, if the application environment
|
||||
has changed.
|
||||
|
||||
`changed` is a keyword list of keys and their changed values in the
|
||||
application environment. `new` is a keyword list with all new keys
|
||||
and their values. `removed` is a list with all removed keys.
|
||||
"""
|
||||
@callback config_change(changed, new, removed) :: :ok
|
||||
when changed: keyword, new: keyword, removed: [atom]
|
||||
|
||||
@optional_callbacks start_phase: 3, prep_stop: 1, config_change: 3
|
||||
|
||||
@doc false
|
||||
defmacro __using__(_) do
|
||||
@@ -354,7 +365,7 @@ defmodule Application do
|
||||
`fetch_env/2`. Returns `nil` if the application is not loaded.
|
||||
"""
|
||||
@spec spec(app) :: [{key, value}] | nil
|
||||
def spec(app) do
|
||||
def spec(app) when is_atom(app) do
|
||||
case :application.get_all_key(app) do
|
||||
{:ok, info} -> :lists.keydelete(:env, 1, info)
|
||||
:undefined -> nil
|
||||
@@ -369,7 +380,7 @@ defmodule Application do
|
||||
will raise. Returns `nil` if the application is not loaded.
|
||||
"""
|
||||
@spec spec(app, key) :: value | nil
|
||||
def spec(app, key) when key in @application_keys do
|
||||
def spec(app, key) when is_atom(app) and key in @application_keys do
|
||||
case :application.get_key(app, key) do
|
||||
{:ok, value} -> value
|
||||
:undefined -> nil
|
||||
@@ -395,7 +406,7 @@ defmodule Application do
|
||||
Returns all key-value pairs for `app`.
|
||||
"""
|
||||
@spec get_all_env(app) :: [{key, value}]
|
||||
def get_all_env(app) do
|
||||
def get_all_env(app) when is_atom(app) do
|
||||
:application.get_all_env(app)
|
||||
end
|
||||
|
||||
@@ -404,9 +415,44 @@ defmodule Application do
|
||||
|
||||
If the configuration parameter does not exist, the function returns the
|
||||
`default` value.
|
||||
|
||||
## Examples
|
||||
|
||||
`get_env/3` is commonly used to read the configuration of your OTP applications.
|
||||
Since Mix configurations are commonly used to configure applications, we will use
|
||||
this as a point of illustration.
|
||||
|
||||
Consider a new application `:my_app`. `:my_app` contains a database engine which
|
||||
supports a pool of databases. The database engine needs to know the configuration for
|
||||
each of those databases, and that configuration is supplied by key-value pairs in
|
||||
environment of `:my_app`.
|
||||
|
||||
config :my_app, Databases.RepoOne,
|
||||
# A database configuration
|
||||
ip: "localhost",
|
||||
port: 5433
|
||||
|
||||
config :my_app, Databases.RepoTwo,
|
||||
# Another database configuration (for the same OTP app)
|
||||
ip: "localhost",
|
||||
port: 20717
|
||||
|
||||
config :my_app, my_app_databases: [Databases.RepoOne, Databases.RepoTwo]
|
||||
|
||||
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
|
||||
`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) do
|
||||
def get_env(app, key, default \\ nil) when is_atom(app) do
|
||||
:application.get_env(app, key, default)
|
||||
end
|
||||
|
||||
@@ -416,7 +462,7 @@ defmodule Application do
|
||||
If the configuration parameter does not exist, the function returns `:error`.
|
||||
"""
|
||||
@spec fetch_env(app, key) :: {:ok, value} | :error
|
||||
def fetch_env(app, key) do
|
||||
def fetch_env(app, key) when is_atom(app) do
|
||||
case :application.get_env(app, key) do
|
||||
{:ok, value} -> {:ok, value}
|
||||
:undefined -> :error
|
||||
@@ -428,8 +474,8 @@ defmodule Application do
|
||||
|
||||
If the configuration parameter does not exist, raises `ArgumentError`.
|
||||
"""
|
||||
@spec fetch_env!(app, key) :: value | no_return
|
||||
def fetch_env!(app, key) do
|
||||
@spec fetch_env!(app, key) :: value
|
||||
def fetch_env!(app, key) when is_atom(app) do
|
||||
case fetch_env(app, key) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
@@ -467,13 +513,13 @@ defmodule Application do
|
||||
environment values specified in the `.app` file will override the ones
|
||||
previously set.
|
||||
|
||||
The persistent option can be set to `true` when there is a need to guarantee
|
||||
The `:persistent` option can be set to `true` when there is a need to guarantee
|
||||
parameters set with this function will not be overridden by the ones defined
|
||||
in the application resource file on load. This means persistent values will
|
||||
stick after the application is loaded and also on application reload.
|
||||
"""
|
||||
@spec put_env(app, key, value, timeout: timeout, persistent: boolean) :: :ok
|
||||
def put_env(app, key, value, opts \\ []) do
|
||||
def put_env(app, key, value, opts \\ []) when is_atom(app) do
|
||||
:application.set_env(app, key, value, opts)
|
||||
end
|
||||
|
||||
@@ -483,7 +529,7 @@ defmodule Application do
|
||||
See `put_env/4` for a description of the options.
|
||||
"""
|
||||
@spec delete_env(app, key, timeout: timeout, persistent: boolean) :: :ok
|
||||
def delete_env(app, key, opts \\ []) do
|
||||
def delete_env(app, key, opts \\ []) when is_atom(app) do
|
||||
:application.unset_env(app, key, opts)
|
||||
end
|
||||
|
||||
@@ -559,7 +605,7 @@ defmodule Application do
|
||||
When stopped, the application is still loaded.
|
||||
"""
|
||||
@spec stop(app) :: :ok | {:error, term}
|
||||
def stop(app) do
|
||||
def stop(app) when is_atom(app) do
|
||||
:application.stop(app)
|
||||
end
|
||||
|
||||
@@ -642,11 +688,11 @@ defmodule Application do
|
||||
@spec app_dir(app, String.t() | [String.t()]) :: String.t()
|
||||
def app_dir(app, path)
|
||||
|
||||
def app_dir(app, path) when is_binary(path) do
|
||||
def app_dir(app, path) when is_atom(app) and is_binary(path) do
|
||||
Path.join(app_dir(app), path)
|
||||
end
|
||||
|
||||
def app_dir(app, path) when is_list(path) do
|
||||
def app_dir(app, path) when is_atom(app) and is_list(path) do
|
||||
Path.join([app_dir(app) | path])
|
||||
end
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ defmodule Bitwise do
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro bnot(expr) do
|
||||
quote(do: :erlang.bnot(unquote(expr)))
|
||||
end
|
||||
@@ -79,6 +80,7 @@ defmodule Bitwise do
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro ~~~expr do
|
||||
quote(do: :erlang.bnot(unquote(expr)))
|
||||
end
|
||||
@@ -90,6 +92,7 @@ defmodule Bitwise do
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro band(left, right) do
|
||||
quote(do: :erlang.band(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -101,6 +104,7 @@ defmodule Bitwise do
|
||||
1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro left &&& right do
|
||||
quote(do: :erlang.band(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -112,6 +116,7 @@ defmodule Bitwise do
|
||||
11
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro bor(left, right) do
|
||||
quote(do: :erlang.bor(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -123,6 +128,7 @@ defmodule Bitwise do
|
||||
11
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro left ||| right do
|
||||
quote(do: :erlang.bor(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -134,6 +140,7 @@ defmodule Bitwise do
|
||||
10
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro bxor(left, right) do
|
||||
quote(do: :erlang.bxor(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -145,6 +152,7 @@ defmodule Bitwise do
|
||||
10
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro left ^^^ right do
|
||||
quote(do: :erlang.bxor(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -162,6 +170,7 @@ defmodule Bitwise do
|
||||
-1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro bsl(left, right) do
|
||||
quote(do: :erlang.bsl(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -179,6 +188,7 @@ defmodule Bitwise do
|
||||
-1
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro left <<< right do
|
||||
quote(do: :erlang.bsl(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -196,6 +206,7 @@ defmodule Bitwise do
|
||||
-4
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro bsr(left, right) do
|
||||
quote(do: :erlang.bsr(unquote(left), unquote(right)))
|
||||
end
|
||||
@@ -213,6 +224,7 @@ defmodule Bitwise do
|
||||
-4
|
||||
|
||||
"""
|
||||
@doc guard: true
|
||||
defmacro left >>> right do
|
||||
quote(do: :erlang.bsr(unquote(left), unquote(right)))
|
||||
end
|
||||
|
||||
+72
-13
@@ -17,11 +17,15 @@ defmodule Calendar do
|
||||
"""
|
||||
|
||||
@type year :: integer
|
||||
@type month :: integer
|
||||
@type day :: integer
|
||||
@type hour :: integer
|
||||
@type minute :: integer
|
||||
@type second :: integer
|
||||
@type month :: pos_integer
|
||||
@type day :: pos_integer
|
||||
@type week :: pos_integer
|
||||
@type day_of_week :: non_neg_integer
|
||||
@type era :: non_neg_integer
|
||||
|
||||
@type hour :: non_neg_integer
|
||||
@type minute :: non_neg_integer
|
||||
@type second :: non_neg_integer
|
||||
|
||||
@typedoc """
|
||||
The internal time format is used when converting between calendars.
|
||||
@@ -36,13 +40,8 @@ defmodule Calendar do
|
||||
The internal date format that is used when converting between calendars.
|
||||
|
||||
This is the number of days including the fractional part that has passed of
|
||||
the last day since 0000-01-01+00:00T00:00.00000 in ISO 8601 notation (also
|
||||
the last day since 0000-01-01+00:00T00:00.000000 in ISO 8601 notation (also
|
||||
known as midnight 1 January BC 1 of the proleptic Gregorian calendar).
|
||||
|
||||
The `parts_per_day` represent how many subparts the current day is subdivided in
|
||||
(for different calendars, picking a different `parts_per_day` might make sense).
|
||||
The `parts_in_day` represents how many of these `parts_per_day` have passed in the
|
||||
last day.
|
||||
"""
|
||||
@type iso_days :: {days :: integer, day_fraction}
|
||||
|
||||
@@ -112,6 +111,28 @@ defmodule Calendar do
|
||||
std_offset: std_offset
|
||||
}
|
||||
|
||||
@typedoc """
|
||||
Specifies the time zone database for calendar operations.
|
||||
|
||||
Many functions in the `DateTime` module require a time zone database.
|
||||
By default, it uses the default time zone database returned by
|
||||
`Calendar.get_time_zone_database/0`, which defaults to
|
||||
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC"
|
||||
datetimes and returns `{:error, :utc_only_time_zone_database}`
|
||||
for any other time zone.
|
||||
|
||||
Other time zone databases (including ones provided by packages)
|
||||
can be configure as default either via configuration:
|
||||
|
||||
config :elixir, :time_zone_database, CustomTimeZoneDatabase
|
||||
|
||||
or by calling `Calendar.put_time_zone_database/1`.
|
||||
|
||||
See `Calendar.TimeZoneDatabase` for more information on custom
|
||||
time zone databases.
|
||||
"""
|
||||
@type time_zone_database :: module()
|
||||
|
||||
@doc """
|
||||
Returns how many days there are in the given year-month.
|
||||
"""
|
||||
@@ -134,7 +155,27 @@ defmodule Calendar do
|
||||
@doc """
|
||||
Calculates the day of the week from the given `year`, `month`, and `day`.
|
||||
"""
|
||||
@callback day_of_week(year, month, day) :: 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`.
|
||||
"""
|
||||
@callback day_of_year(year, month, day) :: non_neg_integer()
|
||||
|
||||
@doc """
|
||||
Calculates the quarter of the year from the given `year`, `month`, and `day`.
|
||||
"""
|
||||
@callback quarter_of_year(year, month, day) :: non_neg_integer()
|
||||
|
||||
@doc """
|
||||
Calculates the year and era from the given `year`.
|
||||
"""
|
||||
@callback year_of_era(year) :: {year, era}
|
||||
|
||||
@doc """
|
||||
Calculates the day and era from the given `year`, `month`, and `day`.
|
||||
"""
|
||||
@callback day_of_era(year, month, day) :: {non_neg_integer(), era}
|
||||
|
||||
@doc """
|
||||
Converts the date into a string according to the calendar.
|
||||
@@ -170,7 +211,7 @@ defmodule Calendar do
|
||||
@callback time_to_string(hour, minute, second, microsecond) :: String.t()
|
||||
|
||||
@doc """
|
||||
Converts the given datetime (with time zone) into the `t:iso_days/0` format.
|
||||
Converts the given datetime (without time zone) into the `t:iso_days/0` format.
|
||||
"""
|
||||
@callback naive_datetime_to_iso_days(year, month, day, hour, minute, second, microsecond) ::
|
||||
iso_days
|
||||
@@ -258,4 +299,22 @@ defmodule Calendar do
|
||||
end
|
||||
|
||||
def truncate(_, :second), do: {0, 0}
|
||||
|
||||
@doc """
|
||||
Sets the current time zone database.
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec put_time_zone_database(time_zone_database()) :: :ok
|
||||
def put_time_zone_database(database) do
|
||||
Application.put_env(:elixir, :time_zone_database, database)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets the current time zone database.
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec get_time_zone_database() :: time_zone_database()
|
||||
def get_time_zone_database() do
|
||||
Application.get_env(:elixir, :time_zone_database, Calendar.UTCOnlyTimeZoneDatabase)
|
||||
end
|
||||
end
|
||||
|
||||
+139
-21
@@ -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`](`Kernel.sigil_D/2`) sigil:
|
||||
`~D` (see `Kernel.sigil_D/2`) sigil:
|
||||
|
||||
iex> ~D[2000-01-01]
|
||||
~D[2000-01-01]
|
||||
@@ -25,7 +25,7 @@ defmodule Date do
|
||||
|
||||
Developers should avoid creating the Date structs directly
|
||||
and instead rely on the functions provided by this module as well
|
||||
as the ones in 3rd party calendar libraries.
|
||||
as the ones in third-party calendar libraries.
|
||||
|
||||
## Comparing dates
|
||||
|
||||
@@ -53,7 +53,7 @@ defmodule Date do
|
||||
@enforce_keys [:year, :month, :day]
|
||||
defstruct [:year, :month, :day, calendar: Calendar.ISO]
|
||||
|
||||
@type t :: %Date{
|
||||
@type t :: %__MODULE__{
|
||||
year: Calendar.year(),
|
||||
month: Calendar.month(),
|
||||
day: Calendar.day(),
|
||||
@@ -248,6 +248,8 @@ defmodule Date do
|
||||
Parses the extended "Dates" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
The year parsed by this function is limited to four digits.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.from_iso8601("2015-01-23")
|
||||
@@ -263,24 +265,29 @@ defmodule Date do
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes>>, calendar) do
|
||||
with {year, ""} <- Integer.parse(year),
|
||||
{month, ""} <- Integer.parse(month),
|
||||
{day, ""} <- Integer.parse(day) do
|
||||
with {:ok, date} <- new(year, month, day, Calendar.ISO), do: convert(date, calendar)
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
def from_iso8601(<<?-, next, rest::binary>>, calendar) when next != ?- do
|
||||
with {:ok, %{year: year} = date} <- from_iso8601(<<next>> <> rest, calendar) do
|
||||
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(<<_::binary>>, _calendar) do
|
||||
{:error, :invalid_format}
|
||||
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 """
|
||||
@@ -460,7 +467,7 @@ defmodule Date do
|
||||
cannot compare #{inspect(date1)} with #{inspect(date2)}.
|
||||
|
||||
This comparison would be ambiguous as their calendars have incompatible day rollover moments.
|
||||
Specify an exact time of day (using `DateTime`s) to resolve this ambiguity
|
||||
Specify an exact time of day (using DateTime) to resolve this ambiguity
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -551,9 +558,20 @@ defmodule Date do
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec add(Calendar.date(), integer()) :: t
|
||||
def add(%{calendar: Calendar.ISO} = date, days) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
|
||||
{year, month, day} =
|
||||
Calendar.ISO.date_to_iso_days(year, month, day)
|
||||
|> Kernel.+(days)
|
||||
|> Calendar.ISO.date_from_iso_days()
|
||||
|
||||
%Date{calendar: Calendar.ISO, year: year, month: month, day: day}
|
||||
end
|
||||
|
||||
def add(%{calendar: calendar} = date, days) do
|
||||
{iso_days, fraction} = to_iso_days(date)
|
||||
from_iso_days({iso_days + days, fraction}, calendar)
|
||||
{base_days, fraction} = to_iso_days(date)
|
||||
from_iso_days({base_days + days, fraction}, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -634,13 +652,113 @@ defmodule Date do
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec day_of_week(Calendar.date()) :: non_neg_integer()
|
||||
@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}) do
|
||||
calendar.day_of_week(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the day of the year of a given `date`.
|
||||
|
||||
Returns the day of the year as an integer. For the ISO 8601
|
||||
calendar (the default), it is an integer from 1 to 366.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.day_of_year(~D[2016-01-01])
|
||||
1
|
||||
iex> Date.day_of_year(~D[2016-11-01])
|
||||
306
|
||||
iex> Date.day_of_year(~D[-0015-10-30])
|
||||
303
|
||||
iex> Date.day_of_year(~D[2004-12-31])
|
||||
366
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec day_of_year(Calendar.date()) :: Calendar.day()
|
||||
def day_of_year(date)
|
||||
|
||||
def day_of_year(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.day_of_year(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the quarter of the year of a given `date`.
|
||||
|
||||
Returns the day of the year as an integer. For the ISO 8601
|
||||
calendar (the default), it is an integer from 1 to 4.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.quarter_of_year(~D[2016-10-31])
|
||||
4
|
||||
iex> Date.quarter_of_year(~D[2016-01-01])
|
||||
1
|
||||
iex> Date.quarter_of_year(~N[2016-04-01 01:23:45])
|
||||
2
|
||||
iex> Date.quarter_of_year(~D[-0015-09-30])
|
||||
3
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec quarter_of_year(Calendar.date()) :: non_neg_integer()
|
||||
def quarter_of_year(date)
|
||||
|
||||
def quarter_of_year(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.quarter_of_year(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the year-of-era and era for a given
|
||||
calendar year.
|
||||
|
||||
Returns a tuple `{year, era}` representing the
|
||||
year within the era and the era number.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.year_of_era(~D[0001-01-01])
|
||||
{1, 1}
|
||||
iex> Date.year_of_era(~D[0000-12-31])
|
||||
{1, 0}
|
||||
iex> Date.year_of_era(~D[-0001-01-01])
|
||||
{2, 0}
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec year_of_era(Calendar.date()) :: {Calendar.year(), non_neg_integer()}
|
||||
def year_of_era(date)
|
||||
|
||||
def year_of_era(%{calendar: calendar, year: year}) do
|
||||
calendar.year_of_era(year)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the day-of-era and era for a given
|
||||
calendar `date`.
|
||||
|
||||
Returns a tuple `{day, era}` representing the
|
||||
day within the era and the era number.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.day_of_era(~D[0001-01-01])
|
||||
{1, 1}
|
||||
iex> Date.day_of_era(~D[0000-12-31])
|
||||
{1, 0}
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec day_of_era(Calendar.date()) :: {Calendar.day(), non_neg_integer()}
|
||||
def day_of_era(date)
|
||||
|
||||
def day_of_era(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.day_of_era(year, month, day)
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
defimpl String.Chars do
|
||||
|
||||
+501
-136
@@ -12,26 +12,25 @@ defmodule DateTime do
|
||||
are structural and based on the DateTime struct fields. For proper
|
||||
comparison between datetimes, use the `compare/2` function.
|
||||
|
||||
The functions on this module work with the `DateTime` struct as well
|
||||
as any struct that contains the same fields as the `DateTime` struct.
|
||||
Such functions expect `t:Calendar.datetime/0` in their typespecs
|
||||
(instead of `t:t/0`).
|
||||
|
||||
Developers should avoid creating the DateTime struct directly
|
||||
Developers should avoid creating the `DateTime` struct directly
|
||||
and instead rely on the functions provided by this module as
|
||||
well as the ones in 3rd party calendar libraries.
|
||||
well as the ones in third-party calendar libraries.
|
||||
|
||||
## Where are my functions?
|
||||
## Time zone database
|
||||
|
||||
You will notice this module only contains conversion
|
||||
functions as well as functions that work on UTC. This
|
||||
is because a proper DateTime implementation requires a
|
||||
TimeZone database which currently is not provided as part
|
||||
of Elixir.
|
||||
Many functions in this module require a time zone database.
|
||||
By default, it uses the default time zone database returned by
|
||||
`Calendar.get_time_zone_database/0`, which defaults to
|
||||
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC"
|
||||
datetimes and returns `{:error, :utc_only_time_zone_database}`
|
||||
for any other time zone.
|
||||
|
||||
Such may be addressed in upcoming versions, meanwhile,
|
||||
use 3rd party packages to provide DateTime building and
|
||||
similar functionality with time zone backing.
|
||||
Other time zone databases (including ones provided by packages)
|
||||
can be configure as default either via configuration:
|
||||
|
||||
config :elixir, :time_zone_database, CustomTimeZoneDatabase
|
||||
|
||||
or by calling `Calendar.put_time_zone_database/1`.
|
||||
"""
|
||||
|
||||
@enforce_keys [:year, :month, :day, :hour, :minute, :second] ++
|
||||
@@ -176,8 +175,11 @@ defmodule DateTime do
|
||||
@doc """
|
||||
Converts the given `NaiveDateTime` to `DateTime`.
|
||||
|
||||
It expects a time zone to put the NaiveDateTime in.
|
||||
Currently it only supports "Etc/UTC" as time zone.
|
||||
It expects a time zone to put the `NaiveDateTime` in.
|
||||
If the time zone is "Etc/UTC", it always succeeds. Otherwise,
|
||||
the NaiveDateTime is checked against the time zone database
|
||||
given as `time_zone_database`. See the "Time zone database"
|
||||
section in the module documentation.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -185,12 +187,136 @@ defmodule DateTime do
|
||||
iex> datetime
|
||||
#DateTime<2016-05-24 13:26:08.003Z>
|
||||
|
||||
When the datetime is ambiguous - for instance during changing from summer
|
||||
to winter time - the two possible valid datetimes are returned. First the one
|
||||
that happens first, then the one that happens after.
|
||||
|
||||
iex> {:ambiguous, first_dt, second_dt} = DateTime.from_naive(~N[2018-10-28 02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> first_dt
|
||||
#DateTime<2018-10-28 02:30:00+02:00 CEST Europe/Copenhagen>
|
||||
iex> second_dt
|
||||
#DateTime<2018-10-28 02:30:00+01:00 CET Europe/Copenhagen>
|
||||
|
||||
When there is a gap in wall time - for instance in spring when the clocks are
|
||||
turned forward - the latest valid datetime just before the gap and the first
|
||||
valid datetime just after the gap.
|
||||
|
||||
iex> {:gap, just_before, just_after} = DateTime.from_naive(~N[2019-03-31 02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> just_before
|
||||
#DateTime<2019-03-31 01:59:59.999999+01:00 CET Europe/Copenhagen>
|
||||
iex> just_after
|
||||
#DateTime<2019-03-31 03:00:00+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
Most of the time there is one, and just one, valid datetime for a certain
|
||||
date and time in a certain time zone.
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_naive(~N[2018-07-28 12:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> datetime
|
||||
#DateTime<2018-07-28 12:30:00+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
This function accepts any map or struct that contains at least the same fields as a `NaiveDateTime`
|
||||
struct. The most common example of that is a `DateTime`. In this case the information about the time
|
||||
zone of that `DateTime` is completely ignored. This is the same principle as passing a `DateTime` to
|
||||
`Date.to_iso8601/2`. `Date.to_iso8601/2` extracts only the date-specific fields (calendar, year,
|
||||
month and day) of the given structure and ignores all others.
|
||||
|
||||
This way if you have a `DateTime` in one time zone, you can get the same wall time in another time zone.
|
||||
For instance if you have 2018-08-24 10:00:00 in Copenhagen and want a `DateTime` for 2018-08-24 10:00:00
|
||||
in UTC you can do:
|
||||
|
||||
iex> cph_datetime = DateTime.from_naive!(~N[2018-08-24 10:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> {:ok, utc_datetime} = DateTime.from_naive(cph_datetime, "Etc/UTC", FakeTimeZoneDatabase)
|
||||
iex> utc_datetime
|
||||
#DateTime<2018-08-24 10:00:00Z>
|
||||
|
||||
If instead you want a `DateTime` for the same point time in a different time zone see the
|
||||
`DateTime.shift_zone/3` function which would convert 2018-08-24 10:00:00 in Copenhagen
|
||||
to 2018-08-24 08:00:00 in UTC.
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec from_naive(NaiveDateTime.t(), Calendar.time_zone()) :: {:ok, t}
|
||||
def from_naive(naive_datetime, time_zone)
|
||||
@spec from_naive(
|
||||
Calendar.naive_datetime(),
|
||||
Calendar.time_zone(),
|
||||
Calendar.time_zone_database()
|
||||
) ::
|
||||
{:ok, t}
|
||||
| {:ambiguous, t, t}
|
||||
| {:gap, t, t}
|
||||
| {:error,
|
||||
:incompatible_calendars | :time_zone_not_found | :utc_only_time_zone_database}
|
||||
|
||||
def from_naive(
|
||||
naive_datetime,
|
||||
time_zone,
|
||||
time_zone_database \\ Calendar.get_time_zone_database()
|
||||
)
|
||||
|
||||
def from_naive(naive_datetime, "Etc/UTC", _) do
|
||||
utc_period = %{std_offset: 0, utc_offset: 0, zone_abbr: "UTC"}
|
||||
{:ok, from_naive_with_period(naive_datetime, "Etc/UTC", utc_period)}
|
||||
end
|
||||
|
||||
def from_naive(%{calendar: Calendar.ISO} = naive_datetime, time_zone, time_zone_database) do
|
||||
case time_zone_database.time_zone_periods_from_wall_datetime(naive_datetime, time_zone) do
|
||||
{:ok, period} ->
|
||||
{:ok, from_naive_with_period(naive_datetime, time_zone, period)}
|
||||
|
||||
{:ambiguous, first_period, second_period} ->
|
||||
first_datetime = from_naive_with_period(naive_datetime, time_zone, first_period)
|
||||
second_datetime = from_naive_with_period(naive_datetime, time_zone, second_period)
|
||||
{:ambiguous, first_datetime, second_datetime}
|
||||
|
||||
{:gap, {first_period, first_period_until_wall}, {second_period, second_period_from_wall}} ->
|
||||
# `until_wall` is not valid, but any time just before is.
|
||||
# So by subtracting a second and adding .999999 seconds
|
||||
# we get the last microsecond just before.
|
||||
before_naive =
|
||||
first_period_until_wall
|
||||
|> Map.put(:microsecond, {999_999, 6})
|
||||
|> NaiveDateTime.add(-1)
|
||||
|
||||
after_naive = second_period_from_wall
|
||||
|
||||
latest_datetime_before = from_naive_with_period(before_naive, time_zone, first_period)
|
||||
first_datetime_after = from_naive_with_period(after_naive, time_zone, second_period)
|
||||
{:gap, latest_datetime_before, first_datetime_after}
|
||||
|
||||
{:error, _} = error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
def from_naive(%{calendar: calendar} = naive_datetime, time_zone, time_zone_database)
|
||||
when calendar != Calendar.ISO do
|
||||
# For non-ISO calendars, convert to ISO, create ISO DateTime, and then
|
||||
# convert to original calendar
|
||||
iso_result =
|
||||
with {:ok, in_iso} <- NaiveDateTime.convert(naive_datetime, Calendar.ISO) do
|
||||
from_naive(in_iso, time_zone, time_zone_database)
|
||||
end
|
||||
|
||||
case iso_result do
|
||||
{:ok, dt} ->
|
||||
convert(dt, calendar)
|
||||
|
||||
{:ambiguous, dt1, dt2} ->
|
||||
with {:ok, dt1converted} <- convert(dt1, calendar),
|
||||
{:ok, dt2converted} <- convert(dt2, calendar),
|
||||
do: {:ambiguous, dt1converted, dt2converted}
|
||||
|
||||
{:gap, dt1, dt2} ->
|
||||
with {:ok, dt1converted} <- convert(dt1, calendar),
|
||||
{:ok, dt2converted} <- convert(dt2, calendar),
|
||||
do: {:gap, dt1converted, dt2converted}
|
||||
|
||||
{:error, _} = error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
defp from_naive_with_period(naive_datetime, time_zone, period) do
|
||||
%{std_offset: std_offset, utc_offset: utc_offset, zone_abbr: zone_abbr} = period
|
||||
|
||||
def from_naive(%NaiveDateTime{} = naive_datetime, "Etc/UTC") do
|
||||
%{
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
@@ -202,7 +328,7 @@ defmodule DateTime do
|
||||
day: day
|
||||
} = naive_datetime
|
||||
|
||||
datetime = %DateTime{
|
||||
%DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
@@ -211,40 +337,171 @@ defmodule DateTime do
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
std_offset: 0,
|
||||
utc_offset: 0,
|
||||
zone_abbr: "UTC",
|
||||
time_zone: "Etc/UTC"
|
||||
std_offset: std_offset,
|
||||
utc_offset: utc_offset,
|
||||
zone_abbr: zone_abbr,
|
||||
time_zone: time_zone
|
||||
}
|
||||
|
||||
{:ok, datetime}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `NaiveDateTime` to `DateTime`.
|
||||
|
||||
It expects a time zone to put the NaiveDateTime in.
|
||||
Currently it only supports "Etc/UTC" as time zone.
|
||||
If the time zone is "Etc/UTC", it always succeeds. Otherwise,
|
||||
the NaiveDateTime is checked against the time zone database
|
||||
given as `time_zone_database`. See the "Time zone database"
|
||||
section in the module documentation.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> DateTime.from_naive!(~N[2016-05-24 13:26:08.003], "Etc/UTC")
|
||||
#DateTime<2016-05-24 13:26:08.003Z>
|
||||
|
||||
iex> DateTime.from_naive!(~N[2018-05-24 13:26:08.003], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
#DateTime<2018-05-24 13:26:08.003+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec from_naive!(NaiveDateTime.t(), Calendar.time_zone()) :: t
|
||||
def from_naive!(naive_datetime, time_zone) do
|
||||
case from_naive(naive_datetime, time_zone) do
|
||||
@spec from_naive!(
|
||||
NaiveDateTime.t(),
|
||||
Calendar.time_zone(),
|
||||
Calendar.time_zone_database()
|
||||
) :: t
|
||||
def from_naive!(
|
||||
naive_datetime,
|
||||
time_zone,
|
||||
time_zone_database \\ Calendar.get_time_zone_database()
|
||||
) do
|
||||
case from_naive(naive_datetime, time_zone, time_zone_database) do
|
||||
{:ok, datetime} ->
|
||||
datetime
|
||||
|
||||
{:ambiguous, dt1, dt2} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(naive_datetime)} to datetime because such " <>
|
||||
"instant is ambiguous in time zone #{time_zone} as there is an overlap " <>
|
||||
"between #{inspect(dt1)} and #{inspect(dt2)}"
|
||||
|
||||
{:gap, dt1, dt2} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(naive_datetime)} to datetime because such " <>
|
||||
"instant does not exist in time zone #{time_zone} as there is a gap " <>
|
||||
"between #{inspect(dt1)} and #{inspect(dt2)}"
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot parse #{inspect(naive_datetime)} to datetime, reason: #{inspect(reason)}"
|
||||
"cannot convert #{inspect(naive_datetime)} to datetime, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Changes the time zone of a `DateTime`.
|
||||
|
||||
Returns a `DateTime` for the same point in time, but instead at
|
||||
the time zone provided. It assumes that `DateTime` is valid and
|
||||
exists in the given time zone and calendar.
|
||||
|
||||
By default, it uses the default time zone database returned by
|
||||
`Calendar.get_time_zone_database/0`, which defaults to
|
||||
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC" datetimes.
|
||||
Other time zone databases can be passed as argument or set globally.
|
||||
See the "Time zone database" section in the module docs.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> cph_datetime = DateTime.from_naive!(~N[2018-07-16 12:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> {:ok, pacific_datetime} = DateTime.shift_zone(cph_datetime, "America/Los_Angeles", FakeTimeZoneDatabase)
|
||||
iex> pacific_datetime
|
||||
#DateTime<2018-07-16 03:00:00-07:00 PDT America/Los_Angeles>
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec shift_zone(t, Calendar.time_zone(), Calendar.time_zone_database()) ::
|
||||
{:ok, t} | {:error, :time_zone_not_found | :utc_only_time_zone_database}
|
||||
def shift_zone(datetime, time_zone, time_zone_database \\ Calendar.get_time_zone_database())
|
||||
|
||||
def shift_zone(%{time_zone: time_zone} = datetime, time_zone, _) do
|
||||
{:ok, datetime}
|
||||
end
|
||||
|
||||
def shift_zone(datetime, time_zone, time_zone_database) do
|
||||
%{
|
||||
std_offset: std_offset,
|
||||
utc_offset: utc_offset,
|
||||
calendar: calendar,
|
||||
microsecond: {_, precision}
|
||||
} = datetime
|
||||
|
||||
datetime
|
||||
|> to_iso_days()
|
||||
|> apply_tz_offset(utc_offset + std_offset)
|
||||
|> shift_zone_for_iso_days_utc(calendar, precision, time_zone, time_zone_database)
|
||||
end
|
||||
|
||||
defp shift_zone_for_iso_days_utc(iso_days_utc, calendar, precision, time_zone, time_zone_db) do
|
||||
case time_zone_db.time_zone_period_from_utc_iso_days(iso_days_utc, time_zone) do
|
||||
{:ok, %{std_offset: std_offset, utc_offset: utc_offset, zone_abbr: zone_abbr}} ->
|
||||
{year, month, day, hour, minute, second, {microsecond_without_precision, _}} =
|
||||
iso_days_utc
|
||||
|> apply_tz_offset(-(utc_offset + std_offset))
|
||||
|> calendar.naive_datetime_from_iso_days()
|
||||
|
||||
datetime = %DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond_without_precision, precision},
|
||||
std_offset: std_offset,
|
||||
utc_offset: utc_offset,
|
||||
zone_abbr: zone_abbr,
|
||||
time_zone: time_zone
|
||||
}
|
||||
|
||||
{:ok, datetime}
|
||||
|
||||
{:error, _} = error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the current datetime in the provided time zone.
|
||||
|
||||
By default, it uses the default time_zone returned by
|
||||
`Calendar.get_time_zone_database/0`, which defaults to
|
||||
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC" datetimes.
|
||||
Other time zone databases can be passed as argument or set globally.
|
||||
See the "Time zone database" section in the module docs.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, datetime} = DateTime.now("Etc/UTC")
|
||||
iex> datetime.time_zone
|
||||
"Etc/UTC"
|
||||
iex> DateTime.now("Europe/Copenhagen")
|
||||
{:error, :utc_only_time_zone_database}
|
||||
iex> DateTime.now("not a real time zone name", FakeTimeZoneDatabase)
|
||||
{:error, :time_zone_not_found}
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec now(Calendar.time_zone(), Calendar.time_zone_database()) ::
|
||||
{:ok, t} | {:error, :time_zone_not_found | :utc_only_time_zone_database}
|
||||
def now(time_zone, time_zone_database \\ Calendar.get_time_zone_database())
|
||||
|
||||
def now("Etc/UTC", _) do
|
||||
{:ok, utc_now()}
|
||||
end
|
||||
|
||||
def now(time_zone, time_zone_database) do
|
||||
shift_zone(utc_now(), time_zone, time_zone_database)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `datetime` to Unix time.
|
||||
|
||||
@@ -297,9 +554,9 @@ defmodule DateTime do
|
||||
~N[2000-02-29 23:00:07.0]
|
||||
|
||||
"""
|
||||
@spec to_naive(t) :: NaiveDateTime.t()
|
||||
def to_naive(%DateTime{} = datetime) do
|
||||
%DateTime{
|
||||
@spec to_naive(Calendar.datetime()) :: NaiveDateTime.t()
|
||||
def to_naive(datetime) do
|
||||
%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
@@ -337,8 +594,8 @@ defmodule DateTime do
|
||||
~D[2000-02-29]
|
||||
|
||||
"""
|
||||
@spec to_date(t) :: Date.t()
|
||||
def to_date(%DateTime{} = datetime) do
|
||||
@spec to_date(Calendar.datetime()) :: Date.t()
|
||||
def to_date(datetime) do
|
||||
%{year: year, month: month, day: day, calendar: calendar} = datetime
|
||||
%Date{year: year, month: month, day: day, calendar: calendar}
|
||||
end
|
||||
@@ -358,8 +615,8 @@ defmodule DateTime do
|
||||
~T[23:00:07.0]
|
||||
|
||||
"""
|
||||
@spec to_time(t) :: Time.t()
|
||||
def to_time(%DateTime{} = datetime) do
|
||||
@spec to_time(Calendar.datetime()) :: Time.t()
|
||||
def to_time(datetime) do
|
||||
%{hour: hour, minute: minute, second: second, microsecond: microsecond, calendar: calendar} =
|
||||
datetime
|
||||
|
||||
@@ -466,10 +723,10 @@ defmodule DateTime do
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
Time representations with reduced accuracy are not supported.
|
||||
|
||||
Note that while ISO 8601 allows datetimes to specify 24:00:00 as the
|
||||
zero hour of the next day, this notation is not supported by Elixir.
|
||||
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
|
||||
|
||||
@@ -485,68 +742,113 @@ defmodule DateTime do
|
||||
iex> datetime
|
||||
#DateTime<2015-01-23 21:20:07.123Z>
|
||||
|
||||
iex> {:ok, datetime, 0} = DateTime.from_iso8601("-2015-01-23T23:50:07Z")
|
||||
iex> datetime
|
||||
#DateTime<-2015-01-23 23:50:07Z>
|
||||
|
||||
iex> {:ok, datetime, 9000} = DateTime.from_iso8601("-2015-01-23T23:50:07,123+02:30")
|
||||
iex> datetime
|
||||
#DateTime<-2015-01-23 21:20:07.123Z>
|
||||
|
||||
iex> DateTime.from_iso8601("2015-01-23P23:50:07")
|
||||
{:error, :invalid_format}
|
||||
iex> DateTime.from_iso8601("2015-01-23 23:50:07A")
|
||||
{:error, :invalid_format}
|
||||
iex> DateTime.from_iso8601("2015-01-23T23:50:07")
|
||||
{:error, :missing_offset}
|
||||
iex> DateTime.from_iso8601("2015-01-23 23:50:61")
|
||||
{:error, :invalid_time}
|
||||
iex> DateTime.from_iso8601("2015-01-32 23:50:07")
|
||||
{:error, :invalid_date}
|
||||
|
||||
iex> DateTime.from_iso8601("2015-01-23T23:50:07.123-00:00")
|
||||
{:error, :invalid_format}
|
||||
iex> DateTime.from_iso8601("2015-01-23T23:50:07.123-00:60")
|
||||
{:error, :invalid_format}
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) ::
|
||||
{:ok, t, Calendar.utc_offset()} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) when is_binary(string) do
|
||||
with <<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, rest::binary>> <- string,
|
||||
true <- sep in [?\s, ?T],
|
||||
<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>> <- rest,
|
||||
{year, ""} <- Integer.parse(year),
|
||||
{month, ""} <- Integer.parse(month),
|
||||
{day, ""} <- Integer.parse(day),
|
||||
{hour, ""} <- Integer.parse(hour),
|
||||
{minute, ""} <- Integer.parse(min),
|
||||
{second, ""} <- Integer.parse(sec),
|
||||
{microsecond, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{:ok, date} <- Date.new(year, month, day),
|
||||
{:ok, time} <- Time.new(hour, minute, second, microsecond),
|
||||
{:ok, offset} <- parse_offset(rest) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
%{hour: hour, minute: minute, second: second, microsecond: microsecond} = time
|
||||
{_, precision} = microsecond
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
datetime =
|
||||
Calendar.ISO.naive_datetime_to_iso_days(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond
|
||||
)
|
||||
|> apply_tz_offset(offset)
|
||||
|> from_iso_days("Etc/UTC", "UTC", 0, 0, calendar, precision)
|
||||
|
||||
{:ok, %{datetime | microsecond: microsecond}, offset}
|
||||
else
|
||||
{:error, reason} -> {:error, reason}
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
def from_iso8601(<<?-, rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar, true)
|
||||
end
|
||||
|
||||
defp parse_offset(rest) do
|
||||
case Calendar.ISO.parse_offset(rest) do
|
||||
{offset, ""} when is_integer(offset) -> {:ok, offset}
|
||||
{nil, ""} -> {:error, :missing_offset}
|
||||
def from_iso8601(<<rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar, false)
|
||||
end
|
||||
|
||||
@sep [?\s, ?T]
|
||||
[match_date, guard_date, read_date] = Calendar.ISO.__match_date__()
|
||||
[match_time, guard_time, read_time] = Calendar.ISO.__match_time__()
|
||||
|
||||
defp raw_from_iso8601(string, calendar, is_year_negative) do
|
||||
with <<unquote(match_date), sep, unquote(match_time), rest::binary>> <- string,
|
||||
true <- unquote(guard_date) and sep in @sep and unquote(guard_time),
|
||||
{microsecond, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{offset, ""} <- Calendar.ISO.parse_offset(rest) do
|
||||
{year, month, day} = unquote(read_date)
|
||||
{hour, minute, second} = unquote(read_time)
|
||||
year = if is_year_negative, do: -year, else: year
|
||||
|
||||
cond do
|
||||
not calendar.valid_date?(year, month, day) ->
|
||||
{:error, :invalid_date}
|
||||
|
||||
not calendar.valid_time?(hour, minute, second, microsecond) ->
|
||||
{:error, :invalid_time}
|
||||
|
||||
offset == 0 ->
|
||||
datetime = %DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
std_offset: 0,
|
||||
utc_offset: 0,
|
||||
zone_abbr: "UTC",
|
||||
time_zone: "Etc/UTC"
|
||||
}
|
||||
|
||||
{:ok, datetime, 0}
|
||||
|
||||
is_nil(offset) ->
|
||||
{:error, :missing_offset}
|
||||
|
||||
true ->
|
||||
day_fraction = Calendar.ISO.time_to_day_fraction(hour, minute, second, {0, 0})
|
||||
|
||||
{{year, month, day}, {hour, minute, second, _}} =
|
||||
case apply_tz_offset({0, day_fraction}, offset) do
|
||||
{0, day_fraction} ->
|
||||
{{year, month, day}, Calendar.ISO.time_from_day_fraction(day_fraction)}
|
||||
|
||||
{extra_days, day_fraction} ->
|
||||
base_days = Calendar.ISO.date_to_iso_days(year, month, day)
|
||||
|
||||
{Calendar.ISO.date_from_iso_days(base_days + extra_days),
|
||||
Calendar.ISO.time_from_day_fraction(day_fraction)}
|
||||
end
|
||||
|
||||
datetime = %DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
std_offset: 0,
|
||||
utc_offset: 0,
|
||||
zone_abbr: "UTC",
|
||||
time_zone: "Etc/UTC"
|
||||
}
|
||||
|
||||
{:ok, datetime, offset}
|
||||
end
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
@@ -637,8 +939,8 @@ defmodule DateTime do
|
||||
@doc since: "1.4.0"
|
||||
@spec compare(Calendar.datetime(), Calendar.datetime()) :: :lt | :eq | :gt
|
||||
def compare(
|
||||
%{calendar: _, utc_offset: utc_offset1, std_offset: std_offset1} = datetime1,
|
||||
%{calendar: _, utc_offset: utc_offset2, std_offset: std_offset2} = datetime2
|
||||
%{utc_offset: utc_offset1, std_offset: std_offset1} = datetime1,
|
||||
%{utc_offset: utc_offset2, std_offset: std_offset2} = datetime2
|
||||
) do
|
||||
{days1, {parts1, ppd1}} =
|
||||
datetime1
|
||||
@@ -651,13 +953,13 @@ defmodule DateTime do
|
||||
|> apply_tz_offset(utc_offset2 + std_offset2)
|
||||
|
||||
# Ensure fraction tuples have same denominator.
|
||||
iso_days1 = {days1, parts1 * ppd2}
|
||||
iso_days2 = {days2, parts2 * ppd1}
|
||||
first = {days1, parts1 * ppd2}
|
||||
second = {days2, parts2 * ppd1}
|
||||
|
||||
case {iso_days1, iso_days2} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
cond do
|
||||
first > second -> :gt
|
||||
first < second -> :lt
|
||||
true -> :eq
|
||||
end
|
||||
end
|
||||
|
||||
@@ -686,7 +988,7 @@ defmodule DateTime do
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec diff(Calendar.datetime(), Calendar.datetime()) :: integer()
|
||||
@spec diff(Calendar.datetime(), Calendar.datetime(), System.time_unit()) :: integer()
|
||||
def diff(
|
||||
%{utc_offset: utc_offset1, std_offset: std_offset1} = datetime1,
|
||||
%{utc_offset: utc_offset2, std_offset: std_offset2} = datetime2,
|
||||
@@ -700,10 +1002,81 @@ defmodule DateTime do
|
||||
naive_diff + System.convert_time_unit(offset_diff, :second, unit)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds a specified amount of time to a `DateTime`.
|
||||
|
||||
Accepts an `amount_to_add` in any `unit` available from `t:System.time_unit/0`.
|
||||
Negative values will move backwards in time.
|
||||
|
||||
Takes changes such as summer time/DST into account. This means that adding time
|
||||
can cause the wall time to "go backwards" during "fall back" during autumn.
|
||||
Adding just a few seconds to a datetime just before "spring forward" can cause wall
|
||||
time to increase by more than an hour.
|
||||
|
||||
Fractional second precision stays the same in a similar way to `NaiveDateTime.add/2`.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> dt = DateTime.from_naive!(~N[2018-11-15 10:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> dt |> DateTime.add(3600, :second, FakeTimeZoneDatabase)
|
||||
#DateTime<2018-11-15 11:00:00+01:00 CET Europe/Copenhagen>
|
||||
|
||||
iex> dt = DateTime.from_naive!(~N[2018-11-15 10:00:00], "Etc/UTC")
|
||||
iex> dt |> DateTime.add(3600, :second)
|
||||
#DateTime<2018-11-15 11:00:00Z>
|
||||
|
||||
When adding 3 seconds just before "spring forward" we go from 1:59:59 to 3:00:02
|
||||
|
||||
iex> dt = DateTime.from_naive!(~N[2019-03-31 01:59:59.123], "Europe/Copenhagen", FakeTimeZoneDatabase)
|
||||
iex> dt |> DateTime.add(3, :second, FakeTimeZoneDatabase)
|
||||
#DateTime<2019-03-31 03:00:02.123+02:00 CEST Europe/Copenhagen>
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec add(Calendar.datetime(), integer, System.time_unit(), Calendar.time_zone_database()) ::
|
||||
t()
|
||||
def add(
|
||||
datetime,
|
||||
amount_to_add,
|
||||
unit \\ :second,
|
||||
time_zone_database \\ Calendar.get_time_zone_database()
|
||||
)
|
||||
when is_integer(amount_to_add) do
|
||||
%{
|
||||
utc_offset: utc_offset,
|
||||
std_offset: std_offset,
|
||||
calendar: calendar,
|
||||
microsecond: {_, precision}
|
||||
} = datetime
|
||||
|
||||
ppd = System.convert_time_unit(86400, :second, unit)
|
||||
total_offset = System.convert_time_unit(utc_offset + std_offset, :second, unit)
|
||||
|
||||
result =
|
||||
datetime
|
||||
|> to_iso_days()
|
||||
# Subtract total offset in order to get UTC and add the integer for the addition
|
||||
|> Calendar.ISO.add_day_fraction_to_iso_days(amount_to_add - total_offset, ppd)
|
||||
|> shift_zone_for_iso_days_utc(calendar, precision, datetime.time_zone, time_zone_database)
|
||||
|
||||
case result do
|
||||
{:ok, result_datetime} ->
|
||||
result_datetime
|
||||
|
||||
{:error, error} ->
|
||||
raise ArgumentError,
|
||||
"cannot add #{amount_to_add} #{unit} to #{inspect(datetime)} (with time zone " <>
|
||||
"database #{inspect(time_zone_database)}), reason: #{inspect(error)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the given datetime with the microsecond field truncated to the given
|
||||
precision (`:microsecond`, `millisecond` or `:second`).
|
||||
|
||||
The given datetime is returned unchanged if it already has lower precision than
|
||||
the given precision.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt1 = %DateTime{year: 2017, month: 11, day: 7, zone_abbr: "CET",
|
||||
@@ -726,11 +1099,15 @@ defmodule DateTime do
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec truncate(t(), :microsecond | :millisecond | :second) :: t()
|
||||
@spec truncate(Calendar.datetime(), :microsecond | :millisecond | :second) :: t()
|
||||
def truncate(%DateTime{microsecond: microsecond} = datetime, precision) do
|
||||
%{datetime | microsecond: Calendar.truncate(microsecond, precision)}
|
||||
end
|
||||
|
||||
def truncate(%{} = datetime_map, precision) do
|
||||
truncate(from_map(datetime_map), precision)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a given `datetime` from one calendar to another.
|
||||
|
||||
@@ -758,42 +1135,14 @@ defmodule DateTime do
|
||||
@spec convert(Calendar.datetime(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, :incompatible_calendars}
|
||||
|
||||
# Keep it multiline for proper function clause errors.
|
||||
def convert(
|
||||
%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
time_zone: time_zone,
|
||||
zone_abbr: zone_abbr,
|
||||
utc_offset: utc_offset,
|
||||
std_offset: std_offset
|
||||
},
|
||||
calendar
|
||||
) do
|
||||
datetime = %DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
time_zone: time_zone,
|
||||
zone_abbr: zone_abbr,
|
||||
utc_offset: utc_offset,
|
||||
std_offset: std_offset
|
||||
}
|
||||
|
||||
def convert(%DateTime{calendar: calendar} = datetime, calendar) do
|
||||
{:ok, datetime}
|
||||
end
|
||||
|
||||
def convert(%{calendar: calendar} = datetime, calendar) do
|
||||
{:ok, from_map(datetime)}
|
||||
end
|
||||
|
||||
def convert(%{calendar: dt_calendar, microsecond: {_, precision}} = datetime, calendar) do
|
||||
if Calendar.compatible_calendars?(dt_calendar, calendar) do
|
||||
result_datetime =
|
||||
@@ -830,7 +1179,7 @@ defmodule DateTime do
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec convert!(Calendar.datetime(), Calendar.calendar()) :: t | no_return
|
||||
@spec convert!(Calendar.datetime(), Calendar.calendar()) :: t
|
||||
def convert!(datetime, calendar) do
|
||||
case convert(datetime, calendar) do
|
||||
{:ok, value} ->
|
||||
@@ -862,10 +1211,6 @@ defmodule DateTime do
|
||||
%{time_zone: time_zone, zone_abbr: zone_abbr, utc_offset: utc_offset, std_offset: std_offset} =
|
||||
datetime
|
||||
|
||||
from_iso_days(iso_days, time_zone, zone_abbr, utc_offset, std_offset, calendar, precision)
|
||||
end
|
||||
|
||||
defp from_iso_days(iso_days, time_zone, zone_abbr, utc_offset, std_offset, calendar, precision) do
|
||||
{year, month, day, hour, minute, second, {microsecond, _}} =
|
||||
calendar.naive_datetime_from_iso_days(iso_days)
|
||||
|
||||
@@ -885,10 +1230,30 @@ defmodule DateTime do
|
||||
}
|
||||
end
|
||||
|
||||
defp apply_tz_offset(iso_days, 0) do
|
||||
iso_days
|
||||
end
|
||||
|
||||
defp apply_tz_offset(iso_days, offset) do
|
||||
Calendar.ISO.add_day_fraction_to_iso_days(iso_days, -offset, 86400)
|
||||
end
|
||||
|
||||
defp from_map(%{} = datetime_map) do
|
||||
%DateTime{
|
||||
year: datetime_map.year,
|
||||
month: datetime_map.month,
|
||||
day: datetime_map.day,
|
||||
hour: datetime_map.hour,
|
||||
minute: datetime_map.minute,
|
||||
second: datetime_map.second,
|
||||
microsecond: datetime_map.microsecond,
|
||||
time_zone: datetime_map.time_zone,
|
||||
zone_abbr: datetime_map.zone_abbr,
|
||||
utc_offset: datetime_map.utc_offset,
|
||||
std_offset: datetime_map.std_offset
|
||||
}
|
||||
end
|
||||
|
||||
defimpl String.Chars do
|
||||
def to_string(datetime) do
|
||||
%{
|
||||
|
||||
+242
-62
@@ -26,8 +26,9 @@ defmodule Calendar.ISO do
|
||||
|
||||
@seconds_per_minute 60
|
||||
@seconds_per_hour 60 * 60
|
||||
# Note that this does _not_ handle leap seconds.
|
||||
# Note that this does *not* handle leap seconds.
|
||||
@seconds_per_day 24 * 60 * 60
|
||||
@last_second_of_the_day @seconds_per_day - 1
|
||||
@microseconds_per_second 1_000_000
|
||||
@parts_per_day @seconds_per_day * @microseconds_per_second
|
||||
|
||||
@@ -36,6 +37,44 @@ defmodule Calendar.ISO do
|
||||
|
||||
@months_in_year 12
|
||||
|
||||
# The ISO epoch starts, in this implementation,
|
||||
# with ~D[0000-01-01]. Era "1" starts
|
||||
# on ~D[0001-01-01] which is 366 days later.
|
||||
@iso_epoch 366
|
||||
|
||||
@doc false
|
||||
def __match_date__ do
|
||||
quote do
|
||||
[
|
||||
<<y1, y2, y3, y4, ?-, m1, m2, ?-, d1, d2>>,
|
||||
y1 >= ?0 and y1 <= ?9 and y2 >= ?0 and y2 <= ?9 and y3 >= ?0 and y3 <= ?9 and y4 >= ?0 and
|
||||
y4 <= ?9 and m1 >= ?0 and m1 <= ?9 and m2 >= ?0 and m2 <= ?9 and d1 >= ?0 and d1 <= ?9 and
|
||||
d2 >= ?0 and d2 <= ?9,
|
||||
{
|
||||
(y1 - ?0) * 1000 + (y2 - ?0) * 100 + (y3 - ?0) * 10 + (y4 - ?0),
|
||||
(m1 - ?0) * 10 + (m2 - ?0),
|
||||
(d1 - ?0) * 10 + (d2 - ?0)
|
||||
}
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def __match_time__ do
|
||||
quote do
|
||||
[
|
||||
<<h1, h2, ?:, i1, i2, ?:, s1, s2>>,
|
||||
h1 >= ?0 and h1 <= ?9 and h2 >= ?0 and h2 <= ?9 and i1 >= ?0 and i1 <= ?9 and i2 >= ?0 and
|
||||
i2 <= ?9 and s1 >= ?0 and s1 <= ?9 and s2 >= ?0 and s2 <= ?9,
|
||||
{
|
||||
(h1 - ?0) * 10 + (h2 - ?0),
|
||||
(i1 - ?0) * 10 + (i2 - ?0),
|
||||
(s1 - ?0) * 10 + (s2 - ?0)
|
||||
}
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the `t:Calendar.iso_days/0` format of the specified date.
|
||||
|
||||
@@ -141,8 +180,12 @@ defmodule Calendar.ISO do
|
||||
@impl true
|
||||
@spec time_from_day_fraction(Calendar.day_fraction()) ::
|
||||
{Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()}
|
||||
def time_from_day_fraction({0, _}) do
|
||||
{0, 0, 0, {0, 6}}
|
||||
end
|
||||
|
||||
def time_from_day_fraction({parts_in_day, parts_per_day}) do
|
||||
total_microseconds = div(parts_in_day * @parts_per_day, parts_per_day)
|
||||
total_microseconds = divide_by_parts_per_day(parts_in_day, parts_per_day)
|
||||
|
||||
{hours, rest_microseconds1} =
|
||||
div_mod(total_microseconds, @seconds_per_hour * @microseconds_per_second)
|
||||
@@ -154,9 +197,13 @@ defmodule Calendar.ISO do
|
||||
{hours, minutes, seconds, {microseconds, 6}}
|
||||
end
|
||||
|
||||
defp divide_by_parts_per_day(parts_in_day, @parts_per_day), do: parts_in_day
|
||||
|
||||
defp divide_by_parts_per_day(parts_in_day, parts_per_day),
|
||||
do: div(parts_in_day * @parts_per_day, parts_per_day)
|
||||
|
||||
# Converts year, month, day to count of days since 0000-01-01.
|
||||
@doc false
|
||||
@doc since: "1.5.0"
|
||||
def date_to_iso_days(0, 1, 1) do
|
||||
0
|
||||
end
|
||||
@@ -174,23 +221,13 @@ defmodule Calendar.ISO do
|
||||
|
||||
# Converts count of days since 0000-01-01 to {year, month, day} tuple.
|
||||
@doc false
|
||||
@doc since: "1.5.0"
|
||||
def date_from_iso_days(days) when days in 0..3_652_424 do
|
||||
def date_from_iso_days(days) when days in -3_652_059..3_652_424 do
|
||||
{year, day_of_year} = days_to_year(days)
|
||||
extra_day = if leap_year?(year), do: 1, else: 0
|
||||
{month, day_in_month} = year_day_to_year_date(extra_day, day_of_year)
|
||||
{year, month, day_in_month + 1}
|
||||
end
|
||||
|
||||
def date_from_iso_days(days) when days in -3_652_059..-1 do
|
||||
{year, day_of_year} = days_to_year(-days)
|
||||
previous_extra_day = if leap_year?(year), do: 1, else: 0
|
||||
extra_day = if leap_year?(year + 1), do: 1, else: 0
|
||||
day_of_year = @days_per_nonleap_year + extra_day - day_of_year
|
||||
{month, day_in_month} = year_day_to_year_date(extra_day, day_of_year)
|
||||
{-year - 1, month, day_in_month + previous_extra_day}
|
||||
end
|
||||
|
||||
defp div_mod(int1, int2) do
|
||||
div = div(int1, int2)
|
||||
rem = int1 - div * int2
|
||||
@@ -302,7 +339,123 @@ defmodule Calendar.ISO do
|
||||
@impl true
|
||||
def day_of_week(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
Integer.mod(date_to_iso_days(year, month, day) + 5, 7) + 1
|
||||
iso_days_to_day_of_week(date_to_iso_days(year, month, day))
|
||||
end
|
||||
|
||||
defp iso_days_to_day_of_week(iso_days) do
|
||||
Integer.mod(iso_days + 5, 7) + 1
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the day of the year from the given `year`, `month`, and `day`.
|
||||
|
||||
It is an integer from 1 to 366.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.day_of_year(2016, 1, 31)
|
||||
31
|
||||
iex> Calendar.ISO.day_of_year(-99, 2, 1)
|
||||
32
|
||||
iex> Calendar.ISO.day_of_year(2018, 2, 28)
|
||||
59
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec day_of_year(year, month, day) :: 1..366
|
||||
@impl true
|
||||
def day_of_year(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
true = day <= days_in_month(year, month)
|
||||
days_before_month(month) + leap_day_offset(year, month) + day
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the quarter of the year from the given `year`, `month`, and `day`.
|
||||
|
||||
It is an integer from 1 to 4.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.quarter_of_year(2016, 1, 31)
|
||||
1
|
||||
iex> Calendar.ISO.quarter_of_year(2016, 4, 3)
|
||||
2
|
||||
iex> Calendar.ISO.quarter_of_year(-99, 9, 31)
|
||||
3
|
||||
iex> Calendar.ISO.quarter_of_year(2018, 12, 28)
|
||||
4
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec quarter_of_year(year, month, day) :: 1..4
|
||||
@impl true
|
||||
def quarter_of_year(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
div(month - 1, 3) + 1
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the year and era from the given `year`.
|
||||
|
||||
The ISO calendar has two eras: the current era which
|
||||
starts in year 1 and is defined as era "1". And a
|
||||
second era for those years less than 1 defined as
|
||||
era "0".
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.year_of_era(1)
|
||||
{1, 1}
|
||||
iex> Calendar.ISO.year_of_era(2018)
|
||||
{2018, 1}
|
||||
iex> Calendar.ISO.year_of_era(0)
|
||||
{1, 0}
|
||||
iex> Calendar.ISO.year_of_era(-1)
|
||||
{2, 0}
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec year_of_era(year) :: {year, era :: 0..1}
|
||||
@impl true
|
||||
def year_of_era(year) when is_integer(year) and year > 0 do
|
||||
{year, 1}
|
||||
end
|
||||
|
||||
def year_of_era(year) when is_integer(year) and year < 1 do
|
||||
{abs(year) + 1, 0}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the day and era from the given `year`, `month`, and `day`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.day_of_era(0, 1, 1)
|
||||
{366, 0}
|
||||
iex> Calendar.ISO.day_of_era(1, 1, 1)
|
||||
{1, 1}
|
||||
iex> Calendar.ISO.day_of_era(0, 12, 31)
|
||||
{1, 0}
|
||||
iex> Calendar.ISO.day_of_era(0, 12, 30)
|
||||
{2, 0}
|
||||
iex> Calendar.ISO.day_of_era(-1, 12, 31)
|
||||
{367, 0}
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec day_of_era(year, month, day) :: {day :: pos_integer(), era :: 0..1}
|
||||
@impl true
|
||||
def day_of_era(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) and year > 0 do
|
||||
day = date_to_iso_days(year, month, day) - @iso_epoch + 1
|
||||
{day, 1}
|
||||
end
|
||||
|
||||
def day_of_era(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) and year < 1 do
|
||||
day = abs(date_to_iso_days(year, month, day) - @iso_epoch)
|
||||
{day, 0}
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -351,12 +504,12 @@ defmodule Calendar.ISO do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.date_to_string(2015, 2, 28)
|
||||
"2015-02-28"
|
||||
iex> Calendar.ISO.date_to_string(2017, 8, 1)
|
||||
"2017-08-01"
|
||||
iex> Calendar.ISO.date_to_string(-99, 1, 31)
|
||||
"-0099-01-31"
|
||||
iex> Calendar.ISO.date_to_string(2015, 2, 28)
|
||||
"2015-02-28"
|
||||
iex> Calendar.ISO.date_to_string(2017, 8, 1)
|
||||
"2017-08-01"
|
||||
iex> Calendar.ISO.date_to_string(-99, 1, 31)
|
||||
"-0099-01-31"
|
||||
|
||||
"""
|
||||
@spec date_to_string(year, month, day) :: String.t()
|
||||
@@ -378,10 +531,10 @@ defmodule Calendar.ISO do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.naive_datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 6})
|
||||
"2015-02-28 01:02:03.000004"
|
||||
iex> Calendar.ISO.naive_datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5})
|
||||
"2017-08-01 01:02:03.00000"
|
||||
iex> Calendar.ISO.naive_datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 6})
|
||||
"2015-02-28 01:02:03.000004"
|
||||
iex> Calendar.ISO.naive_datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5})
|
||||
"2017-08-01 01:02:03.00000"
|
||||
|
||||
"""
|
||||
@impl true
|
||||
@@ -403,14 +556,17 @@ defmodule Calendar.ISO do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, "Europe/Berlin", "CET", 3600, 0)
|
||||
"2017-08-01 01:02:03.00000+01:00 CET Europe/Berlin"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, "Europe/Berlin", "CDT", 3600, 3600)
|
||||
"2017-08-01 01:02:03.00000+02:00 CDT Europe/Berlin"
|
||||
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, "America/Los_Angeles", "PST", -28800, 0)
|
||||
"2015-02-28 01:02:03.00000-08:00 PST America/Los_Angeles"
|
||||
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, "America/Los_Angeles", "PDT", -28800, 3600)
|
||||
"2015-02-28 01:02:03.00000-07:00 PDT America/Los_Angeles"
|
||||
iex> time_zone = "Europe/Berlin"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "CET", 3600, 0)
|
||||
"2017-08-01 01:02:03.00000+01:00 CET Europe/Berlin"
|
||||
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "CDT", 3600, 3600)
|
||||
"2017-08-01 01:02:03.00000+02:00 CDT Europe/Berlin"
|
||||
|
||||
iex> time_zone = "America/Los_Angeles"
|
||||
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, time_zone, "PST", -28800, 0)
|
||||
"2015-02-28 01:02:03.00000-08:00 PST America/Los_Angeles"
|
||||
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, time_zone, "PDT", -28800, 3600)
|
||||
"2015-02-28 01:02:03.00000-07:00 PDT America/Los_Angeles"
|
||||
|
||||
"""
|
||||
@impl true
|
||||
@@ -452,49 +608,52 @@ defmodule Calendar.ISO do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.valid_date?(2015, 2, 28)
|
||||
true
|
||||
iex> Calendar.ISO.valid_date?(2015, 2, 30)
|
||||
false
|
||||
iex> Calendar.ISO.valid_date?(-1, 12, 31)
|
||||
true
|
||||
iex> Calendar.ISO.valid_date?(-1, 12, 32)
|
||||
false
|
||||
iex> Calendar.ISO.valid_date?(2015, 2, 28)
|
||||
true
|
||||
iex> Calendar.ISO.valid_date?(2015, 2, 30)
|
||||
false
|
||||
iex> Calendar.ISO.valid_date?(-1, 12, 31)
|
||||
true
|
||||
iex> Calendar.ISO.valid_date?(-1, 12, 32)
|
||||
false
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@impl true
|
||||
@spec valid_date?(year, month, day) :: boolean
|
||||
def valid_date?(year, month, day) do
|
||||
month in 1..12 and year in -9999..9999 and day in 1..days_in_month(year, month)
|
||||
month in 1..12 and year in -9999..9999 and
|
||||
(is_integer(day) and day >= 1 and day <= days_in_month(year, month))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Determines if the date given is valid according to the proleptic Gregorian calendar.
|
||||
Note that leap seconds are considered valid, but the use of 24:00:00 as the
|
||||
zero hour of the day is considered invalid.
|
||||
|
||||
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> Calendar.ISO.valid_time?(10, 50, 25, {3006, 6})
|
||||
true
|
||||
iex> Calendar.ISO.valid_time?(23, 59, 60, {0, 0})
|
||||
true
|
||||
iex> Calendar.ISO.valid_time?(24, 0, 0, {0, 0})
|
||||
false
|
||||
iex> Calendar.ISO.valid_time?(10, 50, 25, {3006, 6})
|
||||
true
|
||||
iex> Calendar.ISO.valid_time?(23, 59, 60, {0, 0})
|
||||
false
|
||||
iex> Calendar.ISO.valid_time?(24, 0, 0, {0, 0})
|
||||
false
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@impl true
|
||||
@spec valid_time?(Calendar.hour(), Calendar.minute(), Calendar.secon(), Calendar.microsecond()) ::
|
||||
@spec valid_time?(Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()) ::
|
||||
boolean
|
||||
def valid_time?(hour, minute, second, {microsecond, precision}) do
|
||||
hour in 0..23 and minute in 0..59 and second in 0..60 and microsecond in 0..999_999 and
|
||||
hour in 0..23 and minute in 0..59 and second in 0..59 and microsecond in 0..999_999 and
|
||||
precision in 0..6
|
||||
end
|
||||
|
||||
@doc """
|
||||
See `c:Calendar.day_rollover_relative_to_midlight_utc/0` for documentation.
|
||||
See `c:Calendar.day_rollover_relative_to_midnight_utc/0` for documentation.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@impl true
|
||||
@@ -530,7 +689,7 @@ defmodule Calendar.ISO do
|
||||
|
||||
defp zero_pad(val, count) when val >= 0 do
|
||||
num = Integer.to_string(val)
|
||||
:binary.copy("0", count - byte_size(num)) <> num
|
||||
:binary.copy("0", max(count - byte_size(num), 0)) <> num
|
||||
end
|
||||
|
||||
defp zero_pad(val, count) do
|
||||
@@ -566,7 +725,6 @@ defmodule Calendar.ISO do
|
||||
do: precision_for_unit(div(number, 10), precision + 1)
|
||||
|
||||
@doc false
|
||||
@doc since: "1.5.0"
|
||||
def date_to_iso8601(year, month, day, format \\ :extended) do
|
||||
date_to_string(year, month, day, format)
|
||||
end
|
||||
@@ -671,15 +829,13 @@ defmodule Calendar.ISO do
|
||||
end
|
||||
|
||||
@doc false
|
||||
@doc since: "1.5.0"
|
||||
def iso_days_to_unit({days, {parts, ppd}}, unit) do
|
||||
day_microseconds = days * @parts_per_day
|
||||
microseconds = div(parts * @parts_per_day, ppd)
|
||||
microseconds = divide_by_parts_per_day(parts, ppd)
|
||||
System.convert_time_unit(day_microseconds + microseconds, :microsecond, unit)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@doc since: "1.5.0"
|
||||
def add_day_fraction_to_iso_days({days, {parts, ppd}}, add, ppd) do
|
||||
normalize_iso_days(days, parts + add, ppd)
|
||||
end
|
||||
@@ -726,13 +882,30 @@ defmodule Calendar.ISO do
|
||||
if leap_year?(year), do: 1, else: 0
|
||||
end
|
||||
|
||||
defp days_to_year(days) when days < 0 do
|
||||
year_estimate = -div(-days, @days_per_nonleap_year) - 1
|
||||
|
||||
{year, days_before_year} =
|
||||
days_to_year(year_estimate, days, days_to_end_of_epoch(year_estimate))
|
||||
|
||||
leap_year_pad = if leap_year?(year), do: 1, else: 0
|
||||
{year, leap_year_pad + @days_per_nonleap_year + days - days_before_year}
|
||||
end
|
||||
|
||||
defp days_to_year(days) do
|
||||
year = Integer.floor_div(days, @days_per_nonleap_year)
|
||||
{year, days_before_year} = days_to_year(year, days, days_in_previous_years(year))
|
||||
year_estimate = div(days, @days_per_nonleap_year)
|
||||
|
||||
{year, days_before_year} =
|
||||
days_to_year(year_estimate, days, days_in_previous_years(year_estimate))
|
||||
|
||||
{year, days - days_before_year}
|
||||
end
|
||||
|
||||
defp days_to_year(year, days1, days2) when days1 < days2 do
|
||||
defp days_to_year(year, days1, days2) when year < 0 and days1 >= days2 do
|
||||
days_to_year(year + 1, days1, days_to_end_of_epoch(year + 1))
|
||||
end
|
||||
|
||||
defp days_to_year(year, days1, days2) when year >= 0 and days1 < days2 do
|
||||
days_to_year(year - 1, days1, days_in_previous_years(year - 1))
|
||||
end
|
||||
|
||||
@@ -740,6 +913,13 @@ defmodule Calendar.ISO do
|
||||
{year, days2}
|
||||
end
|
||||
|
||||
defp days_to_end_of_epoch(year) when year < 0 do
|
||||
previous_year = year + 1
|
||||
|
||||
div(previous_year, 4) - div(previous_year, 100) + div(previous_year, 400) +
|
||||
previous_year * @days_per_nonleap_year
|
||||
end
|
||||
|
||||
defp days_in_previous_years(0), do: 0
|
||||
|
||||
defp days_in_previous_years(year) do
|
||||
@@ -807,7 +987,7 @@ defmodule Calendar.ISO do
|
||||
{date, time}
|
||||
end
|
||||
|
||||
defp seconds_to_time(seconds) when seconds in 0..(@seconds_per_day - 1) do
|
||||
defp seconds_to_time(seconds) when seconds in 0..@last_second_of_the_day do
|
||||
{hour, rest_seconds} = div_mod(seconds, @seconds_per_hour)
|
||||
{minute, second} = div_mod(rest_seconds, @seconds_per_minute)
|
||||
|
||||
|
||||
@@ -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`](`Kernel.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]
|
||||
@@ -28,14 +28,9 @@ defmodule NaiveDateTime do
|
||||
`NaiveDateTime` is not validated against a time zone, such errors
|
||||
would go unnoticed.
|
||||
|
||||
The functions of this module work with the `NaiveDateTime` struct as well
|
||||
as any struct that contains the same fields as the `NaiveDateTime` struct,
|
||||
such as `DateTime`. Such functions expect
|
||||
`t:Calendar.naive_datetime/0` in their typespecs (instead of `t:t/0`).
|
||||
|
||||
Developers should avoid creating the NaiveDateTime structs directly
|
||||
and instead, rely on the functions provided by this module as well
|
||||
as the ones in 3rd party calendar libraries.
|
||||
as the ones in third-party calendar libraries.
|
||||
|
||||
## Comparing naive date times
|
||||
|
||||
@@ -72,7 +67,7 @@ defmodule NaiveDateTime do
|
||||
calendar: Calendar.ISO
|
||||
]
|
||||
|
||||
@type t :: %NaiveDateTime{
|
||||
@type t :: %__MODULE__{
|
||||
year: Calendar.year(),
|
||||
month: Calendar.month(),
|
||||
day: Calendar.day(),
|
||||
@@ -146,13 +141,11 @@ defmodule NaiveDateTime do
|
||||
{:ok, ~N[2000-01-01 23:59:59.0]}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 59, 999_999)
|
||||
{:ok, ~N[2000-01-01 23:59:59.999999]}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 60, 999_999)
|
||||
{:ok, ~N[2000-01-01 23:59:60.999999]}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 24, 59, 59, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 60, 59, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 61, 999_999)
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 60, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 59, 1_000_000)
|
||||
{:error, :invalid_time}
|
||||
@@ -171,10 +164,35 @@ defmodule NaiveDateTime do
|
||||
Calendar.microsecond(),
|
||||
Calendar.calendar()
|
||||
) :: {:ok, t} | {:error, atom}
|
||||
def new(year, month, day, hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
|
||||
with {:ok, date} <- Date.new(year, month, day, calendar),
|
||||
{:ok, time} <- Time.new(hour, minute, second, microsecond, calendar),
|
||||
do: new(date, time)
|
||||
def new(year, month, day, hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
|
||||
def new(year, month, day, hour, minute, second, microsecond, calendar)
|
||||
when is_integer(microsecond) do
|
||||
new(year, month, day, hour, minute, second, {microsecond, 6}, calendar)
|
||||
end
|
||||
|
||||
def new(year, month, day, hour, minute, second, microsecond, calendar) do
|
||||
cond do
|
||||
not calendar.valid_date?(year, month, day) ->
|
||||
{:error, :invalid_date}
|
||||
|
||||
not calendar.valid_time?(hour, minute, second, microsecond) ->
|
||||
{:error, :invalid_time}
|
||||
|
||||
true ->
|
||||
naive_datetime = %NaiveDateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}
|
||||
|
||||
{:ok, naive_datetime}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -210,11 +228,9 @@ defmodule NaiveDateTime do
|
||||
@doc """
|
||||
Adds a specified amount of time to a `NaiveDateTime`.
|
||||
|
||||
Accepts an `integer` in any `unit` available from `t:System.time_unit/0`.
|
||||
Accepts an `amount_to_add` in any `unit` available from `t:System.time_unit/0`.
|
||||
Negative values will move backwards in time.
|
||||
|
||||
This operation is only possible if both calendars are convertible to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
# adds seconds by default
|
||||
@@ -242,17 +258,29 @@ defmodule NaiveDateTime do
|
||||
iex> NaiveDateTime.add(~N[0000-01-01 00:00:00], 63_579_428_950)
|
||||
~N[2014-10-02 00:29:10]
|
||||
|
||||
Passing a `Datetime` automatically converts it to `NaiveDateTime`,
|
||||
discarding the time zone information:
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "CET",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
|
||||
iex> NaiveDateTime.add(dt, 21, :second)
|
||||
~N[2000-02-29 23:00:28]
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec add(t, integer, System.time_unit()) :: t
|
||||
def add(%NaiveDateTime{} = naive_datetime, integer, unit \\ :second)
|
||||
when is_integer(integer) do
|
||||
%{microsecond: {_, precision}, calendar: calendar} = naive_datetime
|
||||
@spec add(Calendar.naive_datetime(), integer, System.time_unit()) :: t
|
||||
def add(
|
||||
%{microsecond: {_, precision}, calendar: calendar} = naive_datetime,
|
||||
amount_to_add,
|
||||
unit \\ :second
|
||||
)
|
||||
when is_integer(amount_to_add) do
|
||||
ppd = System.convert_time_unit(86400, :second, unit)
|
||||
|
||||
naive_datetime
|
||||
|> to_iso_days()
|
||||
|> Calendar.ISO.add_day_fraction_to_iso_days(integer, ppd)
|
||||
|> Calendar.ISO.add_day_fraction_to_iso_days(amount_to_add, ppd)
|
||||
|> from_iso_days(calendar, precision)
|
||||
end
|
||||
|
||||
@@ -283,13 +311,13 @@ defmodule NaiveDateTime do
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec diff(t, t, System.time_unit()) :: integer
|
||||
@spec diff(Calendar.naive_datetime(), Calendar.naive_datetime(), System.time_unit()) :: integer
|
||||
def diff(
|
||||
%NaiveDateTime{} = naive_datetime1,
|
||||
%NaiveDateTime{} = naive_datetime2,
|
||||
%{calendar: calendar1} = naive_datetime1,
|
||||
%{calendar: calendar2} = naive_datetime2,
|
||||
unit \\ :second
|
||||
) do
|
||||
if not Calendar.compatible_calendars?(naive_datetime1.calendar, naive_datetime2.calendar) do
|
||||
if not Calendar.compatible_calendars?(calendar1, calendar2) do
|
||||
raise ArgumentError,
|
||||
"cannot calculate the difference between #{inspect(naive_datetime1)} and " <>
|
||||
"#{inspect(naive_datetime2)} because their calendars are not compatible " <>
|
||||
@@ -305,6 +333,9 @@ defmodule NaiveDateTime do
|
||||
Returns the given naive datetime with the microsecond field truncated to the
|
||||
given precision (`:microsecond`, `:millisecond` or `:second`).
|
||||
|
||||
The given naive datetime is returned unchanged if it already has lower precision
|
||||
than the given precision.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :microsecond)
|
||||
@@ -323,6 +354,31 @@ defmodule NaiveDateTime do
|
||||
%{naive_datetime | microsecond: Calendar.truncate(microsecond, precision)}
|
||||
end
|
||||
|
||||
def truncate(
|
||||
%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
},
|
||||
precision
|
||||
) do
|
||||
%NaiveDateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: Calendar.truncate(microsecond, precision)
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `NaiveDateTime` into a `Date`.
|
||||
|
||||
@@ -335,11 +391,24 @@ defmodule NaiveDateTime do
|
||||
~D[2002-01-13]
|
||||
|
||||
"""
|
||||
@spec to_date(t) :: Date.t()
|
||||
@spec to_date(Calendar.naive_datetime()) :: Date.t()
|
||||
def to_date(%NaiveDateTime{year: year, month: month, day: day, calendar: calendar}) do
|
||||
%Date{year: year, month: month, day: day, calendar: calendar}
|
||||
end
|
||||
|
||||
def to_date(%{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
calendar: calendar,
|
||||
hour: _,
|
||||
minute: _,
|
||||
second: _,
|
||||
microsecond: _
|
||||
}) do
|
||||
%Date{year: year, month: month, day: day, calendar: calendar}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `NaiveDateTime` into `Time`.
|
||||
|
||||
@@ -352,7 +421,7 @@ defmodule NaiveDateTime do
|
||||
~T[23:00:07]
|
||||
|
||||
"""
|
||||
@spec to_time(t) :: Time.t()
|
||||
@spec to_time(Calendar.naive_datetime()) :: Time.t()
|
||||
def to_time(%NaiveDateTime{} = naive_datetime) do
|
||||
%{
|
||||
hour: hour,
|
||||
@@ -371,6 +440,25 @@ defmodule NaiveDateTime do
|
||||
}
|
||||
end
|
||||
|
||||
def to_time(%{
|
||||
year: _,
|
||||
month: _,
|
||||
day: _,
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}) do
|
||||
%Time{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given naive datetime to a string according to its calendar.
|
||||
|
||||
@@ -412,17 +500,17 @@ defmodule NaiveDateTime do
|
||||
Parses the extended "Date and time of day" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Timezone offset may be included in the string but they will be
|
||||
Time zone offset may be included in the string but they will be
|
||||
simply discarded as such information is not included in naive date
|
||||
times.
|
||||
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
Time representations with reduced accuracy are not supported.
|
||||
|
||||
Note that while ISO 8601 allows datetimes to specify 24:00:00 as the
|
||||
zero hour of the next day, this notation is not supported by Elixir.
|
||||
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
|
||||
|
||||
@@ -470,26 +558,31 @@ defmodule NaiveDateTime do
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<?-, next, rest::binary>>, calendar) when next != ?- do
|
||||
with {:ok, %{year: year} = naive_datetime} <- from_iso8601(<<next>> <> rest, calendar) do
|
||||
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(string, calendar) when is_binary(string) do
|
||||
with <<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, rest::binary>> <- string,
|
||||
true <- sep in [?\s, ?T],
|
||||
<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>> <- rest,
|
||||
{year, ""} <- Integer.parse(year),
|
||||
{month, ""} <- Integer.parse(month),
|
||||
{day, ""} <- Integer.parse(day),
|
||||
{hour, ""} <- Integer.parse(hour),
|
||||
{min, ""} <- Integer.parse(min),
|
||||
{sec, ""} <- Integer.parse(sec),
|
||||
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
|
||||
with {:ok, utc_date} <- new(year, month, day, hour, min, sec, microsec, Calendar.ISO),
|
||||
do: convert(utc_date, calendar)
|
||||
{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
|
||||
@@ -511,7 +604,7 @@ defmodule NaiveDateTime do
|
||||
** (ArgumentError) cannot parse "2015-01-23P23:50:07" as naive datetime, reason: :invalid_format
|
||||
|
||||
"""
|
||||
@spec from_iso8601!(String.t(), Calendar.calendar()) :: t | no_return
|
||||
@spec from_iso8601!(String.t(), Calendar.calendar()) :: t
|
||||
def from_iso8601!(string, calendar \\ Calendar.ISO) do
|
||||
case from_iso8601(string, calendar) do
|
||||
{:ok, value} ->
|
||||
@@ -641,8 +734,8 @@ defmodule NaiveDateTime do
|
||||
def from_erl(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_erl({{year, month, day}, {hour, minute, second}}, microsecond, calendar) do
|
||||
with {:ok, utc_date} <- new(year, month, day, hour, minute, second, microsecond),
|
||||
do: convert(utc_date, calendar)
|
||||
with {:ok, iso_naive_dt} <- new(year, month, day, hour, minute, second, microsecond),
|
||||
do: convert(iso_naive_dt, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -661,8 +754,7 @@ defmodule NaiveDateTime do
|
||||
** (ArgumentError) cannot convert {{2000, 13, 1}, {13, 30, 15}} to naive datetime, reason: :invalid_date
|
||||
|
||||
"""
|
||||
@spec from_erl!(:calendar.datetime(), Calendar.microsecond(), Calendar.calendar()) ::
|
||||
t | no_return
|
||||
@spec from_erl!(:calendar.datetime(), Calendar.microsecond(), Calendar.calendar()) :: t
|
||||
def from_erl!(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
|
||||
case from_erl(tuple, microsecond, calendar) do
|
||||
{:ok, value} ->
|
||||
|
||||
@@ -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`](`Kernel.sigil_T/2`) sigil:
|
||||
`~T` (see `Kernel.sigil_T/2`) sigil:
|
||||
|
||||
iex> ~T[23:00:07.001]
|
||||
~T[23:00:07.001]
|
||||
@@ -25,7 +25,7 @@ defmodule Time do
|
||||
|
||||
Developers should avoid creating the Time structs directly
|
||||
and instead rely on the functions provided by this module as well
|
||||
as the ones in 3rd party calendar libraries.
|
||||
as the ones in third-party calendar libraries.
|
||||
|
||||
## Comparing times
|
||||
|
||||
@@ -37,7 +37,7 @@ defmodule Time do
|
||||
@enforce_keys [:hour, :minute, :second]
|
||||
defstruct [:hour, :minute, :second, microsecond: {0, 0}, calendar: Calendar.ISO]
|
||||
|
||||
@type t :: %Time{
|
||||
@type t :: %__MODULE__{
|
||||
hour: Calendar.hour(),
|
||||
minute: Calendar.minute(),
|
||||
second: Calendar.second(),
|
||||
@@ -45,6 +45,8 @@ defmodule Time do
|
||||
calendar: Calendar.calendar()
|
||||
}
|
||||
|
||||
@parts_per_day 86_400_000_000
|
||||
|
||||
@doc """
|
||||
Returns the current time in UTC.
|
||||
|
||||
@@ -78,9 +80,10 @@ defmodule Time do
|
||||
Expects all values to be integers. Returns `{:ok, time}` if each
|
||||
entry fits its appropriate range, returns `{:error, reason}` otherwise.
|
||||
|
||||
Note a time may have 60 seconds in case of leap seconds. Microseconds
|
||||
can also be given with a precision, which must be an integer between
|
||||
0 and 6.
|
||||
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
|
||||
|
||||
@@ -88,18 +91,12 @@ defmodule Time do
|
||||
{:ok, ~T[00:00:00.000000]}
|
||||
iex> Time.new(23, 59, 59, 999_999)
|
||||
{:ok, ~T[23:59:59.999999]}
|
||||
iex> Time.new(23, 59, 60, 999_999)
|
||||
{:ok, ~T[23:59:60.999999]}
|
||||
|
||||
# Time with microseconds and their precision
|
||||
iex> Time.new(23, 59, 60, {10_000, 2})
|
||||
{:ok, ~T[23:59:60.01]}
|
||||
|
||||
iex> Time.new(24, 59, 59, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> Time.new(23, 60, 59, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> Time.new(23, 59, 61, 999_999)
|
||||
iex> Time.new(23, 59, 60, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> Time.new(23, 59, 59, 1_000_000)
|
||||
{:error, :invalid_time}
|
||||
@@ -177,7 +174,7 @@ defmodule Time do
|
||||
Parses the extended "Local time" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Timezone offset may be included in the string but they will be
|
||||
Time zone offset may be included in the string but they will be
|
||||
simply discarded as such information is not included in times.
|
||||
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
@@ -187,6 +184,7 @@ defmodule Time do
|
||||
|
||||
Note that while ISO 8601 allows times to specify 24:00:00 as the
|
||||
zero hour of the next day, this notation is not supported by Elixir.
|
||||
Leap seconds are not supported as well by the built-in Calendar.ISO.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -217,27 +215,31 @@ defmodule Time do
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<?T, h, rest::binary>>, calendar) when h in ?0..?9 do
|
||||
from_iso8601(<<h, rest::binary>>, calendar)
|
||||
def from_iso8601(<<?T, rest::binary>>, calendar) do
|
||||
raw_from_iso8601(rest, calendar)
|
||||
end
|
||||
|
||||
def from_iso8601(<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>>, calendar) do
|
||||
with {hour, ""} <- Integer.parse(hour),
|
||||
{min, ""} <- Integer.parse(min),
|
||||
{sec, ""} <- Integer.parse(sec),
|
||||
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
|
||||
with {:ok, utc_time} <- new(hour, min, sec, microsec, Calendar.ISO),
|
||||
do: convert(utc_time, calendar)
|
||||
{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
|
||||
|
||||
def from_iso8601(<<_::binary>>, _calendar) do
|
||||
{:error, :invalid_format}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Local time" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
@@ -401,12 +403,9 @@ defmodule Time do
|
||||
@spec add(Calendar.time(), integer, System.time_unit()) :: t
|
||||
def add(%{calendar: calendar} = time, number, unit \\ :second) when is_integer(number) do
|
||||
number = System.convert_time_unit(number, unit, :microsecond)
|
||||
iso_days = {0, to_day_fraction(time)}
|
||||
total = Calendar.ISO.iso_days_to_unit(iso_days, :microsecond) + number
|
||||
iso_ppd = 86_400_000_000
|
||||
parts = Integer.mod(total, iso_ppd)
|
||||
|
||||
{hour, minute, second, microsecond} = calendar.time_from_day_fraction({parts, iso_ppd})
|
||||
total = time_to_microseconds(time) + number
|
||||
parts = Integer.mod(total, @parts_per_day)
|
||||
{hour, minute, second, microsecond} = calendar.time_from_day_fraction({parts, @parts_per_day})
|
||||
|
||||
%Time{
|
||||
hour: hour,
|
||||
@@ -417,6 +416,21 @@ defmodule Time do
|
||||
}
|
||||
end
|
||||
|
||||
defp time_to_microseconds(%{
|
||||
calendar: Calendar.ISO,
|
||||
hour: 0,
|
||||
minute: 0,
|
||||
second: 0,
|
||||
microsecond: {0, _}
|
||||
}) do
|
||||
0
|
||||
end
|
||||
|
||||
defp time_to_microseconds(time) do
|
||||
iso_days = {0, to_day_fraction(time)}
|
||||
Calendar.ISO.iso_days_to_unit(iso_days, :microsecond)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two time structs.
|
||||
|
||||
@@ -593,7 +607,33 @@ defmodule Time do
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec diff(Calendar.time(), Calendar.time(), System.time_unit()) :: integer
|
||||
def diff(time1, time2, unit \\ :second) do
|
||||
def diff(time1, time2, unit \\ :second)
|
||||
|
||||
def diff(
|
||||
%{
|
||||
calendar: Calendar.ISO,
|
||||
hour: hour1,
|
||||
minute: minute1,
|
||||
second: second1,
|
||||
microsecond: {microsecond1, @parts_per_day}
|
||||
},
|
||||
%{
|
||||
calendar: Calendar.ISO,
|
||||
hour: hour2,
|
||||
minute: minute2,
|
||||
second: second2,
|
||||
microsecond: {microsecond2, @parts_per_day}
|
||||
},
|
||||
unit
|
||||
) do
|
||||
total =
|
||||
(hour1 - hour2) * 3_600_000_000 + (minute1 - minute2) * 60_000_000 +
|
||||
(second1 - second2) * 1_000_000 + (microsecond1 - microsecond2)
|
||||
|
||||
System.convert_time_unit(total, :microsecond, unit)
|
||||
end
|
||||
|
||||
def diff(time1, time2, unit) do
|
||||
fraction1 = to_day_fraction(time1)
|
||||
fraction2 = to_day_fraction(time2)
|
||||
|
||||
@@ -605,6 +645,9 @@ defmodule Time do
|
||||
Returns the given time with the microsecond field truncated to the given
|
||||
precision (`:microsecond`, `millisecond` or `:second`).
|
||||
|
||||
The given time is returned unchanged if it already has lower precision than
|
||||
the given precision.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.truncate(~T[01:01:01.123456], :microsecond)
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
defmodule Calendar.TimeZoneDatabase do
|
||||
@moduledoc """
|
||||
This module defines a behaviour for providing time zone data.
|
||||
|
||||
IANA provides time zone data that includes data about different
|
||||
UTC offsets and standard offsets for time zones.
|
||||
"""
|
||||
|
||||
@typedoc """
|
||||
A period where a certain combination of UTC offset, standard offset and zone
|
||||
abbreviation is in effect.
|
||||
|
||||
For instance one period could be the summer of 2018 in "Europe/London" where summer time /
|
||||
daylight saving time is in effect and lasts from spring to autumn. At autumn the `std_offset`
|
||||
changes along with the `zone_abbr` so a different period is needed during winter.
|
||||
"""
|
||||
@type time_zone_period :: %{
|
||||
optional(any) => any,
|
||||
utc_offset: Calendar.utc_offset(),
|
||||
std_offset: Calendar.std_offset(),
|
||||
zone_abbr: Calendar.zone_abbr()
|
||||
}
|
||||
|
||||
@typedoc """
|
||||
Limit for when a certain time zone period begins or ends.
|
||||
|
||||
A beginning is inclusive. An ending is exclusive. Eg. if a period is from
|
||||
2015-03-29 01:00:00 and until 2015-10-25 01:00:00, the period includes and
|
||||
begins from the begining of 2015-03-29 01:00:00 and lasts until just before
|
||||
2015-10-25 01:00:00.
|
||||
|
||||
A beginning or end for certain periods are infinite. For instance the latest
|
||||
period for time zones without DST or plans to change. However for the purpose
|
||||
of this behaviour they are only used for gaps in wall time where the needed
|
||||
period limits are at a certain time.
|
||||
"""
|
||||
@type time_zone_period_limit :: Calendar.naive_datetime()
|
||||
|
||||
@doc """
|
||||
Time zone period for a point in time in UTC for a specific time zone.
|
||||
|
||||
Takes a time zone name and a point in time for UTC and returns a
|
||||
`time_zone_period` for that point in time.
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@callback time_zone_period_from_utc_iso_days(Calendar.iso_days(), Calendar.time_zone()) ::
|
||||
{:ok, time_zone_period}
|
||||
| {:error, :time_zone_not_found | :utc_only_time_zone_database}
|
||||
|
||||
@doc """
|
||||
Possible time zone periods for a certain time zone and wall clock date and time.
|
||||
|
||||
When the provided `datetime` is ambiguous a tuple with `:ambiguous` and two possible
|
||||
periods. The periods in the list are sorted with the first element being the one that begins first.
|
||||
|
||||
When the provided `datetime` is in a gap - for instance during the "spring forward" when going
|
||||
from winter time to summer time, a tuple with `:gap` and two periods with limits are returned
|
||||
in a nested tuple. The first nested two-tuple is the period before the gap and a naive datetime
|
||||
with a limit for when the period ends (wall time). The second nested two-tuple is the period
|
||||
just after the gap and a datetime (wall time) for when the period begins just after the gap.
|
||||
|
||||
If there is only a single possible period for the provided `datetime`, the a tuple with `:single`
|
||||
and the `time_zone_period` is returned.
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@callback time_zone_periods_from_wall_datetime(Calendar.naive_datetime(), Calendar.time_zone()) ::
|
||||
{:ok, time_zone_period}
|
||||
| {:ambiguous, time_zone_period, time_zone_period}
|
||||
| {:gap, {time_zone_period, time_zone_period_limit},
|
||||
{time_zone_period, time_zone_period_limit}}
|
||||
| {:error, :time_zone_not_found | :utc_only_time_zone_database}
|
||||
end
|
||||
|
||||
defmodule Calendar.UTCOnlyTimeZoneDatabase do
|
||||
@moduledoc """
|
||||
Built-in time zone database that works only in Etc/UTC.
|
||||
|
||||
For all other time zones, it returns `{:error, :utc_only_time_zone_database}`.
|
||||
"""
|
||||
|
||||
@behaviour Calendar.TimeZoneDatabase
|
||||
|
||||
@impl true
|
||||
def time_zone_period_from_utc_iso_days(_, "Etc/UTC"),
|
||||
do: {:ok, %{std_offset: 0, utc_offset: 0, zone_abbr: "UTC"}}
|
||||
|
||||
def time_zone_period_from_utc_iso_days(_, _),
|
||||
do: {:error, :utc_only_time_zone_database}
|
||||
|
||||
@impl true
|
||||
def time_zone_periods_from_wall_datetime(_, "Etc/UTC"),
|
||||
do: {:ok, %{std_offset: 0, utc_offset: 0, zone_abbr: "UTC"}}
|
||||
|
||||
def time_zone_periods_from_wall_datetime(_, _),
|
||||
do: {:error, :utc_only_time_zone_database}
|
||||
end
|
||||
+22
-21
@@ -26,7 +26,7 @@ defmodule Code do
|
||||
times. This is common in scripts.
|
||||
|
||||
`compile_file/2` must be used when you are interested in the modules defined in a
|
||||
file, without tracking. `eval_file/2` should be used when you are intested on
|
||||
file, without tracking. `eval_file/2` should be used when you are interested in
|
||||
the result of evaluating the file rather than the modules it defines.
|
||||
"""
|
||||
|
||||
@@ -416,7 +416,7 @@ defmodule Code do
|
||||
rules in the future. The goal of documenting them is to provide better
|
||||
understanding on what to expect from the formatter.
|
||||
|
||||
### Multi-line lists, maps, tuples, etc
|
||||
### Multi-line lists, maps, tuples, etc.
|
||||
|
||||
You can force lists, tuples, bitstrings, maps, structs and function
|
||||
calls to have one entry per line by adding a newline after the opening
|
||||
@@ -697,7 +697,7 @@ defmodule Code do
|
||||
|
||||
Accepts `relative_to` as an argument to tell where the file is located.
|
||||
|
||||
While `require_file/2` and `compile_file/2` returns the loaded modules and their
|
||||
While `require_file/2` and `compile_file/2` return the loaded modules and their
|
||||
bytecode, `eval_file/2` simply evaluates the file contents and returns the
|
||||
evaluation result and its bindings (exactly the same return value as `eval_string/3`).
|
||||
"""
|
||||
@@ -732,7 +732,7 @@ defmodule Code do
|
||||
others will get `nil`.
|
||||
|
||||
See `compile_file/2` if you would like to compile a file without tracking its
|
||||
filenames. Finally, if you would like to get the result of evaluating file rather
|
||||
filenames. Finally, if you would like to get the result of evaluating a file rather
|
||||
than the modules defined in it, see `eval_file/2`.
|
||||
|
||||
## Examples
|
||||
@@ -743,7 +743,7 @@ defmodule Code do
|
||||
List.first(modules)
|
||||
#=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>}
|
||||
|
||||
If the code has been required, it returns `nil`:
|
||||
If the file has been required, it returns `nil`:
|
||||
|
||||
Code.require_file("eex_test.exs", "../eex/test")
|
||||
#=> nil
|
||||
@@ -790,7 +790,7 @@ defmodule Code do
|
||||
@doc """
|
||||
Returns a list with the available compiler options.
|
||||
|
||||
See `compiler_options/1` for more info.
|
||||
See `compiler_options/1` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -809,11 +809,11 @@ defmodule Code do
|
||||
The compiler utilizes temporary modules to compile code. For example,
|
||||
`elixir_compiler_1`, `elixir_compiler_2`, etc. In case the compiled code
|
||||
stores references to anonymous functions or similar, the Elixir compiler
|
||||
may be unable to reclaim those modules, keeping an unecessary amount of
|
||||
may be unable to reclaim those modules, keeping an unnecessary amount of
|
||||
code in memory and eventually leading to modules such as `elixir_compiler_12345`.
|
||||
|
||||
This function purges all modules currently kept by the compiler, allowing
|
||||
old compiler module names to be resued. If there are any processes running
|
||||
old compiler module names to be reused. If there are any processes running
|
||||
any code from such modules, they will be terminated too.
|
||||
|
||||
It returns `{:ok, number_of_modules_purged}`.
|
||||
@@ -1047,7 +1047,7 @@ defmodule Code do
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Returns the docs for the given module.
|
||||
Returns the docs for the given module or path to `.beam` file.
|
||||
|
||||
When given a module name, it finds its BEAM code and reads the docs from it.
|
||||
|
||||
@@ -1072,19 +1072,20 @@ defmodule Code do
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec fetch_docs(module | String.t()) ::
|
||||
{:docs_v1, anno, beam_language, format, module_doc :: doc, metadata,
|
||||
docs :: [{{kind, name, arity}, anno, signature, doc, metadata}]}
|
||||
{:docs_v1, annotation, beam_language, format, module_doc :: doc_content, metadata,
|
||||
docs :: [doc_element]}
|
||||
| {:error, :module_not_found | :chunk_not_found | {:invalid_chunk, binary}}
|
||||
| future_formats
|
||||
when anno: :erl_anno.anno(),
|
||||
beam_language: atom,
|
||||
when annotation: :erl_anno.anno(),
|
||||
beam_language: :elixir | :erlang | :lfe | :alpaca | atom(),
|
||||
doc_content: %{binary => binary} | :none | :hidden,
|
||||
doc_element:
|
||||
{{kind :: atom, function_name :: atom, arity}, annotation, signature, doc_content,
|
||||
metadata},
|
||||
format: binary,
|
||||
doc: %{binary => binary} | :none | :hidden,
|
||||
kind: atom,
|
||||
name: atom,
|
||||
signature: [binary],
|
||||
metadata: map,
|
||||
future_formats: term
|
||||
metadata: map
|
||||
def fetch_docs(module_or_path)
|
||||
|
||||
def fetch_docs(module) when is_atom(module) do
|
||||
case :code.get_object_code(module) do
|
||||
{_module, bin, _beam_path} -> do_fetch_docs(bin)
|
||||
@@ -1092,8 +1093,8 @@ defmodule Code do
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_docs(binpath) when is_binary(binpath) do
|
||||
do_fetch_docs(String.to_charlist(binpath))
|
||||
def fetch_docs(path) when is_binary(path) do
|
||||
do_fetch_docs(String.to_charlist(path))
|
||||
end
|
||||
|
||||
@docs_chunk 'Docs'
|
||||
|
||||
@@ -367,24 +367,24 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp quoted_to_algebra(
|
||||
{{:., _, [String, :to_charlist]}, _, [{:<<>>, meta, entries}]} = quoted,
|
||||
{{:., _, [List, :to_charlist]}, meta, [entries]} = quoted,
|
||||
context,
|
||||
state
|
||||
) do
|
||||
cond do
|
||||
not interpolated?(entries) ->
|
||||
not list_interpolated?(entries) ->
|
||||
remote_to_algebra(quoted, context, state)
|
||||
|
||||
meta[:format] == :list_heredoc ->
|
||||
{doc, state} =
|
||||
entries
|
||||
|> prepend_heredoc_line()
|
||||
|> interpolation_to_algebra(:heredoc, state, @single_heredoc, @single_heredoc)
|
||||
|> list_interpolation_to_algebra(:heredoc, state, @single_heredoc, @single_heredoc)
|
||||
|
||||
{force_unfit(doc), state}
|
||||
|
||||
true ->
|
||||
interpolation_to_algebra(entries, @single_quote, state, @single_quote, @single_quote)
|
||||
list_interpolation_to_algebra(entries, @single_quote, state, @single_quote, @single_quote)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -716,14 +716,21 @@ defmodule Code.Formatter do
|
||||
{concat(op_string, doc), @empty, newlines, state}
|
||||
end
|
||||
|
||||
operand_to_algebra_with_comments(
|
||||
operands,
|
||||
meta,
|
||||
min_line,
|
||||
max_line,
|
||||
state,
|
||||
operand_to_algebra
|
||||
)
|
||||
{doc, state} =
|
||||
operand_to_algebra_with_comments(
|
||||
operands,
|
||||
meta,
|
||||
min_line,
|
||||
max_line,
|
||||
state,
|
||||
operand_to_algebra
|
||||
)
|
||||
|
||||
if keyword?(right_arg) and context in [:parens_arg, :no_parens_arg] do
|
||||
{wrap_in_parens(doc), state}
|
||||
else
|
||||
{doc, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp binary_op_to_algebra(op, _, meta, left_arg, right_arg, context, state, _nesting)
|
||||
@@ -772,13 +779,16 @@ defmodule Code.Formatter do
|
||||
concat(concat(group(left), op_string), group(right))
|
||||
|
||||
true ->
|
||||
eol? = eol?(meta)
|
||||
|
||||
next_break_fits? =
|
||||
op in @next_break_fits_operators and next_break_fits?(right_arg, state) and
|
||||
not Keyword.get(meta, :eol, false)
|
||||
op in @next_break_fits_operators and next_break_fits?(right_arg, state) and not eol?
|
||||
|
||||
with_next_break_fits(next_break_fits?, right, fn right ->
|
||||
op_string = " " <> op_string
|
||||
concat(group(left), group(nest(glue(op_string, group(right)), nesting, :break)))
|
||||
right = nest(glue(op_string, group(right)), nesting, :break)
|
||||
right = if eol?, do: force_unfit(right), else: right
|
||||
concat(group(left), group(right))
|
||||
end)
|
||||
end
|
||||
|
||||
@@ -877,7 +887,7 @@ defmodule Code.Formatter do
|
||||
{docs, comments?, state} =
|
||||
quoted_to_algebra_with_comments(operands, [], min_line, max_line, 1, state, fun)
|
||||
|
||||
if comments? or Keyword.get(meta, :eol, false) do
|
||||
if comments? or eol?(meta) do
|
||||
{docs |> Enum.reduce(&line(&2, &1)) |> force_unfit(), state}
|
||||
else
|
||||
{docs |> Enum.reduce(&glue(&2, &1)), state}
|
||||
@@ -1052,6 +1062,8 @@ defmodule Code.Formatter do
|
||||
defp deprecated(Enum, :partition, 2), do: {"split_with", "~> 1.4"}
|
||||
defp deprecated(Code, :unload_files, 2), do: {"unrequire_files", "~> 1.7"}
|
||||
defp deprecated(Code, :loaded_files, 2), do: {"required_files", "~> 1.7"}
|
||||
defp deprecated(Kernel.ParallelCompiler, :files, 2), do: {"compile", "~> 1.6"}
|
||||
defp deprecated(Kernel.ParallelCompiler, :files_to_path, 2), do: {"compile_to_path", "~> 1.6"}
|
||||
defp deprecated(_, _, _), do: :error
|
||||
|
||||
defp remote_target_to_algebra({:fn, _, [_ | _]} = quoted, state) do
|
||||
@@ -1138,7 +1150,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
args = if keyword?, do: left ++ right, else: left ++ [right]
|
||||
many_eol? = match?([_, _ | _], args) and Keyword.get(meta, :eol, false)
|
||||
many_eol? = match?([_, _ | _], args) and eol?(meta)
|
||||
no_generators? = no_generators?(args)
|
||||
to_algebra_fun = "ed_to_algebra(&1, context, &2)
|
||||
|
||||
@@ -1294,6 +1306,14 @@ defmodule Code.Formatter do
|
||||
|
||||
## Interpolation
|
||||
|
||||
defp list_interpolated?(entries) do
|
||||
Enum.all?(entries, fn
|
||||
{{:., _, [Kernel, :to_string]}, _, [_]} -> true
|
||||
entry when is_binary(entry) -> true
|
||||
_ -> false
|
||||
end)
|
||||
end
|
||||
|
||||
defp interpolated?(entries) do
|
||||
Enum.all?(entries, fn
|
||||
{:::, _, [{{:., _, [Kernel, :to_string]}, _, [_]}, {:binary, _, _}]} -> true
|
||||
@@ -1310,6 +1330,23 @@ defmodule Code.Formatter do
|
||||
["\n" | entries]
|
||||
end
|
||||
|
||||
defp list_interpolation_to_algebra([entry | entries], escape, state, acc, last)
|
||||
when is_binary(entry) do
|
||||
acc = concat(acc, escape_string(entry, escape))
|
||||
list_interpolation_to_algebra(entries, escape, state, acc, last)
|
||||
end
|
||||
|
||||
defp list_interpolation_to_algebra([entry | entries], escape, state, acc, last) do
|
||||
{{:., _, [Kernel, :to_string]}, meta, [quoted]} = entry
|
||||
{doc, state} = block_to_algebra(quoted, line(meta), end_line(meta), state)
|
||||
doc = surround("\#{", doc, "}")
|
||||
list_interpolation_to_algebra(entries, escape, state, concat(acc, doc), last)
|
||||
end
|
||||
|
||||
defp list_interpolation_to_algebra([], _escape, state, acc, last) do
|
||||
{concat(acc, last), state}
|
||||
end
|
||||
|
||||
defp interpolation_to_algebra([entry | entries], escape, state, acc, last)
|
||||
when is_binary(entry) do
|
||||
acc = concat(acc, escape_string(entry, escape))
|
||||
@@ -1365,7 +1402,7 @@ defmodule Code.Formatter do
|
||||
|
||||
defp bitstring_to_algebra(meta, args, state) do
|
||||
last = length(args) - 1
|
||||
join = if Keyword.get(meta, :eol, false), do: :line, else: :flex_break
|
||||
join = if eol?(meta), do: :line, else: :flex_break
|
||||
to_algebra_fun = &bitstring_segment_to_algebra(&1, &2, last)
|
||||
|
||||
{args_doc, join, state} =
|
||||
@@ -1433,7 +1470,7 @@ defmodule Code.Formatter do
|
||||
## Literals
|
||||
|
||||
defp list_to_algebra(meta, args, state) do
|
||||
join = if Keyword.get(meta, :eol, false), do: :line, else: :break
|
||||
join = if eol?(meta), do: :line, else: :break
|
||||
fun = "ed_to_algebra(&1, :parens_arg, &2)
|
||||
|
||||
{args_doc, _join, state} =
|
||||
@@ -1443,7 +1480,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp map_to_algebra(meta, name_doc, [{:|, _, [left, right]}], state) do
|
||||
join = if Keyword.get(meta, :eol, false), do: :line, else: :break
|
||||
join = if eol?(meta), do: :line, else: :break
|
||||
fun = "ed_to_algebra(&1, :parens_arg, &2)
|
||||
{left_doc, state} = fun.(left, state)
|
||||
|
||||
@@ -1460,7 +1497,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp map_to_algebra(meta, name_doc, args, state) do
|
||||
join = if Keyword.get(meta, :eol, false), do: :line, else: :break
|
||||
join = if eol?(meta), do: :line, else: :break
|
||||
fun = "ed_to_algebra(&1, :parens_arg, &2)
|
||||
|
||||
{args_doc, _join, state} =
|
||||
@@ -1471,7 +1508,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp tuple_to_algebra(meta, args, join, state) do
|
||||
join = if Keyword.get(meta, :eol, false), do: :line, else: join
|
||||
join = if eol?(meta), do: :line, else: join
|
||||
fun = "ed_to_algebra(&1, :parens_arg, &2)
|
||||
|
||||
{args_doc, join, state} =
|
||||
@@ -1754,7 +1791,7 @@ defmodule Code.Formatter do
|
||||
## Clauses
|
||||
|
||||
defp maybe_force_clauses(doc, clauses) do
|
||||
if Enum.any?(clauses, fn {:->, meta, _} -> Keyword.get(meta, :eol, false) end) do
|
||||
if Enum.any?(clauses, fn {:->, meta, _} -> eol?(meta) end) do
|
||||
force_unfit(doc)
|
||||
else
|
||||
doc
|
||||
@@ -2090,7 +2127,7 @@ defmodule Code.Formatter do
|
||||
(not interpolated?(entries) and eol_or_comments?(meta, state))
|
||||
end
|
||||
|
||||
defp next_break_fits?({{:., _, [String, :to_charlist]}, _, [{:<<>>, meta, [_ | _]}]}, _state) do
|
||||
defp next_break_fits?({{:., _, [List, :to_charlist]}, meta, [[_ | _]]}, _state) do
|
||||
meta[:format] == :list_heredoc
|
||||
end
|
||||
|
||||
@@ -2124,7 +2161,7 @@ defmodule Code.Formatter do
|
||||
end
|
||||
|
||||
defp eol_or_comments?(meta, %{comments: comments}) do
|
||||
Keyword.get(meta, :eol, false) or
|
||||
eol?(meta) or
|
||||
(
|
||||
min_line = line(meta)
|
||||
max_line = end_line(meta)
|
||||
|
||||
@@ -87,7 +87,7 @@ defmodule Code.Identifier do
|
||||
:alias
|
||||
|
||||
true ->
|
||||
case :elixir_config.safe_get(:identifier_tokenizer, String.Tokenizer).tokenize(charlist) do
|
||||
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
|
||||
|
||||
@@ -152,37 +152,23 @@ defmodule Code.Typespec do
|
||||
end
|
||||
end
|
||||
|
||||
# TODO: Do not rely on abstract_code when OTP 20+ support is dropped (v1.8).
|
||||
# We should then be able to simplify this code and use `with`.
|
||||
defp typespecs_abstract_code(module) do
|
||||
case get_module_and_beam(module) do
|
||||
{module, binary} ->
|
||||
case :beam_lib.chunks(binary, [:debug_info]) do
|
||||
{:ok, {_, [debug_info: {:debug_info_v1, backend, data}]}} ->
|
||||
case data do
|
||||
{:elixir_v1, %{}, specs} ->
|
||||
# Fast path to avoid translation to Erlang from Elixir.
|
||||
{:ok, specs}
|
||||
with {module, binary} <- get_module_and_beam(module),
|
||||
{:ok, {_, [debug_info: {:debug_info_v1, backend, data}]}} <-
|
||||
:beam_lib.chunks(binary, [:debug_info]) do
|
||||
case data do
|
||||
{:elixir_v1, %{}, specs} ->
|
||||
# Fast path to avoid translation to Erlang from Elixir.
|
||||
{:ok, specs}
|
||||
|
||||
_ ->
|
||||
case backend.debug_info(:erlang_v1, module, data, []) do
|
||||
{:ok, abstract_code} -> {:ok, abstract_code}
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
_ ->
|
||||
case :beam_lib.chunks(binary, [:abstract_code]) do
|
||||
{:ok, {_, [{:abstract_code, {_raw_abstract_v1, abstract_code}}]}} ->
|
||||
{:ok, abstract_code}
|
||||
|
||||
_ ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
:error ->
|
||||
:error
|
||||
_ ->
|
||||
case backend.debug_info(:erlang_v1, module, data, []) do
|
||||
{:ok, abstract_code} -> {:ok, abstract_code}
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ defprotocol Collectable do
|
||||
implementation for `MapSet`. In this implementation "collecting" elements
|
||||
simply means inserting them in the set through `MapSet.put/2`.
|
||||
|
||||
defimpl Collectable do
|
||||
defimpl Collectable, for: MapSet do
|
||||
def into(original) do
|
||||
collector_fun = fn
|
||||
set, {:cont, elem} -> MapSet.put(set, elem)
|
||||
@@ -79,6 +79,16 @@ end
|
||||
|
||||
defimpl Collectable, for: List do
|
||||
def into(original) do
|
||||
if original != [] do
|
||||
IO.warn(
|
||||
"the Collectable protocol is deprecated for non-empty lists. The behaviour of " <>
|
||||
"things like Enum.into/2 or \"for\" comprehensions with an :into option is incorrect " <>
|
||||
"when collecting into non-empty lists. If you're collecting into a non-empty keyword " <>
|
||||
"list, consider using Keyword.merge/2 instead. If you're collecting into a non-empty " <>
|
||||
"list, consider concatenating the two lists with the ++ operator."
|
||||
)
|
||||
end
|
||||
|
||||
fun = fn
|
||||
list, {:cont, x} -> [x | list]
|
||||
list, :done -> original ++ :lists.reverse(list)
|
||||
|
||||
@@ -295,7 +295,7 @@ defmodule Dict do
|
||||
end
|
||||
|
||||
@deprecated message
|
||||
@spec fetch!(t, key) :: value | no_return
|
||||
@spec fetch!(t, key) :: value
|
||||
def fetch!(dict, key) do
|
||||
target(dict).fetch!(dict, key)
|
||||
end
|
||||
|
||||
@@ -6,7 +6,7 @@ defmodule DynamicSupervisor do
|
||||
that are started in the given order when the supervisor starts. A
|
||||
`DynamicSupervisor` starts with no children. Instead, children are
|
||||
started on demand via `start_child/2`. When a dynamic supervisor
|
||||
terminates, all children are shutdown at the same time, with no guarantee
|
||||
terminates, all children are shut down at the same time, with no guarantee
|
||||
of ordering.
|
||||
|
||||
## Examples
|
||||
@@ -58,7 +58,9 @@ defmodule DynamicSupervisor do
|
||||
end
|
||||
|
||||
See the `Supervisor` docs for a discussion of when you may want to use
|
||||
module-based supervisors.
|
||||
module-based supervisors. The `@doc` annotation immediately preceding
|
||||
`use DymamicSupervisor` will be attached to the generated `child_spec/1`
|
||||
function.
|
||||
|
||||
## Name registration
|
||||
|
||||
@@ -89,7 +91,7 @@ defmodule DynamicSupervisor do
|
||||
def init(initial_arg) do
|
||||
children = [
|
||||
# Or the deprecated: worker(MyWorker, [initial_arg])
|
||||
%{id: MyWorker, start: {MyWorker, :start_link, [initial_arg]})
|
||||
%{id: MyWorker, start: {MyWorker, :start_link, [initial_arg]}}
|
||||
]
|
||||
|
||||
Supervisor.init(children, strategy: :simple_one_for_one)
|
||||
@@ -135,7 +137,7 @@ defmodule DynamicSupervisor do
|
||||
Developers typically invoke `DynamicSupervisor.init/1` at the end of
|
||||
their init callback to return the proper supervision flags.
|
||||
"""
|
||||
@callback init(args :: term) :: {:ok, sup_flags()} | :ignore
|
||||
@callback init(init_arg :: term) :: {:ok, sup_flags()} | :ignore
|
||||
|
||||
@typedoc "The supervisor flags returned on init"
|
||||
@type sup_flags() :: %{
|
||||
@@ -170,6 +172,7 @@ defmodule DynamicSupervisor do
|
||||
| :ignore
|
||||
| {:error, {:already_started, pid} | :max_children | term}
|
||||
|
||||
# In this struct, `args` refers to the arguments passed to init/1 (the `init_arg`).
|
||||
defstruct [
|
||||
:args,
|
||||
:extra_arguments,
|
||||
@@ -208,12 +211,14 @@ defmodule DynamicSupervisor do
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@behaviour DynamicSupervisor
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
See `Supervisor`.
|
||||
"""
|
||||
end
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
@@ -277,8 +282,8 @@ defmodule DynamicSupervisor do
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec start_link(module, term, GenServer.options()) :: Supervisor.on_start()
|
||||
def start_link(mod, args, opts \\ []) do
|
||||
GenServer.start_link(__MODULE__, {mod, args, opts[:name]}, opts)
|
||||
def start_link(mod, init_arg, opts \\ []) do
|
||||
GenServer.start_link(__MODULE__, {mod, init_arg, opts[:name]}, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -305,7 +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) ::
|
||||
@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)
|
||||
@@ -462,13 +467,13 @@ defmodule DynamicSupervisor do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives a set of options that initializes a dynamic supervisor.
|
||||
Receives a set of `options` that initializes a dynamic supervisor.
|
||||
|
||||
This is typically invoked at the end of the `c:init/1` callback of
|
||||
module-based supervisors. See the sections "Module-based supervisors"
|
||||
module-based supervisors. See the "Module-based supervisors" section
|
||||
in the module documentation for more information.
|
||||
|
||||
The options received by this function are also supported by `start_link/2`.
|
||||
The `options` received by this function are also supported by `start_link/2`.
|
||||
|
||||
This function returns a tuple containing the supervisor options.
|
||||
|
||||
@@ -527,11 +532,11 @@ defmodule DynamicSupervisor do
|
||||
## Callbacks
|
||||
|
||||
@impl true
|
||||
def init({mod, args, name}) do
|
||||
def init({mod, init_arg, name}) do
|
||||
Process.put(:"$initial_call", {:supervisor, mod, 1})
|
||||
Process.flag(:trap_exit, true)
|
||||
|
||||
case mod.init(args) do
|
||||
case mod.init(init_arg) do
|
||||
{:ok, flags} when is_map(flags) ->
|
||||
name =
|
||||
cond do
|
||||
@@ -540,7 +545,7 @@ defmodule DynamicSupervisor do
|
||||
is_tuple(name) -> name
|
||||
end
|
||||
|
||||
state = %DynamicSupervisor{mod: mod, args: args, name: name}
|
||||
state = %DynamicSupervisor{mod: mod, args: init_arg, name: name}
|
||||
|
||||
case init(state, flags) do
|
||||
{:ok, state} -> {:ok, state}
|
||||
@@ -745,8 +750,8 @@ defmodule DynamicSupervisor do
|
||||
end
|
||||
|
||||
@impl true
|
||||
def code_change(_, %{mod: mod, args: args} = state, _) do
|
||||
case mod.init(args) do
|
||||
def code_change(_, %{mod: mod, args: init_arg} = state, _) do
|
||||
case mod.init(init_arg) do
|
||||
{:ok, flags} when is_map(flags) ->
|
||||
case init(state, flags) do
|
||||
{:ok, state} -> {:ok, state}
|
||||
|
||||
+159
-123
@@ -31,7 +31,7 @@ defprotocol Enumerable do
|
||||
while also guaranteeing the resource will be closed at the end of the
|
||||
enumeration. This protocol also allows suspension of the enumeration,
|
||||
which is useful when interleaving between many enumerables is required
|
||||
(as in zip).
|
||||
(as in the `zip/1` and `zip/2` functions).
|
||||
|
||||
This protocol requires four functions to be implemented, `reduce/3`,
|
||||
`count/1`, `member?/2`, and `slice/1`. The core of the protocol is the
|
||||
@@ -61,7 +61,7 @@ defprotocol Enumerable do
|
||||
@typedoc """
|
||||
The reducer function.
|
||||
|
||||
Should be called with the enumerable element and the
|
||||
Should be called with the `enumerable` element and the
|
||||
accumulator contents.
|
||||
|
||||
Returns the accumulator for the next enumeration step.
|
||||
@@ -107,7 +107,7 @@ defprotocol Enumerable do
|
||||
number of elements in the slice.
|
||||
|
||||
The `start` position is a number `>= 0` and guaranteed to
|
||||
exist in the enumerable. The length is a number `>= 1` in a way
|
||||
exist in the `enumerable`. The length is a number `>= 1` in a way
|
||||
that `start + length <= count`, where `count` is the maximum
|
||||
amount of elements in the enumerable.
|
||||
|
||||
@@ -117,11 +117,11 @@ defprotocol Enumerable do
|
||||
@type slicing_fun :: (start :: non_neg_integer, length :: pos_integer -> [term()])
|
||||
|
||||
@doc """
|
||||
Reduces the enumerable into an element.
|
||||
Reduces the `enumerable` into an element.
|
||||
|
||||
Most of the operations in `Enum` are implemented in terms of reduce.
|
||||
This function should apply the given `t:reducer/0` function to each
|
||||
item in the enumerable and proceed as expected by the returned
|
||||
item in the `enumerable` and proceed as expected by the returned
|
||||
accumulator.
|
||||
|
||||
See the documentation of the types `t:result/0` and `t:acc/0` for
|
||||
@@ -141,10 +141,10 @@ defprotocol Enumerable do
|
||||
def reduce(enumerable, acc, fun)
|
||||
|
||||
@doc """
|
||||
Retrieves the number of elements in the enumerable.
|
||||
Retrieves the number of elements in the `enumerable`.
|
||||
|
||||
It should return `{:ok, count}` if you can count the number of elements
|
||||
in the enumerable.
|
||||
in the `enumerable`.
|
||||
|
||||
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
|
||||
built on top of `reduce/3` that runs in linear time will be used.
|
||||
@@ -153,10 +153,10 @@ defprotocol Enumerable do
|
||||
def count(enumerable)
|
||||
|
||||
@doc """
|
||||
Checks if an element exists within the enumerable.
|
||||
Checks if an `element` exists within the `enumerable`.
|
||||
|
||||
It should return `{:ok, boolean}` if you can check the membership of a
|
||||
given element in the enumerable with `===/2` without traversing the whole
|
||||
given element in the `enumerable` with `===/2` without traversing the whole
|
||||
enumerable.
|
||||
|
||||
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
|
||||
@@ -168,8 +168,8 @@ defprotocol Enumerable do
|
||||
@doc """
|
||||
Returns a function that slices the data structure contiguously.
|
||||
|
||||
It should return `{:ok, size, slicing_fun}` if the enumerable has
|
||||
a known bound and can access a position in the enumerable without
|
||||
It should return `{:ok, size, slicing_fun}` if the `enumerable` has
|
||||
a known bound and can access a position in the `enumerable` without
|
||||
traversing all previous elements.
|
||||
|
||||
Otherwise it should return `{:error, __MODULE__}` and a default
|
||||
@@ -180,7 +180,7 @@ defprotocol Enumerable do
|
||||
|
||||
The `size` value returned by this function is used for boundary checks,
|
||||
therefore it is extremely important that this function only returns `:ok`
|
||||
if retrieving the `size` of the enumerable is cheap, fast and takes constant
|
||||
if retrieving the `size` of the `enumerable` is cheap, fast and takes constant
|
||||
time. Otherwise the simplest of operations, such as `Enum.at(enumerable, 0)`,
|
||||
will become too expensive.
|
||||
|
||||
@@ -249,7 +249,10 @@ defmodule Enum do
|
||||
@type t :: Enumerable.t()
|
||||
@type acc :: any
|
||||
@type element :: any
|
||||
|
||||
@typedoc "Zero-based index. It can also be a negative integer."
|
||||
@type index :: integer
|
||||
|
||||
@type default :: any
|
||||
|
||||
require Stream.Reducers, as: R
|
||||
@@ -273,9 +276,10 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns `true` if the given `fun` evaluates to true on all of the items in the enumerable.
|
||||
Returns `true` if the given `fun` evaluates to a truthy value (neither `false` nor `nil`)
|
||||
on all of the items in the `enumerable`.
|
||||
|
||||
It stops the iteration at the first invocation that returns `false` or `nil`.
|
||||
It stops the iteration at the first invocation that returns either `false` or `nil`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -286,7 +290,7 @@ defmodule Enum do
|
||||
false
|
||||
|
||||
If no function is given, it defaults to checking if
|
||||
all items in the enumerable are truthy values.
|
||||
all items in the `enumerable` are truthy values.
|
||||
|
||||
iex> Enum.all?([1, 2, 3])
|
||||
true
|
||||
@@ -311,7 +315,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns `true` if the given `fun` evaluates to true on any of the items in the enumerable.
|
||||
Returns `true` if the given `fun` evaluates to true on any of the items in the `enumerable`.
|
||||
|
||||
It stops the iteration at the first invocation that returns a truthy value (neither `false` nor `nil`).
|
||||
|
||||
@@ -324,7 +328,7 @@ defmodule Enum do
|
||||
true
|
||||
|
||||
If no function is given, it defaults to checking if at least one item
|
||||
in the enumerable is a truthy value.
|
||||
in the `enumerable` is a truthy value.
|
||||
|
||||
iex> Enum.any?([false, false, false])
|
||||
false
|
||||
@@ -408,7 +412,7 @@ defmodule Enum do
|
||||
|
||||
@doc """
|
||||
Returns list of lists containing `count` items each, where
|
||||
each new chunk starts `step` elements into the enumerable.
|
||||
each new chunk starts `step` elements into the `enumerable`.
|
||||
|
||||
`step` is optional and, if not passed, defaults to `count`, i.e.
|
||||
chunks do not overlap.
|
||||
@@ -521,7 +525,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Given an enumerable of enumerables, concatenates the enumerables into
|
||||
Given an enumerable of enumerables, concatenates the `enumerables` into
|
||||
a single list.
|
||||
|
||||
## Examples
|
||||
@@ -540,8 +544,8 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Concatenates the enumerable on the right with the enumerable on the
|
||||
left.
|
||||
Concatenates the enumerable on the `right` with the enumerable on the
|
||||
`left`.
|
||||
|
||||
This function produces the same result as the `Kernel.++/2` operator
|
||||
for lists.
|
||||
@@ -565,7 +569,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the size of the enumerable.
|
||||
Returns the size of the `enumerable`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -589,7 +593,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the count of items in the enumerable for which `fun` returns
|
||||
Returns the count of items in the `enumerable` for which `fun` returns
|
||||
a truthy value.
|
||||
|
||||
## Examples
|
||||
@@ -651,7 +655,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Drops the `amount` of items from the enumerable.
|
||||
Drops the `amount` of items from the `enumerable`.
|
||||
|
||||
If a negative `amount` is given, the `amount` of last values will be dropped.
|
||||
The `enumerable` will be enumerated once to retrieve the proper index and
|
||||
@@ -695,7 +699,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a list of every `nth` item in the enumerable dropped,
|
||||
Returns a list of every `nth` item in the `enumerable` dropped,
|
||||
starting with the first element.
|
||||
|
||||
The first item is always dropped, unless `nth` is 0.
|
||||
@@ -728,7 +732,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Drops items at the beginning of the enumerable while `fun` returns a
|
||||
Drops items at the beginning of the `enumerable` while `fun` returns a
|
||||
truthy value.
|
||||
|
||||
## Examples
|
||||
@@ -748,13 +752,13 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Invokes the given `fun` for each item in the enumerable.
|
||||
Invokes the given `fun` for each item in the `enumerable`.
|
||||
|
||||
Returns `:ok`.
|
||||
|
||||
## Examples
|
||||
|
||||
Enum.each(["some", "example"], fn(x) -> IO.puts x end)
|
||||
Enum.each(["some", "example"], fn x -> IO.puts(x) end)
|
||||
"some"
|
||||
"example"
|
||||
#=> :ok
|
||||
@@ -776,7 +780,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Determines if the enumerable is empty.
|
||||
Determines if the `enumerable` is empty.
|
||||
|
||||
Returns `true` if `enumerable` is empty, otherwise `false`.
|
||||
|
||||
@@ -842,7 +846,7 @@ defmodule Enum do
|
||||
Finds the element at the given `index` (zero-based).
|
||||
|
||||
Raises `OutOfBoundsError` if the given `index` is outside the range of
|
||||
the enumerable.
|
||||
the `enumerable`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -856,7 +860,7 @@ defmodule Enum do
|
||||
** (Enum.OutOfBoundsError) out of bounds error
|
||||
|
||||
"""
|
||||
@spec fetch!(t, index) :: element | no_return
|
||||
@spec fetch!(t, index) :: element
|
||||
def fetch!(enumerable, index) do
|
||||
case slice_any(enumerable, index, 1) do
|
||||
[value] -> value
|
||||
@@ -865,11 +869,11 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Filters the enumerable, i.e. returns only those elements
|
||||
Filters the `enumerable`, i.e. returns only those elements
|
||||
for which `fun` returns a truthy value.
|
||||
|
||||
See also `reject/2` which discards all elements where the
|
||||
function a truthy value.
|
||||
function returns a truthy value.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -883,10 +887,13 @@ defmodule Enum do
|
||||
discard the invalid one in one pass:
|
||||
|
||||
strings = ["1234", "abc", "12ab"]
|
||||
|
||||
Enum.flat_map(strings, fn string ->
|
||||
case Integer.parse(string) do
|
||||
{int, _rest} -> [int] # transform to integer
|
||||
:error -> [] # skip the value
|
||||
# transform to integer
|
||||
{int, _rest} -> [int]
|
||||
# skip the value
|
||||
:error -> []
|
||||
end
|
||||
end)
|
||||
|
||||
@@ -1039,7 +1046,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Maps and reduces an enumerable, flattening the given results (only one level deep).
|
||||
Maps and reduces an `enumerable`, flattening the given results (only one level deep).
|
||||
|
||||
It expects an accumulator and a function that receives each enumerable
|
||||
item, and must return a tuple containing a new enumerable (often a list)
|
||||
@@ -1084,11 +1091,11 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Splits the enumerable into groups based on `key_fun`.
|
||||
Splits the `enumerable` into groups based on `key_fun`.
|
||||
|
||||
The result is a map where each key is given by `key_fun`
|
||||
and each value is a list of elements given by `value_fun`.
|
||||
The order of elements within each list is preserved from the enumerable.
|
||||
The order of elements within each list is preserved from the `enumerable`.
|
||||
However, like all maps, the resulting map is unordered.
|
||||
|
||||
## Examples
|
||||
@@ -1164,10 +1171,14 @@ defmodule Enum do
|
||||
@doc """
|
||||
Inserts the given `enumerable` into a `collectable`.
|
||||
|
||||
Note that passing a non-empty list as the `collectable` is deprecated. If you're collecting
|
||||
into a non-empty keyword list, consider using `Keyword.merge/2`. If you're collecting into a
|
||||
non-empty list, consider something like `to_list(enumerable) ++ collectable`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Enum.into([1, 2], [0])
|
||||
[0, 1, 2]
|
||||
iex> Enum.into([1, 2], [])
|
||||
[1, 2]
|
||||
|
||||
iex> Enum.into([a: 1, b: 2], %{})
|
||||
%{a: 1, b: 2}
|
||||
@@ -1180,8 +1191,10 @@ defmodule Enum do
|
||||
|
||||
"""
|
||||
@spec into(Enumerable.t(), Collectable.t()) :: Collectable.t()
|
||||
def into(enumerable, collectable) when is_list(collectable) do
|
||||
collectable ++ to_list(enumerable)
|
||||
def into(enumerable, collectable)
|
||||
|
||||
def into(enumerable, []) do
|
||||
to_list(enumerable)
|
||||
end
|
||||
|
||||
def into(%_{} = enumerable, collectable) do
|
||||
@@ -1258,12 +1271,12 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Joins the given enumerable into a binary using `joiner` as a
|
||||
Joins the given `enumerable` into a binary using `joiner` as a
|
||||
separator.
|
||||
|
||||
If `joiner` is not passed at all, it defaults to the empty binary.
|
||||
|
||||
All items in the enumerable must be convertible to a binary,
|
||||
All items in the `enumerable` must be convertible to a binary,
|
||||
otherwise an error is raised.
|
||||
|
||||
## Examples
|
||||
@@ -1359,7 +1372,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Maps and joins the given enumerable in one pass.
|
||||
Maps and joins the given `enumerable` in one pass.
|
||||
|
||||
`joiner` can be either a binary or a list and the result will be of
|
||||
the same type as `joiner`.
|
||||
@@ -1395,7 +1408,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Invokes the given function to each item in the enumerable to reduce
|
||||
Invokes the given function to each item in the `enumerable` to reduce
|
||||
it to a single element, while keeping an accumulator.
|
||||
|
||||
Returns a tuple where the first element is the mapped enumerable and
|
||||
@@ -1429,7 +1442,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the maximal element in the enumerable according
|
||||
Returns the maximal element in the `enumerable` according
|
||||
to Erlang's term ordering.
|
||||
|
||||
If multiple elements are considered maximal, the first one that was found
|
||||
@@ -1465,13 +1478,14 @@ defmodule Enum do
|
||||
For selecting a maximum value out of two consider using `Kernel.max/2`.
|
||||
|
||||
"""
|
||||
@spec max(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any
|
||||
def max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end) do
|
||||
@spec max(t, (() -> empty_result)) :: element | empty_result when empty_result: any
|
||||
def max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
|
||||
when is_function(empty_fallback, 0) do
|
||||
aggregate(enumerable, &Kernel.max/2, empty_fallback)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the maximal element in the enumerable as calculated
|
||||
Returns the maximal element in the `enumerable` as calculated
|
||||
by the given function.
|
||||
|
||||
If multiple elements are considered maximal, the first one that was found
|
||||
@@ -1492,9 +1506,10 @@ defmodule Enum do
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return
|
||||
@spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result
|
||||
when empty_result: any
|
||||
def max_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end) do
|
||||
def max_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end)
|
||||
when is_function(fun, 1) and is_function(empty_fallback, 0) do
|
||||
first_fun = &{&1, fun.(&1)}
|
||||
|
||||
reduce_fun = fn entry, {_, fun_max} = old ->
|
||||
@@ -1509,7 +1524,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if `element` exists within the enumerable.
|
||||
Checks if `element` exists within the `enumerable`.
|
||||
|
||||
Membership is tested with the match (`===/2`) operator.
|
||||
|
||||
@@ -1549,7 +1564,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the minimal element in the enumerable according
|
||||
Returns the minimal element in the `enumerable` according
|
||||
to Erlang's term ordering.
|
||||
|
||||
If multiple elements are considered minimal, the first one that was found
|
||||
@@ -1585,13 +1600,14 @@ defmodule Enum do
|
||||
For selecting a minimal value out of two consider using `Kernel.min/2`.
|
||||
|
||||
"""
|
||||
@spec min(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any
|
||||
def min(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end) do
|
||||
@spec min(t, (() -> empty_result)) :: element | empty_result when empty_result: any
|
||||
def min(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
|
||||
when is_function(empty_fallback, 0) do
|
||||
aggregate(enumerable, &Kernel.min/2, empty_fallback)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the minimal element in the enumerable as calculated
|
||||
Returns the minimal element in the `enumerable` as calculated
|
||||
by the given function.
|
||||
|
||||
If multiple elements are considered minimal, the first one that was found
|
||||
@@ -1612,9 +1628,10 @@ defmodule Enum do
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return
|
||||
@spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result
|
||||
when empty_result: any
|
||||
def min_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end) do
|
||||
def min_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end)
|
||||
when is_function(fun, 1) and is_function(empty_fallback, 0) do
|
||||
first_fun = &{&1, fun.(&1)}
|
||||
|
||||
reduce_fun = fn entry, {_, fun_min} = old ->
|
||||
@@ -1647,15 +1664,15 @@ defmodule Enum do
|
||||
{nil, nil}
|
||||
|
||||
"""
|
||||
@spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result | no_return
|
||||
@spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result
|
||||
when empty_result: any
|
||||
def min_max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
|
||||
|
||||
def min_max(first..last, _empty_fallback) do
|
||||
def min_max(first..last, empty_fallback) when is_function(empty_fallback, 0) do
|
||||
{Kernel.min(first, last), Kernel.max(first, last)}
|
||||
end
|
||||
|
||||
def min_max(enumerable, empty_fallback) do
|
||||
def min_max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
|
||||
first_fun = &{&1, &1}
|
||||
|
||||
reduce_fun = fn entry, {min, max} ->
|
||||
@@ -1690,12 +1707,10 @@ defmodule Enum do
|
||||
{nil, nil}
|
||||
|
||||
"""
|
||||
@spec min_max_by(t, (element -> any), (() -> empty_result)) ::
|
||||
{element, element} | empty_result | no_return
|
||||
@spec min_max_by(t, (element -> any), (() -> empty_result)) :: {element, element} | empty_result
|
||||
when empty_result: any
|
||||
def min_max_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end)
|
||||
|
||||
def min_max_by(enumerable, fun, empty_fallback) do
|
||||
when is_function(fun, 1) and is_function(empty_fallback, 0) do
|
||||
first_fun = fn entry ->
|
||||
fun_entry = fun.(entry)
|
||||
{{entry, entry}, {fun_entry, fun_entry}}
|
||||
@@ -1773,7 +1788,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a random element of an enumerable.
|
||||
Returns a random element of an `enumerable`.
|
||||
|
||||
Raises `Enum.EmptyError` if `enumerable` is empty.
|
||||
|
||||
@@ -1803,7 +1818,7 @@ defmodule Enum do
|
||||
776
|
||||
|
||||
"""
|
||||
@spec random(t) :: element | no_return
|
||||
@spec random(t) :: element
|
||||
def random(enumerable)
|
||||
|
||||
def random(enumerable) when is_list(enumerable) do
|
||||
@@ -1838,11 +1853,11 @@ defmodule Enum do
|
||||
|
||||
Raises `Enum.EmptyError` if `enumerable` is empty.
|
||||
|
||||
The first element of the enumerable is used as the initial value
|
||||
The first element of the `enumerable` is used as the initial value
|
||||
of the accumulator. Then the function is invoked with the next
|
||||
element and the accumulator. The result returned by the function
|
||||
is used as the accumulator for the next iteration, recursively.
|
||||
When the enumerable is done, the last accumulator is returned.
|
||||
When the `enumerable` is done, the last accumulator is returned.
|
||||
|
||||
Since the first element of the enumerable is used as the initial
|
||||
value of the accumulator, `fun` will only be executed `n - 1` times
|
||||
@@ -1907,8 +1922,8 @@ defmodule Enum do
|
||||
|
||||
def my_map(enumerable, fun) do
|
||||
enumerable
|
||||
|> Enum.reduce([], fn(x, acc) -> [fun.(x) | acc] end)
|
||||
|> Enum.reverse
|
||||
|> Enum.reduce([], fn x, acc -> [fun.(x) | acc] end)
|
||||
|> Enum.reverse()
|
||||
end
|
||||
|
||||
In the example above, `Enum.reduce/3` accumulates the result of each call
|
||||
@@ -1946,21 +1961,28 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reduces the enumerable until `fun` returns `{:halt, term}`.
|
||||
Reduces `enumerable` until `fun` returns `{:halt, term}`.
|
||||
|
||||
The return value for `fun` is expected to be
|
||||
|
||||
* `{:cont, acc}` to continue the reduction with `acc` as the new
|
||||
accumulator or
|
||||
* `{:halt, acc}` to halt the reduction and return `acc` as the return
|
||||
value of this function
|
||||
* `{:halt, acc}` to halt the reduction
|
||||
|
||||
If `fun` returns `{:halt, acc}` the reduction is halted and the function
|
||||
returns `acc`. Otherwise, if the enumerable is exhausted, the function returns
|
||||
the accumulator of the last `{:cont, acc}`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Enum.reduce_while(1..100, 0, fn x, acc ->
|
||||
...> if x < 3, do: {:cont, acc + x}, else: {:halt, acc}
|
||||
...> if x < 5, do: {:cont, acc + x}, else: {:halt, acc}
|
||||
...> end)
|
||||
3
|
||||
10
|
||||
iex> Enum.reduce_while(1..100, 0, fn x, acc ->
|
||||
...> if x > 0, do: {:cont, acc + x}, else: {:halt, acc}
|
||||
...> end)
|
||||
5050
|
||||
|
||||
"""
|
||||
@spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any
|
||||
@@ -2032,10 +2054,10 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reverses the enumerable in the range from initial position `start`
|
||||
Reverses the `enumerable` in the range from initial `start_index`
|
||||
through `count` elements.
|
||||
|
||||
If `count` is greater than the size of the rest of the enumerable,
|
||||
If `count` is greater than the size of the rest of the `enumerable`,
|
||||
then this function will reverse the rest of the enumerable.
|
||||
|
||||
## Examples
|
||||
@@ -2045,23 +2067,23 @@ defmodule Enum do
|
||||
|
||||
"""
|
||||
@spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list
|
||||
def reverse_slice(enumerable, start, count)
|
||||
when is_integer(start) and start >= 0 and is_integer(count) and count >= 0 do
|
||||
def reverse_slice(enumerable, start_index, count)
|
||||
when is_integer(start_index) and start_index >= 0 and is_integer(count) and count >= 0 do
|
||||
list = reverse(enumerable)
|
||||
length = length(list)
|
||||
count = Kernel.min(count, length - start)
|
||||
count = Kernel.min(count, length - start_index)
|
||||
|
||||
if count > 0 do
|
||||
reverse_slice(list, length, start + count, count, [])
|
||||
reverse_slice(list, length, start_index + count, count, [])
|
||||
else
|
||||
:lists.reverse(list)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Applies the given function to each element in the enumerable,
|
||||
Applies the given function to each element in the `enumerable`,
|
||||
storing the result in a list and passing it as the accumulator
|
||||
for the next computation. Uses the first element in the enumerable
|
||||
for the next computation. Uses the first element in the `enumerable`
|
||||
as the starting value.
|
||||
|
||||
## Examples
|
||||
@@ -2077,7 +2099,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Applies the given function to each element in the enumerable,
|
||||
Applies the given function to each element in the `enumerable`,
|
||||
storing the result in a list and passing it as the accumulator
|
||||
for the next computation. Uses the given `acc` as the starting value.
|
||||
|
||||
@@ -2121,17 +2143,21 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a subset list of the given enumerable, from `range.first` to `range.last` positions.
|
||||
Returns a subset list of the given `enumerable` by `index_range`.
|
||||
|
||||
Given `enumerable`, it drops elements until element position `range.first`,
|
||||
then takes elements until element position `range.last` (inclusive).
|
||||
`index_range` must be a `Range`. Given an `enumerable`, it drops
|
||||
elements before `index_range.first` (zero-base), then takes elements
|
||||
until element `index_range.last` (inclusively).
|
||||
|
||||
Positions are normalized, meaning that negative positions will be counted from the end
|
||||
(e.g. `-1` means the last element of the enumerable).
|
||||
If `range.last` is out of bounds, then it is assigned as the position of the last element.
|
||||
Indexes are normalized, meaning that negative indexes will be counted
|
||||
from the end (e.g. `-1` means the last element of the `enumerable`).
|
||||
|
||||
If the normalized `range.first` position is out of bounds of the given enumerable,
|
||||
or this one is greater than the normalized `range.last` position, then `[]` is returned.
|
||||
If `index_range.last` is out of bounds, then it is assigned as the index
|
||||
of the last element.
|
||||
|
||||
If the normalized `index_range.first` is out of bounds of the given
|
||||
`enumerable`, or this one is greater than the normalized `index_range.last`,
|
||||
then `[]` is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -2141,11 +2167,11 @@ defmodule Enum do
|
||||
iex> Enum.slice(1..10, 5..20)
|
||||
[6, 7, 8, 9, 10]
|
||||
|
||||
# last five elements (negative positions)
|
||||
# last five elements (negative indexes)
|
||||
iex> Enum.slice(1..30, -5..-1)
|
||||
[26, 27, 28, 29, 30]
|
||||
|
||||
# last five elements (mixed positive and negative positions)
|
||||
# last five elements (mixed positive and negative indexes)
|
||||
iex> Enum.slice(1..30, 25..-1)
|
||||
[26, 27, 28, 29, 30]
|
||||
|
||||
@@ -2153,13 +2179,15 @@ defmodule Enum do
|
||||
iex> Enum.slice(1..10, 11..20)
|
||||
[]
|
||||
|
||||
# range.first is greater than range.last
|
||||
# index_range.first is greater than index_range.last
|
||||
iex> Enum.slice(1..10, 6..5)
|
||||
[]
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec slice(t, Range.t()) :: list
|
||||
def slice(enumerable, index_range)
|
||||
|
||||
def slice(enumerable, first..last) do
|
||||
{count, fun} = slice_count_and_fun(enumerable)
|
||||
corr_first = if first >= 0, do: first, else: first + count
|
||||
@@ -2174,15 +2202,14 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a subset list of the given enumerable, from `start` position with `amount` of elements if available.
|
||||
Returns a subset list of the given `enumerable`, from `start_index` (zero-based)
|
||||
with `amount` number of elements if available.
|
||||
|
||||
Given `enumerable`, it drops elements until element position `start`,
|
||||
then takes `amount` of elements until the end of the enumerable.
|
||||
Given an `enumerable`, it drops elements right before element `start_index`,
|
||||
then takes `amount` of elements, returning as many elements as possible if there are not enough
|
||||
elements.
|
||||
|
||||
If `start` is out of bounds, it returns `[]`.
|
||||
|
||||
If `amount` is greater than `enumerable` length, it returns as many elements as possible.
|
||||
If `amount` is zero, then `[]` is returned.
|
||||
It returns `[]` if `amount` is `0` or if `start_index` is out of bounds.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -2196,25 +2223,25 @@ defmodule Enum do
|
||||
iex> Enum.slice(1..10, 5, 0)
|
||||
[]
|
||||
|
||||
# out of bound start position
|
||||
# out of bound start index
|
||||
iex> Enum.slice(1..10, 10, 5)
|
||||
[]
|
||||
|
||||
# out of bound start position (negative)
|
||||
# out of bound start index (negative)
|
||||
iex> Enum.slice(1..10, -11, 5)
|
||||
[]
|
||||
|
||||
"""
|
||||
@spec slice(t, index, non_neg_integer) :: list
|
||||
def slice(_enumerable, start, 0) when is_integer(start), do: []
|
||||
def slice(_enumerable, start_index, 0) when is_integer(start_index), do: []
|
||||
|
||||
def slice(enumerable, start, amount)
|
||||
when is_integer(start) and is_integer(amount) and amount >= 0 do
|
||||
slice_any(enumerable, start, amount)
|
||||
def slice(enumerable, start_index, amount)
|
||||
when is_integer(start_index) and is_integer(amount) and amount >= 0 do
|
||||
slice_any(enumerable, start_index, amount)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sorts the enumerable according to Erlang's term ordering.
|
||||
Sorts the `enumerable` according to Erlang's term ordering.
|
||||
|
||||
Uses the merge sort algorithm.
|
||||
|
||||
@@ -2234,7 +2261,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sorts the enumerable by the given function.
|
||||
Sorts the `enumerable` by the given function.
|
||||
|
||||
This function uses the merge sort algorithm. The given function should compare
|
||||
two arguments, and return `true` if the first argument precedes the second one.
|
||||
@@ -2269,10 +2296,10 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sorts the mapped results of the enumerable according to the provided `sorter`
|
||||
Sorts the mapped results of the `enumerable` according to the provided `sorter`
|
||||
function.
|
||||
|
||||
This function maps each element of the enumerable using the provided `mapper`
|
||||
This function maps each element of the `enumerable` using the provided `mapper`
|
||||
function. The enumerable is then sorted by the mapped elements
|
||||
using the `sorter` function, which defaults to `Kernel.<=/2`.
|
||||
|
||||
@@ -2317,7 +2344,7 @@ defmodule Enum do
|
||||
elements in the first one.
|
||||
|
||||
If `count` is a negative number, it starts counting from the
|
||||
back to the beginning of the enumerable.
|
||||
back to the beginning of the `enumerable`.
|
||||
|
||||
Be aware that a negative `count` implies the `enumerable`
|
||||
will be enumerated twice: once to calculate the position, and
|
||||
@@ -2365,13 +2392,22 @@ defmodule Enum do
|
||||
|
||||
@doc """
|
||||
Splits enumerable in two at the position of the element for which
|
||||
`fun` returns `false` for the first time.
|
||||
`fun` returns a falsy value (`false` or `nil`) for the first time.
|
||||
|
||||
It returns a two-element tuple with two lists of elements.
|
||||
The element that triggered the split is part of the second list.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 3 end)
|
||||
{[1, 2], [3, 4]}
|
||||
|
||||
iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 0 end)
|
||||
{[], [1, 2, 3, 4]}
|
||||
|
||||
iex> Enum.split_while([1, 2, 3, 4], fn x -> x > 0 end)
|
||||
{[1, 2, 3, 4], []}
|
||||
|
||||
"""
|
||||
@spec split_while(t, (element -> as_boolean(term))) :: {list, list}
|
||||
def split_while(enumerable, fun) when is_list(enumerable) do
|
||||
@@ -2414,7 +2450,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Takes the first `amount` items from the enumerable.
|
||||
Takes the first `amount` items from the `enumerable`.
|
||||
|
||||
If a negative `amount` is given, the `amount` of last values will be taken.
|
||||
The `enumerable` will be enumerated once to retrieve the proper index and
|
||||
@@ -2464,7 +2500,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a list of every `nth` item in the enumerable,
|
||||
Returns a list of every `nth` item in the `enumerable`,
|
||||
starting with the first element.
|
||||
|
||||
The first item is always included, unless `nth` is 0.
|
||||
@@ -2570,7 +2606,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Takes the items from the beginning of the enumerable while `fun` returns
|
||||
Takes the items from the beginning of the `enumerable` while `fun` returns
|
||||
a truthy value.
|
||||
|
||||
## Examples
|
||||
@@ -2664,10 +2700,10 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Opposite of `Enum.zip/2`; extracts a two-element tuples from the
|
||||
enumerable and groups them together.
|
||||
Opposite of `zip/2`. Extracts two-element tuples from the
|
||||
given `enumerable` and groups them together.
|
||||
|
||||
It takes an enumerable with items being two-element tuples and returns
|
||||
It takes an `enumerable` with items being two-element tuples and returns
|
||||
a tuple with two lists, each of which is formed by the first and
|
||||
second element of each tuple, respectively.
|
||||
|
||||
@@ -2694,7 +2730,7 @@ defmodule Enum do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the enumerable with each element wrapped in a tuple
|
||||
Returns the `enumerable` with each element wrapped in a tuple
|
||||
alongside its index.
|
||||
|
||||
If an `offset` is given, we will index from the given offset instead of from zero.
|
||||
|
||||
@@ -150,7 +150,7 @@ defmodule Exception do
|
||||
Attaches information to exceptions for extra debugging.
|
||||
|
||||
This operation is potentially expensive, as it reads data
|
||||
from the filesystem, parses beam files, evaluates code and
|
||||
from the file system, parses beam files, evaluates code and
|
||||
so on.
|
||||
|
||||
If the exception module implements the optional `c:blame/2`
|
||||
@@ -186,8 +186,6 @@ defmodule Exception do
|
||||
|
||||
This function returns either `{:ok, definition, clauses}` or `:error`.
|
||||
Where `definition` is `:def`, `:defp`, `:defmacro` or `:defmacrop`.
|
||||
Note this functionality requires Erlang/OTP 20, otherwise `:error`
|
||||
is always returned.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec blame_mfa(module, function, args :: [term]) ::
|
||||
@@ -790,6 +788,10 @@ defmodule BadFunctionError do
|
||||
defexception [:term]
|
||||
|
||||
@impl true
|
||||
def message(%{term: term}) when is_function(term) do
|
||||
"function #{inspect(term)} is invalid, likely because it points to an old version of the code"
|
||||
end
|
||||
|
||||
def message(exception) do
|
||||
"expected a function, got: #{inspect(exception.term)}"
|
||||
end
|
||||
@@ -854,7 +856,7 @@ defmodule CondClauseError do
|
||||
|
||||
@impl true
|
||||
def message(_exception) do
|
||||
"no cond clause evaluated to a true value"
|
||||
"no cond clause evaluated to a truthy value"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -944,7 +946,8 @@ defmodule UndefinedFunctionError do
|
||||
end
|
||||
|
||||
defp hint(module, function, arity, true) do
|
||||
hint_for_loaded_module(module, function, arity, nil)
|
||||
behaviour_hint(module, function, arity) <>
|
||||
hint_for_loaded_module(module, function, arity, nil)
|
||||
end
|
||||
|
||||
defp hint(_module, _function, _arity, _loaded?) do
|
||||
@@ -970,9 +973,10 @@ defmodule UndefinedFunctionError do
|
||||
result =
|
||||
case Keyword.take(exports, [function]) do
|
||||
[] ->
|
||||
candidates = exports -- deprecated_functions_for(module)
|
||||
base = Atom.to_string(function)
|
||||
|
||||
for {key, val} <- exports,
|
||||
for {key, val} <- candidates,
|
||||
dist = String.jaro_distance(base, Atom.to_string(key)),
|
||||
dist >= @function_threshold,
|
||||
do: {dist, key, val}
|
||||
@@ -994,6 +998,33 @@ defmodule UndefinedFunctionError do
|
||||
[" * ", Code.Identifier.inspect_as_function(fun), ?/, Integer.to_string(arity), ?\n]
|
||||
end
|
||||
|
||||
defp behaviour_hint(module, function, arity) do
|
||||
case behaviours_for(module) do
|
||||
[] ->
|
||||
""
|
||||
|
||||
behaviours ->
|
||||
case Enum.find(behaviours, &expects_callback?(&1, function, arity)) do
|
||||
nil -> ""
|
||||
behaviour -> ", but the behaviour #{inspect(behaviour)} expects it to be present"
|
||||
end
|
||||
end
|
||||
rescue
|
||||
# In case the module was removed while we are computing this
|
||||
UndefinedFunctionError -> ""
|
||||
end
|
||||
|
||||
defp behaviours_for(module) do
|
||||
:attributes
|
||||
|> module.module_info()
|
||||
|> Keyword.get(:behaviour, [])
|
||||
end
|
||||
|
||||
defp expects_callback?(behaviour, function, arity) do
|
||||
callbacks = behaviour.behaviour_info(:callbacks)
|
||||
Enum.member?(callbacks, {function, arity})
|
||||
end
|
||||
|
||||
defp exports_for(module) do
|
||||
if function_exported?(module, :__info__, 1) do
|
||||
module.__info__(:macros) ++ module.__info__(:functions)
|
||||
@@ -1005,6 +1036,18 @@ defmodule UndefinedFunctionError do
|
||||
UndefinedFunctionError ->
|
||||
[]
|
||||
end
|
||||
|
||||
defp deprecated_functions_for(module) do
|
||||
if function_exported?(module, :__info__, 1) do
|
||||
for {name_arity, _message} <- module.__info__(:deprecated), do: name_arity
|
||||
else
|
||||
[]
|
||||
end
|
||||
rescue
|
||||
# In case the module was removed while we are computing this
|
||||
UndefinedFunctionError ->
|
||||
[]
|
||||
end
|
||||
end
|
||||
|
||||
defmodule FunctionClauseError do
|
||||
@@ -1133,7 +1176,7 @@ defmodule KeyError do
|
||||
def message(exception = %{message: nil}), do: message(exception.key, exception.term)
|
||||
def message(%{message: message}), do: message
|
||||
|
||||
def message(key, term) do
|
||||
defp message(key, term) do
|
||||
message = "key #{inspect(key)} not found"
|
||||
|
||||
if term != nil do
|
||||
@@ -1163,7 +1206,7 @@ defmodule KeyError do
|
||||
end
|
||||
|
||||
defp map_with_atom_keys_only?(term) do
|
||||
is_map(term) and Enum.all?(term, fn {k, _} -> is_atom(k) end)
|
||||
is_map(term) and Enum.all?(Map.to_list(term), fn {k, _} -> is_atom(k) end)
|
||||
end
|
||||
|
||||
defp available_keys(term) when is_map(term), do: Map.keys(term)
|
||||
|
||||
+169
-101
@@ -114,20 +114,35 @@ defmodule File do
|
||||
| {:read_ahead, pos_integer | false}
|
||||
| {:delayed_write, non_neg_integer, non_neg_integer}
|
||||
|
||||
@type erlang_time ::
|
||||
{{year :: non_neg_integer(), month :: 1..12, day :: 1..31},
|
||||
{hour :: 0..23, minute :: 0..59, second :: 0..59}}
|
||||
|
||||
@type posix_time :: integer()
|
||||
|
||||
@doc """
|
||||
Returns `true` if the path is a regular file.
|
||||
|
||||
This function follows symbolic links, so if a symbolic link points to a
|
||||
regular file, `true` is returned.
|
||||
|
||||
## Options
|
||||
|
||||
The supported options are:
|
||||
|
||||
* `:raw` - a single atom to bypass the file server and only check
|
||||
for the file locally
|
||||
|
||||
## Examples
|
||||
|
||||
File.regular? __ENV__.file #=> true
|
||||
File.regular?(__ENV__.file)
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@spec regular?(Path.t()) :: boolean
|
||||
def regular?(path) do
|
||||
:elixir_utils.read_file_type(IO.chardata_to_string(path)) == {:ok, :regular}
|
||||
@spec regular?(Path.t(), [regular_option]) :: boolean
|
||||
when regular_option: :raw
|
||||
def regular?(path, opts \\ []) do
|
||||
:elixir_utils.read_file_type(IO.chardata_to_string(path), opts) == {:ok, :regular}
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -136,6 +151,13 @@ defmodule File do
|
||||
This function follows symbolic links, so if a symbolic link points to a
|
||||
directory, `true` is returned.
|
||||
|
||||
## Options
|
||||
|
||||
The supported options are:
|
||||
|
||||
* `:raw` - a single atom to bypass the file server and only check
|
||||
for the file locally
|
||||
|
||||
## Examples
|
||||
|
||||
File.dir?("./test")
|
||||
@@ -150,21 +172,29 @@ defmodule File do
|
||||
File.dir?("~/Downloads")
|
||||
#=> false
|
||||
|
||||
"~/Downloads" |> Path.expand |> File.dir?
|
||||
"~/Downloads" |> Path.expand() |> File.dir?()
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@spec dir?(Path.t()) :: boolean
|
||||
def dir?(path) do
|
||||
:elixir_utils.read_file_type(IO.chardata_to_string(path)) == {:ok, :directory}
|
||||
@spec dir?(Path.t(), [dir_option]) :: boolean
|
||||
when dir_option: :raw
|
||||
def dir?(path, opts \\ []) do
|
||||
:elixir_utils.read_file_type(IO.chardata_to_string(path), opts) == {:ok, :directory}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns `true` if the given path exists.
|
||||
|
||||
It can be regular file, directory, socket, symbolic link, named pipe or device file.
|
||||
It can be a regular file, directory, socket, symbolic link, named pipe, or device file.
|
||||
Returns `false` for symbolic links pointing to non-existing targets.
|
||||
|
||||
## Options
|
||||
|
||||
The supported options are:
|
||||
|
||||
* `:raw` - a single atom to bypass the file server and only check
|
||||
for the file locally
|
||||
|
||||
## Examples
|
||||
|
||||
File.exists?("test/")
|
||||
@@ -177,9 +207,11 @@ defmodule File do
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@spec exists?(Path.t()) :: boolean
|
||||
def exists?(path) do
|
||||
match?({:ok, _}, :file.read_file_info(IO.chardata_to_string(path)))
|
||||
@spec exists?(Path.t(), [exists_option]) :: boolean
|
||||
when exists_option: :raw
|
||||
def exists?(path, opts \\ []) do
|
||||
opts = [{:time, :posix}] ++ opts
|
||||
match?({:ok, _}, :file.read_file_info(IO.chardata_to_string(path), opts))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -205,9 +237,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `mkdir/1`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `mkdir/1`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec mkdir!(Path.t()) :: :ok | no_return
|
||||
@spec mkdir!(Path.t()) :: :ok
|
||||
def mkdir!(path) do
|
||||
case mkdir(path) do
|
||||
:ok ->
|
||||
@@ -268,9 +301,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `mkdir_p/1`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `mkdir_p/1`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec mkdir_p!(Path.t()) :: :ok | no_return
|
||||
@spec mkdir_p!(Path.t()) :: :ok
|
||||
def mkdir_p!(path) do
|
||||
case mkdir_p(path) do
|
||||
:ok ->
|
||||
@@ -306,10 +340,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a binary with the contents of the given filename or raises
|
||||
`File.Error` if an error occurs.
|
||||
Returns a binary with the contents of the given filename,
|
||||
or raises a `File.Error` exception if an error occurs.
|
||||
"""
|
||||
@spec read!(Path.t()) :: binary | no_return
|
||||
@spec read!(Path.t()) :: binary
|
||||
def read!(path) do
|
||||
case read(path) do
|
||||
{:ok, binary} ->
|
||||
@@ -354,10 +388,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `stat/2` but returns the `File.Stat` directly, or
|
||||
throws `File.Error` if an error is returned.
|
||||
Same as `stat/2` but returns the `File.Stat` directly,
|
||||
or raises a `File.Error` exception if an error is returned.
|
||||
"""
|
||||
@spec stat!(Path.t(), stat_options) :: File.Stat.t() | no_return
|
||||
@spec stat!(Path.t(), stat_options) :: File.Stat.t()
|
||||
def stat!(path, opts \\ []) do
|
||||
case stat(path, opts) do
|
||||
{:ok, info} ->
|
||||
@@ -405,10 +439,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `lstat/2` but returns the `File.Stat` struct directly, or
|
||||
throws `File.Error` if an error is returned.
|
||||
Same as `lstat/2` but returns the `File.Stat` struct directly,
|
||||
or raises a `File.Error` exception if an error is returned.
|
||||
"""
|
||||
@spec lstat!(Path.t(), stat_options) :: File.Stat.t() | no_return
|
||||
@spec lstat!(Path.t(), stat_options) :: File.Stat.t()
|
||||
def lstat!(path, opts \\ []) do
|
||||
case lstat(path, opts) do
|
||||
{:ok, info} ->
|
||||
@@ -447,11 +481,11 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `read_link/1` but returns the target directly or throws `File.Error` if an error is
|
||||
returned.
|
||||
Same as `read_link/1` but returns the target directly,
|
||||
or raises a `File.Error` exception if an error is returned.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec read_link!(Path.t()) :: binary | no_return
|
||||
@spec read_link!(Path.t()) :: binary
|
||||
def read_link!(path) do
|
||||
case read_link(path) do
|
||||
{:ok, resolved} ->
|
||||
@@ -463,7 +497,7 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Writes the given `File.Stat` back to the filesystem at the given
|
||||
Writes the given `File.Stat` back to the file system at the given
|
||||
path. Returns `:ok` or `{:error, reason}`.
|
||||
"""
|
||||
@spec write_stat(Path.t(), File.Stat.t(), stat_options) :: :ok | {:error, posix}
|
||||
@@ -473,10 +507,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `write_stat/3` but raises an exception if it fails.
|
||||
Same as `write_stat/3` but raises a `File.Error` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
"""
|
||||
@spec write_stat!(Path.t(), File.Stat.t(), stat_options) :: :ok | no_return
|
||||
@spec write_stat!(Path.t(), File.Stat.t(), stat_options) :: :ok
|
||||
def write_stat!(path, stat, opts \\ []) do
|
||||
case write_stat(path, stat, opts) do
|
||||
:ok ->
|
||||
@@ -494,32 +528,60 @@ defmodule File do
|
||||
Updates modification time (mtime) and access time (atime) of
|
||||
the given file.
|
||||
|
||||
The file is created if it doesn’t exist. Requires datetime in UTC.
|
||||
The file is created if it doesn't exist. Requires datetime in UTC
|
||||
(as returned by `:erlang.universaltime()`) or an integer
|
||||
representing the POSIX timestamp (as returned by `System.os_time(:second)`).
|
||||
|
||||
## Examples
|
||||
|
||||
File.touch("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
|
||||
#=> :ok
|
||||
File.touch("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
|
||||
{:error, :enoent}
|
||||
|
||||
File.touch("/tmp/a.txt", 1544519753)
|
||||
#=> :ok
|
||||
|
||||
"""
|
||||
@spec touch(Path.t(), :calendar.datetime()) :: :ok | {:error, posix}
|
||||
def touch(path, time \\ :calendar.universal_time()) do
|
||||
@spec touch(Path.t(), erlang_time() | posix_time()) :: :ok | {:error, posix}
|
||||
def touch(path, time \\ System.os_time(:second))
|
||||
|
||||
def touch(path, time) when is_tuple(time) do
|
||||
path = IO.chardata_to_string(path)
|
||||
|
||||
case :elixir_utils.change_universal_time(path, time) do
|
||||
{:error, :enoent} -> touch_new(path, time)
|
||||
other -> other
|
||||
end
|
||||
with {:error, :enoent} <- :elixir_utils.change_universal_time(path, time),
|
||||
:ok <- write(path, "", [:append]),
|
||||
do: :elixir_utils.change_universal_time(path, time)
|
||||
end
|
||||
|
||||
defp touch_new(path, time) do
|
||||
case write(path, "", [:append]) do
|
||||
:ok -> :elixir_utils.change_universal_time(path, time)
|
||||
{:error, _reason} = error -> error
|
||||
end
|
||||
def touch(path, time) when is_integer(time) do
|
||||
path = IO.chardata_to_string(path)
|
||||
|
||||
with {:error, :enoent} <- :elixir_utils.change_posix_time(path, time),
|
||||
:ok <- write(path, "", [:append]),
|
||||
do: :elixir_utils.change_posix_time(path, time)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `touch/2` but raises an exception if it fails.
|
||||
Same as `touch/2` but raises a `File.Error` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
|
||||
The file is created if it doesn't exist. Requires datetime in UTC
|
||||
(as returned by `:erlang.universaltime()`) or an integer
|
||||
representing the POSIX timestamp (as returned by `System.os_time(:second)`).
|
||||
|
||||
## Examples
|
||||
|
||||
File.touch!("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
|
||||
#=> :ok
|
||||
File.touch!("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
|
||||
#=> ** (File.Error) could not touch "/fakedir/b.txt": no such file or directory
|
||||
|
||||
File.touch!("/tmp/a.txt", 1544519753)
|
||||
|
||||
Returns `:ok` otherwise. Requires datetime in UTC.
|
||||
"""
|
||||
@spec touch!(Path.t(), :calendar.datetime()) :: :ok | no_return
|
||||
def touch!(path, time \\ :calendar.universal_time()) do
|
||||
@spec touch!(Path.t(), erlang_time() | posix_time()) :: :ok
|
||||
def touch!(path, time \\ System.os_time(:second)) do
|
||||
case touch(path, time) do
|
||||
:ok ->
|
||||
:ok
|
||||
@@ -543,12 +605,11 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `ln/2` but raises an exception if it fails.
|
||||
|
||||
Returns `:ok` otherwise
|
||||
Same as `ln/2` but raises a `File.LinkError` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec ln!(Path.t(), Path.t()) :: :ok | no_return
|
||||
@spec ln!(Path.t(), Path.t()) :: :ok
|
||||
def ln!(existing, new) do
|
||||
case ln(existing, new) do
|
||||
:ok ->
|
||||
@@ -577,11 +638,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `ln_s/2` but raises an exception if it fails.
|
||||
|
||||
Returns `:ok` otherwise
|
||||
Same as `ln_s/2` but raises a `File.LinkError` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
"""
|
||||
@spec ln_s!(Path.t(), Path.t()) :: :ok | no_return
|
||||
@spec ln_s!(Path.t(), Path.t()) :: :ok
|
||||
def ln_s!(existing, new) do
|
||||
case ln_s(existing, new) do
|
||||
:ok ->
|
||||
@@ -625,11 +685,11 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
The same as `copy/3` but raises an `File.CopyError` if it fails.
|
||||
The same as `copy/3` but raises a `File.CopyError` exception if it fails.
|
||||
Returns the `bytes_copied` otherwise.
|
||||
"""
|
||||
@spec copy!(Path.t() | io_device, Path.t() | io_device, pos_integer | :infinity) ::
|
||||
non_neg_integer | no_return
|
||||
non_neg_integer
|
||||
def copy!(source, destination, bytes_count \\ :infinity) do
|
||||
case copy(source, destination, bytes_count) do
|
||||
{:ok, bytes_count} ->
|
||||
@@ -659,10 +719,10 @@ defmodule File do
|
||||
## Examples
|
||||
|
||||
# Rename file "a.txt" to "b.txt"
|
||||
File.rename "a.txt", "b.txt"
|
||||
File.rename("a.txt", "b.txt")
|
||||
|
||||
# Rename directory "samples" to "tmp"
|
||||
File.rename "samples", "tmp"
|
||||
File.rename("samples", "tmp")
|
||||
|
||||
"""
|
||||
@spec rename(Path.t(), Path.t()) :: :ok | {:error, posix}
|
||||
@@ -707,10 +767,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
The same as `cp/3`, but raises `File.CopyError` if it fails.
|
||||
The same as `cp/3`, but raises a `File.CopyError` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
"""
|
||||
@spec cp!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok | no_return
|
||||
@spec cp!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok
|
||||
def cp!(source, destination, callback \\ fn _, _ -> true end) do
|
||||
case cp(source, destination, callback) do
|
||||
:ok ->
|
||||
@@ -756,15 +816,15 @@ defmodule File do
|
||||
## Examples
|
||||
|
||||
# Copies file "a.txt" to "b.txt"
|
||||
File.cp_r "a.txt", "b.txt"
|
||||
File.cp_r("a.txt", "b.txt")
|
||||
|
||||
# Copies all files in "samples" to "tmp"
|
||||
File.cp_r "samples", "tmp"
|
||||
File.cp_r("samples", "tmp")
|
||||
|
||||
# Same as before, but asks the user how to proceed in case of conflicts
|
||||
File.cp_r "samples", "tmp", fn source, destination ->
|
||||
File.cp_r("samples", "tmp", fn source, destination ->
|
||||
IO.gets("Overwriting #{destination} by #{source}. Type y to confirm. ") == "y\n"
|
||||
end
|
||||
end)
|
||||
|
||||
"""
|
||||
@spec cp_r(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) ::
|
||||
@@ -787,10 +847,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
The same as `cp_r/3`, but raises `File.CopyError` if it fails.
|
||||
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(), (Path.t(), Path.t() -> boolean)) :: [binary] | no_return
|
||||
@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} ->
|
||||
@@ -939,9 +999,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `write/3` but raises an exception if it fails, returns `:ok` otherwise.
|
||||
Same as `write/3` but raises a `File.Error` exception if it fails.
|
||||
Returns `:ok` otherwise.
|
||||
"""
|
||||
@spec write!(Path.t(), iodata, [mode]) :: :ok | no_return
|
||||
@spec write!(Path.t(), iodata, [mode]) :: :ok
|
||||
def write!(path, content, modes \\ []) do
|
||||
modes = normalize_modes(modes, false)
|
||||
|
||||
@@ -1018,9 +1079,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `rm/1`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `rm/1`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec rm!(Path.t()) :: :ok | no_return
|
||||
@spec rm!(Path.t()) :: :ok
|
||||
def rm!(path) do
|
||||
case rm(path) do
|
||||
:ok ->
|
||||
@@ -1055,7 +1117,8 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `rmdir/1`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `rmdir/1`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec rmdir!(Path.t()) :: :ok | {:error, posix}
|
||||
def rmdir!(path) do
|
||||
@@ -1082,10 +1145,10 @@ defmodule File do
|
||||
|
||||
## Examples
|
||||
|
||||
File.rm_rf "samples"
|
||||
File.rm_rf("samples")
|
||||
#=> {:ok, ["samples", "samples/1.txt"]}
|
||||
|
||||
File.rm_rf "unknown"
|
||||
File.rm_rf("unknown")
|
||||
#=> {:ok, []}
|
||||
|
||||
"""
|
||||
@@ -1145,7 +1208,7 @@ defmodule File do
|
||||
|
||||
# On Windows, symlinks are treated as directory and must be removed
|
||||
# with rmdir/1. But on Unix, we remove them via rm/1. So we first try
|
||||
# to remove it as a directory and, if we get :enotdir, we fallback to
|
||||
# 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
|
||||
@@ -1176,10 +1239,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `rm_rf/1` but raises `File.Error` in case of failures,
|
||||
Same as `rm_rf/1` but raises a `File.Error` exception in case of failures,
|
||||
otherwise the list of files or directories removed.
|
||||
"""
|
||||
@spec rm_rf!(Path.t()) :: [binary] | no_return
|
||||
@spec rm_rf!(Path.t()) :: [binary]
|
||||
def rm_rf!(path) do
|
||||
case rm_rf(path) do
|
||||
{:ok, files} ->
|
||||
@@ -1301,7 +1364,7 @@ defmodule File do
|
||||
|
||||
## Examples
|
||||
|
||||
File.open("file.txt", [:read, :write], fn(file) ->
|
||||
File.open("file.txt", [:read, :write], fn file ->
|
||||
IO.read(file, :line)
|
||||
end)
|
||||
|
||||
@@ -1324,14 +1387,13 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Similar to `open/2` but raises an error if file could not be opened.
|
||||
|
||||
Returns the IO device otherwise.
|
||||
Similar to `open/2` but raises a `File.Error` exception if the file
|
||||
could not be opened. Returns the IO device otherwise.
|
||||
|
||||
See `open/2` for the list of available modes.
|
||||
"""
|
||||
@spec open!(Path.t(), [mode | :ram]) :: io_device | no_return
|
||||
@spec open!(Path.t(), (io_device -> res)) :: res | no_return when res: var
|
||||
@spec open!(Path.t(), [mode | :ram]) :: io_device
|
||||
@spec open!(Path.t(), (io_device -> res)) :: res when res: var
|
||||
def open!(path, modes_or_function \\ []) do
|
||||
case open(path, modes_or_function) do
|
||||
{:ok, io_device_or_function_result} ->
|
||||
@@ -1343,13 +1405,14 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Similar to `open/3` but raises an error if file could not be opened.
|
||||
Similar to `open/3` but raises a `File.Error` exception if the file
|
||||
could not be opened.
|
||||
|
||||
If it succeeds opening the file, it returns the `function` result on the IO device.
|
||||
|
||||
See `open/2` for the list of available `modes`.
|
||||
"""
|
||||
@spec open!(Path.t(), [mode | :ram], (io_device -> res)) :: res | no_return when res: var
|
||||
@spec open!(Path.t(), [mode | :ram], (io_device -> res)) :: res when res: var
|
||||
def open!(path, modes, function) do
|
||||
case open(path, modes, function) do
|
||||
{:ok, function_result} ->
|
||||
@@ -1386,9 +1449,9 @@ defmodule File do
|
||||
defp fix_drive_letter(original), do: original
|
||||
|
||||
@doc """
|
||||
The same as `cwd/0`, but raises an exception if it fails.
|
||||
The same as `cwd/0`, but raises a `File.Error` exception if it fails.
|
||||
"""
|
||||
@spec cwd!() :: binary | no_return
|
||||
@spec cwd!() :: binary
|
||||
def cwd!() do
|
||||
case cwd() do
|
||||
{:ok, cwd} ->
|
||||
@@ -1410,9 +1473,9 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
The same as `cd/1`, but raises an exception if it fails.
|
||||
The same as `cd/1`, but raises a `File.Error` exception if it fails.
|
||||
"""
|
||||
@spec cd!(Path.t()) :: :ok | no_return
|
||||
@spec cd!(Path.t()) :: :ok
|
||||
def cd!(path) do
|
||||
case cd(path) do
|
||||
:ok ->
|
||||
@@ -1461,10 +1524,9 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
The same as `ls/1` but raises `File.Error`
|
||||
in case of an error.
|
||||
The same as `ls/1` but raises a `File.Error` exception in case of an error.
|
||||
"""
|
||||
@spec ls!(Path.t()) :: [binary] | no_return
|
||||
@spec ls!(Path.t()) :: [binary]
|
||||
def ls!(path \\ ".") do
|
||||
case ls(path) do
|
||||
{:ok, value} ->
|
||||
@@ -1512,7 +1574,8 @@ 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 `[:utf8]` in the modes parameter,
|
||||
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` .
|
||||
|
||||
@@ -1524,6 +1587,9 @@ defmodule File do
|
||||
If you pass `:trim_bom` in the modes parameter, the stream will
|
||||
trim UTF-8, UTF-16 and UTF-32 byte order marks when reading from file.
|
||||
|
||||
Note that this function does not try to discover the file encoding basing
|
||||
on BOM.
|
||||
|
||||
## Examples
|
||||
|
||||
# Read in 2048 byte chunks rather than lines
|
||||
@@ -1532,7 +1598,6 @@ defmodule File do
|
||||
#=> path: "./test/test.data", raw: true}
|
||||
|
||||
See `Stream.run/1` for an example of streaming into a file.
|
||||
|
||||
"""
|
||||
@spec stream!(Path.t(), stream_mode, :line | pos_integer) :: File.Stream.t()
|
||||
def stream!(path, modes \\ [], line_or_bytes \\ :line) do
|
||||
@@ -1547,7 +1612,7 @@ defmodule File do
|
||||
|
||||
## Permissions
|
||||
|
||||
File permissions are specified by adding together the following octal flags:
|
||||
File permissions are specified by adding together the following octal modes:
|
||||
|
||||
* `0o400` - read permission: owner
|
||||
* `0o200` - write permission: owner
|
||||
@@ -1572,9 +1637,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `chmod/2`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `chmod/2`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec chmod!(Path.t(), non_neg_integer) :: :ok | no_return
|
||||
@spec chmod!(Path.t(), non_neg_integer) :: :ok
|
||||
def chmod!(path, mode) do
|
||||
case chmod(path, mode) do
|
||||
:ok ->
|
||||
@@ -1599,9 +1665,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `chgrp/2`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `chgrp/2`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec chgrp!(Path.t(), non_neg_integer) :: :ok | no_return
|
||||
@spec chgrp!(Path.t(), non_neg_integer) :: :ok
|
||||
def chgrp!(path, gid) do
|
||||
case chgrp(path, gid) do
|
||||
:ok ->
|
||||
@@ -1626,9 +1693,10 @@ defmodule File do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Same as `chown/2`, but raises an exception in case of failure. Otherwise `:ok`.
|
||||
Same as `chown/2`, but raises a `File.Error` exception in case of failure.
|
||||
Otherwise `:ok`.
|
||||
"""
|
||||
@spec chown!(Path.t(), non_neg_integer) :: :ok | no_return
|
||||
@spec chown!(Path.t(), non_neg_integer) :: :ok
|
||||
def chown!(path, uid) do
|
||||
case chown(path, uid) do
|
||||
:ok ->
|
||||
|
||||
@@ -12,7 +12,7 @@ defmodule File.Stat do
|
||||
|
||||
* `size` - size of file in bytes.
|
||||
|
||||
* `type` - `:device | :directory | :regular | :other`; the type of the
|
||||
* `type` - `:device | :directory | :regular | :other | :symlink`; the type of the
|
||||
file.
|
||||
|
||||
* `access` - `:read | :write | :read_write | :none`; the current system
|
||||
@@ -58,7 +58,22 @@ defmodule File.Stat do
|
||||
pairs = :lists.zip(keys, vals)
|
||||
|
||||
defstruct keys
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
size: non_neg_integer(),
|
||||
type: :device | :directory | :regular | :other | :symlink,
|
||||
access: :read | :write | :read_write | :none,
|
||||
atime: :calendar.datetime(),
|
||||
mtime: :calendar.datetime(),
|
||||
ctime: :calendar.datetime(),
|
||||
mode: non_neg_integer(),
|
||||
links: non_neg_integer(),
|
||||
major_device: non_neg_integer(),
|
||||
minor_device: non_neg_integer(),
|
||||
inode: non_neg_integer(),
|
||||
uid: non_neg_integer(),
|
||||
gid: non_neg_integer()
|
||||
}
|
||||
|
||||
@doc """
|
||||
Converts a `File.Stat` struct to a `:file_info` record.
|
||||
|
||||
@@ -140,12 +140,24 @@ defmodule File.Stream do
|
||||
end
|
||||
end
|
||||
|
||||
defp trim_bom(device, raw) do
|
||||
header = if raw, do: IO.binread(device, 4), else: IO.read(device, 1)
|
||||
{:ok, new_pos} = :file.position(device, bom_length(header))
|
||||
defp trim_bom(device, true) do
|
||||
bom_length = device |> IO.binread(4) |> bom_length()
|
||||
{:ok, new_pos} = :file.position(device, bom_length)
|
||||
{device, new_pos}
|
||||
end
|
||||
|
||||
defp trim_bom(device, false) do
|
||||
# Or we read the bom in the correct amount or it isn't there
|
||||
case bom_length(IO.read(device, 1)) do
|
||||
0 ->
|
||||
{:ok, _} = :file.position(device, 0)
|
||||
{device, 0}
|
||||
|
||||
_ ->
|
||||
{device, 1}
|
||||
end
|
||||
end
|
||||
|
||||
defp bom_length(<<239, 187, 191, _rest::binary>>), do: 3
|
||||
defp bom_length(<<254, 255, _rest::binary>>), do: 2
|
||||
defp bom_length(<<255, 254, _rest::binary>>), do: 2
|
||||
|
||||
+43
-24
@@ -33,7 +33,7 @@ defmodule Float do
|
||||
There are also other known problems like flooring or rounding numbers. See
|
||||
`round/2` and `floor/2` for more details about them.
|
||||
|
||||
To learn more about floting-point arithmetic visit:
|
||||
To learn more about floating-point arithmetic visit:
|
||||
|
||||
* [0.30000000000000004.com](http://0.30000000000000004.com/)
|
||||
* [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/)
|
||||
@@ -149,6 +149,10 @@ defmodule Float do
|
||||
@spec floor(float, precision_range) :: float
|
||||
def floor(number, precision \\ 0)
|
||||
|
||||
def floor(number, 0) when is_float(number) do
|
||||
:math.floor(number)
|
||||
end
|
||||
|
||||
def floor(number, precision) when is_float(number) and precision in @precision_range do
|
||||
round(number, precision, :floor)
|
||||
end
|
||||
@@ -192,6 +196,10 @@ defmodule Float do
|
||||
@spec ceil(float, precision_range) :: float
|
||||
def ceil(number, precision \\ 0)
|
||||
|
||||
def ceil(number, 0) when is_float(number) do
|
||||
:math.ceil(number)
|
||||
end
|
||||
|
||||
def ceil(number, precision) when is_float(number) and precision in @precision_range do
|
||||
round(number, precision, :ceil)
|
||||
end
|
||||
@@ -248,25 +256,26 @@ defmodule Float do
|
||||
# and could be implemented in the future.
|
||||
def round(float, precision \\ 0)
|
||||
|
||||
def round(float, 0) when is_float(float) do
|
||||
float |> :erlang.round() |> :erlang.float()
|
||||
end
|
||||
|
||||
def round(float, precision) when is_float(float) and precision in @precision_range do
|
||||
round(float, precision, :half_up)
|
||||
end
|
||||
|
||||
def round(number, precision) when is_float(number) do
|
||||
def round(float, precision) when is_float(float) do
|
||||
raise ArgumentError, invalid_precision_message(precision)
|
||||
end
|
||||
|
||||
defp round(0.0, _precision, _rounding), do: 0.0
|
||||
|
||||
defp round(float, precision, rounding) do
|
||||
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
|
||||
{num, count, _} = decompose(significant)
|
||||
{num, count, _} = decompose(significant, 1)
|
||||
count = count - exp + 1023
|
||||
|
||||
cond do
|
||||
# There is no decimal precision
|
||||
# zero or minus zero
|
||||
count <= 0 or (0 == exp and <<0::52>> == significant) ->
|
||||
float
|
||||
|
||||
# Precision beyond 15 digits
|
||||
count >= 104 ->
|
||||
case rounding do
|
||||
@@ -373,6 +382,8 @@ defmodule Float do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Float.ratio(0.0)
|
||||
{0, 1}
|
||||
iex> Float.ratio(3.14)
|
||||
{7070651414971679, 2251799813685248}
|
||||
iex> Float.ratio(-3.14)
|
||||
@@ -388,27 +399,35 @@ defmodule Float do
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec ratio(float) :: {pos_integer | neg_integer, pos_integer}
|
||||
@spec ratio(float) :: {integer, pos_integer}
|
||||
def ratio(0.0), do: {0, 1}
|
||||
|
||||
def ratio(float) when is_float(float) do
|
||||
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
|
||||
{num, _, den} = decompose(significant)
|
||||
num = sign(sign, num)
|
||||
case <<float::float>> do
|
||||
<<sign::1, 0::11, significant::52-bitstring>> ->
|
||||
{num, _, den} = decompose(significant, 0)
|
||||
{sign(sign, num), shift_left(den, 1022)}
|
||||
|
||||
case exp - 1023 do
|
||||
exp when exp > 0 ->
|
||||
{den, exp} = shift_right(den, exp)
|
||||
{shift_left(num, exp), den}
|
||||
<<sign::1, exp::11, significant::52-bitstring>> ->
|
||||
{num, _, den} = decompose(significant, 1)
|
||||
num = sign(sign, num)
|
||||
|
||||
exp when exp < 0 ->
|
||||
{num, shift_left(den, -exp)}
|
||||
case exp - 1023 do
|
||||
exp when exp > 0 ->
|
||||
{den, exp} = shift_right(den, exp)
|
||||
{shift_left(num, exp), den}
|
||||
|
||||
0 ->
|
||||
{num, den}
|
||||
exp when exp < 0 ->
|
||||
{num, shift_left(den, -exp)}
|
||||
|
||||
0 ->
|
||||
{num, den}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp decompose(significant) do
|
||||
decompose(significant, 1, 0, 2, 1, 1)
|
||||
defp decompose(significant, initial) do
|
||||
decompose(significant, 1, 0, 2, 1, initial)
|
||||
end
|
||||
|
||||
defp decompose(<<1::1, bits::bitstring>>, count, last_count, power, _last_power, acc) do
|
||||
@@ -423,11 +442,11 @@ defmodule Float do
|
||||
{acc, last_count, last_power}
|
||||
end
|
||||
|
||||
@compile {:inline, sign: 2, shift_left: 2}
|
||||
defp sign(0, num), do: num
|
||||
defp sign(1, num), do: -num
|
||||
|
||||
defp shift_left(num, 0), do: num
|
||||
defp shift_left(num, times), do: shift_left(num <<< 1, times - 1)
|
||||
defp shift_left(num, times), do: num <<< times
|
||||
|
||||
defp shift_right(num, 0), do: {num, 0}
|
||||
defp shift_right(1, times), do: {1, times}
|
||||
|
||||
+134
-71
@@ -61,7 +61,9 @@ 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`.
|
||||
A `cast/2` message must be handled by `c:handle_cast/2`. There are 7 possible
|
||||
callbacks to be implemented when you use a `GenServer`. The only required
|
||||
callback is `init/1`.
|
||||
|
||||
## Client / Server APIs
|
||||
|
||||
@@ -111,25 +113,46 @@ defmodule GenServer do
|
||||
the same module. If the server and/or client implementations are growing
|
||||
complex, you may want to have them in different modules.
|
||||
|
||||
## use GenServer and callbacks
|
||||
## How to supervise
|
||||
|
||||
There are 7 callbacks to be implemented when you use a `GenServer`.
|
||||
The only required callback is `init/1`.
|
||||
A `GenServer` is most commonly started under a supervision tree.
|
||||
When we invoke `use GenServer`, it automatically defines a `child_spec/1`
|
||||
function that allows us to start the `Stack` directly under a supervisor.
|
||||
To start a default stack of `[:hello]` under a supervisor, one may do:
|
||||
|
||||
`use GenServer` also defines a `child_spec/1` function, allowing the
|
||||
defined module to be put under a supervision tree. The generated
|
||||
`child_spec/1` can be customized with the following options:
|
||||
children = [
|
||||
{Stack, [:hello]}
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_all)
|
||||
|
||||
Note you can also start it simply as `Stack`, which is the same as
|
||||
`{Stack, []}`:
|
||||
|
||||
children = [
|
||||
Stack # The same as {Stack, []}
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_all)
|
||||
|
||||
In both cases, `Stack.start_link/1` is always invoked.
|
||||
|
||||
`use GenServer` also accepts a list of options which configures the
|
||||
child specification and therefore how it runs under a supervisor.
|
||||
The generated `child_spec/1` can be customized with the following options:
|
||||
|
||||
* `:id` - the child specification identifier, defaults to the current module
|
||||
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
|
||||
* `:restart` - when the child should be restarted, defaults to `:permanent`
|
||||
* `:shutdown` - how to shut down the child
|
||||
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
|
||||
|
||||
For example:
|
||||
|
||||
use GenServer, restart: :transient, shutdown: 10_000
|
||||
|
||||
See the `Supervisor` docs for more information.
|
||||
See the "Child specification" section in the `Supervisor` module for more
|
||||
detailed information. The `@doc` annotation immediately preceding
|
||||
`use GenServer` will be attached to the generated `child_spec/1` function.
|
||||
|
||||
## Name registration
|
||||
|
||||
@@ -158,7 +181,8 @@ defmodule GenServer do
|
||||
{:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack)
|
||||
|
||||
# Now messages can be sent directly to MyStack
|
||||
GenServer.call(MyStack, :pop) #=> :hello
|
||||
GenServer.call(MyStack, :pop)
|
||||
#=> :hello
|
||||
|
||||
Once the server is started, the remaining functions in this module (`call/3`,
|
||||
`cast/2`, and friends) will also accept an atom, or any `{:global, ...}` or
|
||||
@@ -195,25 +219,32 @@ defmodule GenServer do
|
||||
defmodule MyApp.Periodically do
|
||||
use GenServer
|
||||
|
||||
def start_link do
|
||||
def start_link(_) do
|
||||
GenServer.start_link(__MODULE__, %{})
|
||||
end
|
||||
|
||||
@impl true
|
||||
def init(state) do
|
||||
schedule_work() # Schedule work to be performed on start
|
||||
# Schedule work to be performed on start
|
||||
schedule_work()
|
||||
|
||||
{:ok, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info(:work, state) do
|
||||
# Do the desired work here
|
||||
schedule_work() # Reschedule once more
|
||||
...
|
||||
|
||||
# Reschedule once more
|
||||
schedule_work()
|
||||
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
defp schedule_work() do
|
||||
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
|
||||
defp schedule_work do
|
||||
# In 2 hours
|
||||
Process.send_after(self(), :work, 2 * 60 * 60 * 1000)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -300,29 +331,48 @@ defmodule GenServer do
|
||||
*DBG* <0.122.0> got cast {push,1}
|
||||
*DBG* <0.122.0> new state [1]
|
||||
:ok
|
||||
|
||||
iex> :sys.get_state(pid)
|
||||
[1]
|
||||
|
||||
iex> Stack.pop(pid)
|
||||
*DBG* <0.122.0> got call pop from <0.80.0>
|
||||
*DBG* <0.122.0> sent 1 to <0.80.0>, new state []
|
||||
1
|
||||
|
||||
iex> :sys.statistics(pid, :get)
|
||||
{:ok,
|
||||
[start_time: {{2016, 7, 16}, {12, 29, 41}},
|
||||
current_time: {{2016, 7, 16}, {12, 29, 50}},
|
||||
reductions: 117, messages_in: 2, messages_out: 0]}
|
||||
[
|
||||
start_time: {{2016, 7, 16}, {12, 29, 41}},
|
||||
current_time: {{2016, 7, 16}, {12, 29, 50}},
|
||||
reductions: 117,
|
||||
messages_in: 2,
|
||||
messages_out: 0
|
||||
]}
|
||||
|
||||
iex> :sys.no_debug(pid) # turn off all debug handlers
|
||||
:ok
|
||||
|
||||
iex> :sys.get_status(pid)
|
||||
{:status, #PID<0.122.0>, {:module, :gen_server},
|
||||
[["$initial_call": {Stack, :init, 1}, # pdict
|
||||
"$ancestors": [#PID<0.80.0>, #PID<0.51.0>]],
|
||||
:running, # :running | :suspended
|
||||
#PID<0.80.0>, # parent
|
||||
[], # debugger state
|
||||
[header: 'Status for generic server <0.122.0>', # module status
|
||||
data: [{'Status', :running}, {'Parent', #PID<0.80.0>},
|
||||
{'Logged events', []}], data: [{'State', [1]}]]]}
|
||||
[
|
||||
[
|
||||
"$initial_call": {Stack, :init, 1}, # process dictionary
|
||||
"$ancestors": [#PID<0.80.0>, #PID<0.51.0>]
|
||||
],
|
||||
:running, # :running | :suspended
|
||||
#PID<0.80.0>, # parent
|
||||
[], # debugger state
|
||||
[
|
||||
header: 'Status for generic server <0.122.0>', # module status
|
||||
data: [
|
||||
{'Status', :running},
|
||||
{'Parent', #PID<0.80.0>},
|
||||
{'Logged events', []}
|
||||
],
|
||||
data: [{'State', [1]}]
|
||||
]
|
||||
]}
|
||||
|
||||
## Learn more
|
||||
|
||||
@@ -330,10 +380,10 @@ defmodule GenServer do
|
||||
guide provides a tutorial-like introduction. The documentation and links
|
||||
in Erlang can also provide extra insight.
|
||||
|
||||
* [GenServer – Elixir's Getting Started Guide](http://elixir-lang.org/getting-started/mix-otp/genserver.html)
|
||||
* [GenServer - Elixir's Getting Started Guide](https://elixir-lang.org/getting-started/mix-otp/genserver.html)
|
||||
* [`:gen_server` module documentation](http://www.erlang.org/doc/man/gen_server.html)
|
||||
* [gen_server Behaviour – OTP Design Principles](http://www.erlang.org/doc/design_principles/gen_server_concepts.html)
|
||||
* [Clients and Servers – Learn You Some Erlang for Great Good!](http://learnyousomeerlang.com/clients-and-servers)
|
||||
* [gen_server Behaviour - OTP Design Principles](http://www.erlang.org/doc/design_principles/gen_server_concepts.html)
|
||||
* [Clients and Servers - Learn You Some Erlang for Great Good!](http://learnyousomeerlang.com/clients-and-servers)
|
||||
|
||||
"""
|
||||
|
||||
@@ -341,7 +391,7 @@ defmodule GenServer do
|
||||
Invoked when the server is started. `start_link/3` or `start/3` will
|
||||
block until it returns.
|
||||
|
||||
`args` is the argument term (second argument) passed to `start_link/3`.
|
||||
`init_arg` is the argument term (second argument) passed to `start_link/3`.
|
||||
|
||||
Returning `{:ok, state}` will cause `start_link/3` to return
|
||||
`{:ok, pid}` and the process to enter its loop.
|
||||
@@ -378,7 +428,7 @@ defmodule GenServer do
|
||||
`{:error, reason}` and the process to exit with reason `reason` without
|
||||
entering the loop or calling `c:terminate/2`.
|
||||
"""
|
||||
@callback init(args :: term) ::
|
||||
@callback init(init_arg :: term) ::
|
||||
{:ok, state}
|
||||
| {:ok, state, timeout | :hibernate | {:continue, term}}
|
||||
| :ignore
|
||||
@@ -450,7 +500,7 @@ defmodule GenServer do
|
||||
{:reply, reply, new_state}
|
||||
| {:reply, reply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate, {:continue, term}}
|
||||
| {:noreply, new_state, timeout | :hibernate | {:continue, term}}
|
||||
| {:stop, reason, reply, new_state}
|
||||
| {:stop, reason, new_state}
|
||||
when reply: term, new_state: term, reason: term
|
||||
@@ -540,13 +590,20 @@ defmodule GenServer do
|
||||
* the `GenServer` traps exits (using `Process.flag/2`) *and* the parent
|
||||
process sends an exit signal
|
||||
|
||||
If part of a supervision tree, a `GenServer`'s `Supervisor` will send an exit
|
||||
signal when shutting it down. The exit signal is based on the shutdown
|
||||
strategy in the child's specification. If it is `:brutal_kill` the `GenServer`
|
||||
is killed and so `c:terminate/2` is not called. However if it is a timeout the
|
||||
`Supervisor` will send the exit signal `:shutdown` and the `GenServer` will
|
||||
have the duration of the timeout to call `c:terminate/2` - if the process is
|
||||
still alive after the timeout it is killed.
|
||||
If part of a supervision tree, a `GenServer`'s will receive an exit
|
||||
signal when the tree is shutting down. The exit signal is based on
|
||||
the shutdown strategy in the child's specification, where we this
|
||||
value can be:
|
||||
|
||||
* `:brutal_kill`: the `GenServer` is killed and so `c:terminate/2` is not called.
|
||||
|
||||
* a timeout value, where the supervisor will send the exit signal `:shutdown` and
|
||||
the `GenServer` will have the duration of the timeout to terminate.
|
||||
If after duration of this timeout the process is still alive, it will be killed
|
||||
immediately.
|
||||
|
||||
For a more in-depth explanation, please read the "Shutdown values (:shutdown)"
|
||||
section in the `Supervisor` module.
|
||||
|
||||
If the `GenServer` receives an exit signal (that is not `:normal`) from any
|
||||
process when it is not trapping exits it will exit abruptly with the same
|
||||
@@ -562,7 +619,7 @@ defmodule GenServer do
|
||||
receiving a `GenServer`'s exit signal and do not need to be closed manually
|
||||
in `c:terminate/2`.
|
||||
|
||||
If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is
|
||||
If `reason` is neither `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is
|
||||
logged.
|
||||
|
||||
This callback is optional.
|
||||
@@ -640,6 +697,7 @@ defmodule GenServer do
|
||||
| {:name, name}
|
||||
| {:timeout, timeout}
|
||||
| {:spawn_opt, Process.spawn_opt()}
|
||||
| {:hibernate_after, timeout}
|
||||
|
||||
@typedoc "Debug options supported by the `start*` functions"
|
||||
@type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t()}]
|
||||
@@ -660,15 +718,18 @@ defmodule GenServer do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@behaviour GenServer
|
||||
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
See `Supervisor`.
|
||||
"""
|
||||
end
|
||||
|
||||
def child_spec(init_arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
start: {__MODULE__, :start_link, [arg]}
|
||||
start: {__MODULE__, :start_link, [init_arg]}
|
||||
}
|
||||
|
||||
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
|
||||
@@ -750,8 +811,8 @@ defmodule GenServer do
|
||||
|
||||
We will inject a default implementation for now:
|
||||
|
||||
def init(args) do
|
||||
{:ok, args}
|
||||
def init(init_arg) do
|
||||
{:ok, init_arg}
|
||||
end
|
||||
|
||||
You can copy the implementation above or define your own that converts \
|
||||
@@ -762,8 +823,8 @@ defmodule GenServer do
|
||||
|
||||
quote do
|
||||
@doc false
|
||||
def init(args) do
|
||||
{:ok, args}
|
||||
def init(init_arg) do
|
||||
{:ok, init_arg}
|
||||
end
|
||||
|
||||
defoverridable init: 1
|
||||
@@ -777,7 +838,7 @@ defmodule GenServer do
|
||||
This is often used to start the `GenServer` as part of a supervision tree.
|
||||
|
||||
Once the server is started, the `c:init/1` function of the given `module` is
|
||||
called with `args` as its arguments to initialize the server. To ensure a
|
||||
called with `init_arg` as its argument to initialize the server. To ensure a
|
||||
synchronized start-up procedure, this function does not return until `c:init/1`
|
||||
has returned.
|
||||
|
||||
@@ -800,6 +861,10 @@ defmodule GenServer do
|
||||
* `:spawn_opt` - if present, its value is passed as options to the
|
||||
underlying process as in `Process.spawn/4`
|
||||
|
||||
* `:hibernate_after` - if present, the GenServer process awaits any message for
|
||||
the given number of milliseconds and if no message is received, the process goes
|
||||
into hibernation automatically (by calling `:proc_lib.hibernate/3`).
|
||||
|
||||
## Return values
|
||||
|
||||
If the server is successfully created and initialized, this function returns
|
||||
@@ -813,8 +878,8 @@ defmodule GenServer do
|
||||
`{:error, reason}` or `:ignore`, respectively.
|
||||
"""
|
||||
@spec start_link(module, any, options) :: on_start
|
||||
def start_link(module, args, options \\ []) when is_atom(module) and is_list(options) do
|
||||
do_start(:link, module, args, options)
|
||||
def start_link(module, init_arg, options \\ []) when is_atom(module) and is_list(options) do
|
||||
do_start(:link, module, init_arg, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -823,23 +888,23 @@ defmodule GenServer do
|
||||
See `start_link/3` for more information.
|
||||
"""
|
||||
@spec start(module, any, options) :: on_start
|
||||
def start(module, args, options \\ []) when is_atom(module) and is_list(options) do
|
||||
do_start(:nolink, module, args, options)
|
||||
def start(module, init_arg, options \\ []) when is_atom(module) and is_list(options) do
|
||||
do_start(:nolink, module, init_arg, options)
|
||||
end
|
||||
|
||||
defp do_start(link, module, args, options) do
|
||||
defp do_start(link, module, init_arg, options) do
|
||||
case Keyword.pop(options, :name) do
|
||||
{nil, opts} ->
|
||||
:gen.start(:gen_server, link, module, args, opts)
|
||||
:gen.start(:gen_server, link, module, init_arg, opts)
|
||||
|
||||
{atom, opts} when is_atom(atom) ->
|
||||
:gen.start(:gen_server, link, {:local, atom}, module, args, opts)
|
||||
:gen.start(:gen_server, link, {:local, atom}, module, init_arg, opts)
|
||||
|
||||
{{:global, _term} = tuple, opts} ->
|
||||
:gen.start(:gen_server, link, tuple, module, args, opts)
|
||||
:gen.start(:gen_server, link, tuple, module, init_arg, opts)
|
||||
|
||||
{{:via, via_module, _term} = tuple, opts} when is_atom(via_module) ->
|
||||
:gen.start(:gen_server, link, tuple, module, args, opts)
|
||||
:gen.start(:gen_server, link, tuple, module, init_arg, opts)
|
||||
|
||||
{other, _} ->
|
||||
raise ArgumentError, """
|
||||
@@ -938,11 +1003,13 @@ defmodule GenServer do
|
||||
|
||||
`c:handle_cast/2` will be called on the server to handle
|
||||
the request. In case the `server` is on a node which is
|
||||
not yet connected to the caller one, the call is going to
|
||||
block until a connection happens. This is different than
|
||||
the behaviour in OTP's `:gen_server` where the message
|
||||
is sent by another process in this case, which could cause
|
||||
messages to other nodes to arrive out of order.
|
||||
not yet connected to the caller one, the semantics differ
|
||||
depending on the used Erlang/OTP version.
|
||||
|
||||
Before Erlang/OTP 21, the call is going to block until a
|
||||
connection happens. This was done to guarantee ordering.
|
||||
Starting with Erlang/OTP 21, both Erlang and Elixir do
|
||||
not block the call.
|
||||
"""
|
||||
@spec cast(server, term) :: :ok
|
||||
def cast(server, request)
|
||||
@@ -1068,12 +1135,8 @@ defmodule GenServer do
|
||||
def reply(client, reply)
|
||||
|
||||
def reply({to, tag}, reply) when is_pid(to) do
|
||||
try do
|
||||
send(to, {tag, reply})
|
||||
:ok
|
||||
catch
|
||||
_, _ -> :ok
|
||||
end
|
||||
send(to, {tag, reply})
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
@@ -20,7 +20,7 @@ defprotocol Inspect do
|
||||
## Examples
|
||||
|
||||
Many times, inspecting a structure can be implemented in function
|
||||
of existing entities. For example, here is `MapSet`'s `inspect`
|
||||
of existing entities. For example, here is `MapSet`'s `inspect/2`
|
||||
implementation:
|
||||
|
||||
defimpl Inspect, for: MapSet do
|
||||
@@ -39,8 +39,8 @@ defprotocol Inspect do
|
||||
other string `">"`.
|
||||
|
||||
Since regular strings are valid entities in an algebra document,
|
||||
an implementation of inspect may simply return a string,
|
||||
although that will devoid it of any pretty-printing.
|
||||
an implementation of the `Inspect` protocol may simply return a
|
||||
string, although that will devoid it of any pretty-printing.
|
||||
|
||||
## Error handling
|
||||
|
||||
@@ -48,12 +48,30 @@ defprotocol Inspect do
|
||||
Elixir will raise an `ArgumentError` error and will automatically fall back
|
||||
to a raw representation for printing the structure.
|
||||
|
||||
You can however access the underlying error by invoking the Inspect
|
||||
implementation directly. For example, to test Inspect.MapSet above,
|
||||
You can however access the underlying error by invoking the `Inspect`
|
||||
implementation directly. For example, to test `Inspect.MapSet` above,
|
||||
you can invoke it as:
|
||||
|
||||
Inspect.MapSet.inspect(MapSet.new(), %Inspect.Opts{})
|
||||
|
||||
## Deriving
|
||||
|
||||
The `Inspect` protocol can be derived to hide certain fields from
|
||||
structs, so they don't show up in logs, inspects and similar. This
|
||||
is especially useful for fields containing private information.
|
||||
|
||||
The options `:only` and `:except` can be used with `@derive` to
|
||||
specify which fields should and should not appear in the
|
||||
algebra document:
|
||||
|
||||
defmodule User do
|
||||
@derive {Inspect, only: [:id, :name]}
|
||||
defstruct [:id, :name, :address]
|
||||
end
|
||||
|
||||
inspect(%User{id: 1, name: "Homer", address: "742 Evergreen Terrace"})
|
||||
#=> #User<id: 1, name: "Homer", ...>
|
||||
|
||||
"""
|
||||
|
||||
# Handle structs in Any
|
||||
@@ -372,6 +390,39 @@ defimpl Inspect, for: Reference do
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Any do
|
||||
defmacro __deriving__(module, struct, options) do
|
||||
fields =
|
||||
struct
|
||||
|> Map.drop([:__exception__, :__struct__])
|
||||
|> Map.keys()
|
||||
|
||||
only = Keyword.get(options, :only, fields)
|
||||
except = Keyword.get(options, :except, [])
|
||||
|
||||
filtered_fields =
|
||||
fields
|
||||
|> Enum.reject(&(&1 in except))
|
||||
|> Enum.filter(&(&1 in only))
|
||||
|
||||
inspect_module =
|
||||
if fields == only and except == [] do
|
||||
quote(do: Inspect.Map)
|
||||
else
|
||||
quote(do: Inspect.Any)
|
||||
end
|
||||
|
||||
quote do
|
||||
defimpl Inspect, for: unquote(module) do
|
||||
def inspect(struct, opts) do
|
||||
map = Map.take(struct, unquote(filtered_fields))
|
||||
colorless_opts = %{opts | syntax_colors: []}
|
||||
name = Inspect.Atom.inspect(unquote(module), colorless_opts)
|
||||
unquote(inspect_module).inspect(map, name, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def inspect(%module{} = struct, opts) do
|
||||
try do
|
||||
module.__struct__
|
||||
@@ -388,4 +439,17 @@ defimpl Inspect, for: Any do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def inspect(map, name, opts) do
|
||||
# Use the :limit option and an extra element to force
|
||||
# `container_doc/6` to append "...".
|
||||
opts = %{opts | limit: min(opts.limit, map_size(map))}
|
||||
map = :maps.to_list(map) ++ ["..."]
|
||||
|
||||
open = color("#" <> name <> "<", :map, opts)
|
||||
sep = color(",", :map, opts)
|
||||
close = color(">", :map, opts)
|
||||
|
||||
container_doc(open, map, close, opts, &Inspect.List.keyword/2, separator: sep, break: :strict)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
defmodule Inspect.Opts do
|
||||
@moduledoc """
|
||||
Defines the Inspect.Opts used by the Inspect protocol.
|
||||
Defines the options used by the `Inspect` protocol.
|
||||
|
||||
The following fields are available:
|
||||
|
||||
@@ -15,8 +15,8 @@ defmodule Inspect.Opts do
|
||||
When the default `:infer`, the binary will be printed as a string if it
|
||||
is printable, otherwise in bit syntax.
|
||||
|
||||
* `:charlists` - when `:as_charlists` all lists will be printed as char
|
||||
lists, non-printable elements will be escaped.
|
||||
* `:charlists` - when `:as_charlists` all lists will be printed as charlists,
|
||||
non-printable elements will be escaped.
|
||||
|
||||
When `:as_lists` all lists will be printed as lists.
|
||||
|
||||
@@ -29,7 +29,7 @@ defmodule Inspect.Opts do
|
||||
the number of items to a particular number, use `:infinity`.
|
||||
|
||||
* `:printable_limit` - limits the number of bytes that are printed for strings
|
||||
and char lists. Defaults to 4096. If you don't want to limit the number of items
|
||||
and charlists. Defaults to 4096. If you don't want to limit the number of items
|
||||
to a particular number, use `:infinity`.
|
||||
|
||||
* `:pretty` - if set to `true` enables pretty printing, defaults to `false`.
|
||||
@@ -148,7 +148,7 @@ defmodule Inspect.Algebra do
|
||||
|
||||
## Implementation details
|
||||
|
||||
The implementation of Inspect.Algebra is based on the Strictly Pretty
|
||||
The implementation of `Inspect.Algebra` is based on the Strictly Pretty
|
||||
paper by [Lindig][0] which builds on top of previous pretty printing
|
||||
algorithms but is tailored to strict languages, such as Elixir.
|
||||
The core idea in the paper is the use of explicit document groups which
|
||||
@@ -312,7 +312,7 @@ defmodule Inspect.Algebra do
|
||||
attempts to put as much as possible on the same line. If they are not simple,
|
||||
only one entry is shown per line if they do not fit.
|
||||
|
||||
The limit in the given `Inspect.Opts` is respected and when reached this
|
||||
The limit in the given `inspect_opts` is respected and when reached this
|
||||
function stops processing and outputs `"..."` instead.
|
||||
|
||||
## Options
|
||||
@@ -324,18 +324,22 @@ defmodule Inspect.Algebra do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]",
|
||||
...> %Inspect.Opts{limit: :infinity}, fn i, _opts -> to_string(i) end)
|
||||
iex> inspect_opts = %Inspect.Opts{limit: :infinity}
|
||||
iex> fun = fn i, _opts -> to_string(i) end
|
||||
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]", inspect_opts, fun)
|
||||
iex> Inspect.Algebra.format(doc, 5) |> IO.iodata_to_binary()
|
||||
"[1,\n 2,\n 3,\n 4,\n 5]"
|
||||
|
||||
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]",
|
||||
...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end)
|
||||
iex> inspect_opts = %Inspect.Opts{limit: 3}
|
||||
iex> fun = fn i, _opts -> to_string(i) end
|
||||
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]", inspect_opts, fun)
|
||||
iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary()
|
||||
"[1, 2, 3, ...]"
|
||||
|
||||
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]",
|
||||
...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end, separator: "!")
|
||||
iex> inspect_opts = %Inspect.Opts{limit: 3}
|
||||
iex> fun = fn i, _opts -> to_string(i) end
|
||||
iex> opts = [separator: "!"]
|
||||
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]", inspect_opts, fun, opts)
|
||||
iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary()
|
||||
"[1! 2! 3! ...]"
|
||||
|
||||
@@ -343,7 +347,7 @@ defmodule Inspect.Algebra do
|
||||
@doc since: "1.6.0"
|
||||
@spec container_doc(t, [any], t, Inspect.Opts.t(), (term, Inspect.Opts.t() -> t), keyword()) ::
|
||||
t
|
||||
def container_doc(left, collection, right, inspect, fun, opts \\ [])
|
||||
def container_doc(left, collection, right, inspect_opts, fun, opts \\ [])
|
||||
when is_doc(left) and is_list(collection) and is_doc(right) and is_function(fun, 2) and
|
||||
is_list(opts) do
|
||||
case collection do
|
||||
@@ -355,7 +359,7 @@ defmodule Inspect.Algebra do
|
||||
separator = Keyword.get(opts, :separator, @container_separator)
|
||||
|
||||
{docs, simple?} =
|
||||
container_each(collection, inspect.limit, inspect, fun, [], break == :maybe)
|
||||
container_each(collection, inspect_opts.limit, inspect_opts, fun, [], break == :maybe)
|
||||
|
||||
flex? = simple? or break == :flex
|
||||
docs = fold_doc(docs, &join(&1, &2, flex?, separator))
|
||||
@@ -406,14 +410,16 @@ defmodule Inspect.Algebra do
|
||||
defp simple?(:doc_nil), do: true
|
||||
defp simple?(other), do: is_binary(other)
|
||||
|
||||
# TODO: Remove on 2.0
|
||||
@doc false
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
@deprecated "Use a combination of concat/2 and nest/2 instead"
|
||||
def surround(left, doc, right) when is_doc(left) and is_doc(doc) and is_doc(right) do
|
||||
concat(concat(left, nest(doc, 1)), right)
|
||||
end
|
||||
|
||||
# TODO: Remove on 2.0
|
||||
@doc false
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
@deprecated "Use Inspect.Algebra.container_doc/6 instead"
|
||||
def surround_many(
|
||||
left,
|
||||
docs,
|
||||
@@ -538,7 +544,7 @@ defmodule Inspect.Algebra do
|
||||
["hello", "\n ", "world"]
|
||||
|
||||
"""
|
||||
@spec nest(t, non_neg_integer) :: doc_nest
|
||||
@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
|
||||
@@ -640,7 +646,7 @@ defmodule Inspect.Algebra do
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec next_break_fits(t) :: doc_fits
|
||||
@spec next_break_fits(t, :enabled | :disabled) :: doc_fits
|
||||
def next_break_fits(doc, mode \\ @next_break_fits)
|
||||
when is_doc(doc) and mode in [:enabled, :disabled] do
|
||||
doc_fits(doc, mode)
|
||||
@@ -735,29 +741,31 @@ defmodule Inspect.Algebra do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> doc = Inspect.Algebra.group(
|
||||
...> Inspect.Algebra.concat(
|
||||
...> Inspect.Algebra.group(
|
||||
...> Inspect.Algebra.concat(
|
||||
...> "Hello,",
|
||||
...> Inspect.Algebra.concat(
|
||||
...> Inspect.Algebra.break,
|
||||
...> "A"
|
||||
...> )
|
||||
...> )
|
||||
...> ),
|
||||
iex> doc =
|
||||
...> Inspect.Algebra.group(
|
||||
...> Inspect.Algebra.concat(
|
||||
...> Inspect.Algebra.break,
|
||||
...> "B"
|
||||
...> Inspect.Algebra.group(
|
||||
...> Inspect.Algebra.concat(
|
||||
...> "Hello,",
|
||||
...> Inspect.Algebra.concat(
|
||||
...> Inspect.Algebra.break(),
|
||||
...> "A"
|
||||
...> )
|
||||
...> )
|
||||
...> ),
|
||||
...> Inspect.Algebra.concat(
|
||||
...> Inspect.Algebra.break(),
|
||||
...> "B"
|
||||
...> )
|
||||
...> )
|
||||
...> ))
|
||||
...> )
|
||||
iex> Inspect.Algebra.format(doc, 80)
|
||||
["Hello,", " ", "A", " ", "B"]
|
||||
iex> Inspect.Algebra.format(doc, 6)
|
||||
["Hello,", "\n", "A", "\n", "B"]
|
||||
|
||||
"""
|
||||
@spec group(t) :: doc_group
|
||||
@spec group(t, :self | :inherit) :: doc_group
|
||||
def group(doc, mode \\ :self) when is_doc(doc) do
|
||||
doc_group(doc, mode)
|
||||
end
|
||||
@@ -787,7 +795,8 @@ defmodule Inspect.Algebra do
|
||||
...> Inspect.Algebra.concat(
|
||||
...> "Hughes",
|
||||
...> Inspect.Algebra.line()
|
||||
...> ), "Wadler"
|
||||
...> ),
|
||||
...> "Wadler"
|
||||
...> )
|
||||
iex> Inspect.Algebra.format(doc, 80)
|
||||
["Hughes", "\n", "Wadler"]
|
||||
@@ -822,9 +831,10 @@ defmodule Inspect.Algebra do
|
||||
## Examples
|
||||
|
||||
iex> docs = ["A", "B", "C"]
|
||||
iex> docs = Inspect.Algebra.fold_doc(docs, fn(doc, acc) ->
|
||||
...> Inspect.Algebra.concat([doc, "!", acc])
|
||||
...> end)
|
||||
iex> docs =
|
||||
...> Inspect.Algebra.fold_doc(docs, fn doc, acc ->
|
||||
...> Inspect.Algebra.concat([doc, "!", acc])
|
||||
...> end)
|
||||
iex> Inspect.Algebra.format(docs, 80)
|
||||
["A", "!", "B", "!", "C"]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ defmodule Integer do
|
||||
|
||||
Some functions that work on integers are found in `Kernel`:
|
||||
|
||||
* `abs/2`
|
||||
* `abs/1`
|
||||
* `div/2`
|
||||
* `max/2`
|
||||
* `min/2`
|
||||
@@ -158,7 +158,7 @@ defmodule Integer do
|
||||
Returns the integer represented by the ordered `digits`.
|
||||
|
||||
An optional `base` value may be provided representing the radix for the `digits`.
|
||||
Base has to be an integer greater or equal than `2`.
|
||||
Base has to be an integer greater than or equal to `2`.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
+13
-13
@@ -36,7 +36,7 @@ defmodule IO do
|
||||
|
||||
@type device :: atom | pid
|
||||
@type nodata :: {:error, term} | :eof
|
||||
@type chardata() :: :unicode.chardata()
|
||||
@type chardata :: String.t() | maybe_improper_list(char | chardata, String.t() | [])
|
||||
|
||||
defmacrop is_iodata(data) do
|
||||
quote do
|
||||
@@ -147,10 +147,10 @@ defmodule IO do
|
||||
|
||||
## Examples
|
||||
|
||||
IO.write "sample"
|
||||
IO.write("sample")
|
||||
#=> sample
|
||||
|
||||
IO.write :stderr, "error"
|
||||
IO.write(:stderr, "error")
|
||||
#=> error
|
||||
|
||||
"""
|
||||
@@ -183,10 +183,10 @@ defmodule IO do
|
||||
|
||||
## Examples
|
||||
|
||||
IO.puts "Hello World!"
|
||||
IO.puts("Hello World!")
|
||||
#=> Hello World!
|
||||
|
||||
IO.puts :stderr, "error"
|
||||
IO.puts(:stderr, "error")
|
||||
#=> error
|
||||
|
||||
"""
|
||||
@@ -207,7 +207,7 @@ defmodule IO do
|
||||
## Examples
|
||||
|
||||
stacktrace = [{MyApp, :main, 1, [file: 'my_app.ex', line: 4]}]
|
||||
IO.warn "variable bar is unused", stacktrace
|
||||
IO.warn("variable bar is unused", stacktrace)
|
||||
#=> warning: variable bar is unused
|
||||
#=> my_app.ex:4: MyApp.main/1
|
||||
|
||||
@@ -232,7 +232,7 @@ defmodule IO do
|
||||
|
||||
## Examples
|
||||
|
||||
IO.warn "variable bar is unused"
|
||||
IO.warn("variable bar is unused")
|
||||
#=> warning: variable bar is unused
|
||||
#=> (iex) evaluator.ex:108: IEx.Evaluator.eval/4
|
||||
|
||||
@@ -263,7 +263,7 @@ defmodule IO do
|
||||
|
||||
## Examples
|
||||
|
||||
IO.inspect <<0, 1, 2>>, width: 40
|
||||
IO.inspect(<<0, 1, 2>>, width: 40)
|
||||
|
||||
Prints:
|
||||
|
||||
@@ -271,7 +271,7 @@ defmodule IO do
|
||||
|
||||
We can use the `:label` option to decorate the output:
|
||||
|
||||
IO.inspect 1..100, label: "a wonderful range"
|
||||
IO.inspect(1..100, label: "a wonderful range")
|
||||
|
||||
Prints:
|
||||
|
||||
@@ -283,7 +283,7 @@ defmodule IO do
|
||||
|> IO.inspect(label: "before")
|
||||
|> Enum.map(&(&1 * 2))
|
||||
|> IO.inspect(label: "after")
|
||||
|> Enum.sum
|
||||
|> Enum.sum()
|
||||
|
||||
Prints:
|
||||
|
||||
@@ -374,7 +374,7 @@ defmodule IO do
|
||||
|
||||
To display "What is your name?" as a prompt and await user input:
|
||||
|
||||
IO.gets "What is your name?\n"
|
||||
IO.gets("What is your name?\n")
|
||||
|
||||
"""
|
||||
@spec gets(device, chardata | String.Chars.t()) :: chardata | nodata
|
||||
@@ -403,7 +403,7 @@ defmodule IO do
|
||||
Here is an example on how we mimic an echo server
|
||||
from the command line:
|
||||
|
||||
Enum.each IO.stream(:stdio, :line), &IO.write(&1)
|
||||
Enum.each(IO.stream(:stdio, :line), &IO.write(&1))
|
||||
|
||||
"""
|
||||
@spec stream(device, :line | pos_integer) :: Enumerable.t()
|
||||
@@ -457,7 +457,7 @@ defmodule IO do
|
||||
"string"
|
||||
|
||||
"""
|
||||
@spec chardata_to_string(chardata) :: String.t() | no_return
|
||||
@spec chardata_to_string(chardata) :: String.t()
|
||||
def chardata_to_string(string) when is_binary(string) do
|
||||
string
|
||||
end
|
||||
|
||||
@@ -7,12 +7,13 @@ defmodule IO.ANSI.Docs do
|
||||
@doc """
|
||||
The default options used by this module.
|
||||
|
||||
The supported values are:
|
||||
The supported keys are:
|
||||
|
||||
* `:enabled` - toggles coloring on and off (true)
|
||||
* `:doc_bold` - bold text (bright)
|
||||
* `:doc_code` - code blocks (cyan)
|
||||
* `:doc_headings` - h1, h2, h3, h4, h5, h6 headings (yellow)
|
||||
* `:doc_metadata` - documentation metadata keys (yellow)
|
||||
* `:doc_inline_code` - inline code (cyan)
|
||||
* `:doc_table_heading` - the style for table headings
|
||||
* `:doc_title` - top level heading (reverse, yellow)
|
||||
@@ -29,6 +30,7 @@ defmodule IO.ANSI.Docs do
|
||||
doc_bold: [:bright],
|
||||
doc_code: [:cyan],
|
||||
doc_headings: [:yellow],
|
||||
doc_metadata: [:yellow],
|
||||
doc_inline_code: [:cyan],
|
||||
doc_table_heading: [:reverse],
|
||||
doc_title: [:reverse, :yellow],
|
||||
@@ -53,10 +55,50 @@ defmodule IO.ANSI.Docs do
|
||||
newline_after_block()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Prints documentation metadata (only `delegate_to`, `deprecated`, `guard`, and `since` for now).
|
||||
|
||||
See `default_options/0` for docs on the supported options.
|
||||
"""
|
||||
@spec print_metadata(map, keyword) :: :ok
|
||||
def print_metadata(metadata, options \\ []) when is_map(metadata) do
|
||||
options = Keyword.merge(default_options(), options)
|
||||
print_each_metadata(metadata, options) && IO.write("\n")
|
||||
end
|
||||
|
||||
@metadata_filter [:deprecated, :guard, :since]
|
||||
|
||||
defp print_each_metadata(metadata, options) do
|
||||
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)
|
||||
|
||||
{key, value}, _printed when is_boolean(value) and key in @metadata_filter ->
|
||||
IO.puts([metadata_label(key, options), ' ', to_string(value)])
|
||||
|
||||
{:delegate_to, {m, f, a}}, _printed ->
|
||||
label = metadata_label(:delegate_to, options)
|
||||
IO.puts([label, ' ', Exception.format_mfa(m, f, a)])
|
||||
|
||||
_metadata, printed ->
|
||||
printed
|
||||
end)
|
||||
end
|
||||
|
||||
defp metadata_label(key, options) do
|
||||
if options[:enabled] do
|
||||
"#{color(:doc_metadata, options)}#{key}:#{IO.ANSI.reset()}"
|
||||
else
|
||||
"#{key}:"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Prints the documentation body.
|
||||
|
||||
In addition to the printing string, takes a set of options
|
||||
In addition to the printing string, takes a set of `options`
|
||||
defined in `default_options/0`.
|
||||
"""
|
||||
@spec print(String.t(), keyword) :: :ok
|
||||
@@ -482,7 +524,8 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp escape_underlines_in_link(text) do
|
||||
~r{https?\S*}
|
||||
# Regular expression adapted from https://tools.ietf.org/html/rfc3986#appendix-B
|
||||
~r{[a-z][a-z0-9\+\-\.]*://\S*}i
|
||||
|> Regex.recompile!()
|
||||
|> Regex.replace(text, &String.replace(&1, "_", "\\_"))
|
||||
end
|
||||
@@ -496,8 +539,9 @@ defmodule IO.ANSI.Docs do
|
||||
# We have four entries: **, *, _ and `.
|
||||
#
|
||||
# The first three behave the same while the last one is simpler
|
||||
# when it comes to delimiters. But, since the first has two
|
||||
# characters, we need to handle 3 cases:
|
||||
# when it comes to delimiters as it ignores spaces and escape
|
||||
# characters. But, since the first has two characters, we need to
|
||||
# handle 3 cases:
|
||||
#
|
||||
# 1. **
|
||||
# 2. _ and *
|
||||
@@ -559,8 +603,7 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
# An escape is not valid inside `
|
||||
defp handle_inline(<<?\\, mark, rest::binary>>, limit, buffer, acc, options)
|
||||
when not (mark == limit and mark == ?`) do
|
||||
defp handle_inline(<<?\\, mark, rest::binary>>, limit, buffer, acc, options) when limit != ?` do
|
||||
handle_inline(rest, limit, [mark | buffer], acc, options)
|
||||
end
|
||||
|
||||
|
||||
+294
-135
File diff suppressed because it is too large
Load Diff
@@ -162,7 +162,7 @@ defmodule Kernel.LexicalTracker do
|
||||
end
|
||||
|
||||
def handle_cast({:remote_struct, module, line}, state) do
|
||||
state = add_remote_dispatch(state, module, {:__struct__, 1}, line, :compile)
|
||||
state = add_remote_dispatch(state, module, {:__struct__, 0}, line, :compile)
|
||||
structs = :maps.put(module, true, state.structs)
|
||||
{:noreply, %{state | structs: structs}}
|
||||
end
|
||||
|
||||
@@ -45,7 +45,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
It returns `{:ok, modules, warnings}` or `{:error, errors, warnings}`.
|
||||
|
||||
Both errors and warnings are a list of three element tuples containing
|
||||
Both errors and warnings are a list of three-element tuples containing
|
||||
the file, line and the formatted error/warning.
|
||||
|
||||
## Options
|
||||
@@ -90,7 +90,7 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
It returns `{:ok, modules, warnings}` or `{:error, errors, warnings}`.
|
||||
|
||||
Both errors and warnings are a list of three element tuples containing
|
||||
Both errors and warnings are a list of three-element tuples containing
|
||||
the file, line and the formatted error/warning.
|
||||
|
||||
## Options
|
||||
@@ -107,8 +107,9 @@ defmodule Kernel.ParallelCompiler do
|
||||
spawn_workers(files, :require, options)
|
||||
end
|
||||
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
# TODO: Remove on 2.0
|
||||
@doc false
|
||||
@deprecated "Use Kernel.ParallelCompiler.compile/2 instead"
|
||||
def files(files, options \\ []) when is_list(options) do
|
||||
case spawn_workers(files, :compile, options) do
|
||||
{:ok, modules, _} -> modules
|
||||
@@ -116,8 +117,9 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
end
|
||||
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
# TODO: Remove on 2.0
|
||||
@doc false
|
||||
@deprecated "Use Kernel.ParallelCompiler.compile_to_path/2 instead"
|
||||
def files_to_path(files, path, options \\ []) when is_binary(path) and is_list(options) do
|
||||
case spawn_workers(files, {:compile, path}, options) do
|
||||
{:ok, modules, _} -> modules
|
||||
@@ -250,14 +252,16 @@ defmodule Kernel.ParallelCompiler do
|
||||
when length(waiting) == length(queued) do
|
||||
# The goal of this function is to find leaves in the dependency graph,
|
||||
# i.e. to find code that depends on code that we know is not being defined.
|
||||
without_definition =
|
||||
for {pid, _, _, _} <- queued,
|
||||
entry = waiting_on_without_definition(waiting, pid),
|
||||
do: entry
|
||||
|
||||
# Note we only release modules because those can be rescued. A missing
|
||||
# struct is a guaranteed compile error, so we never release it and treat
|
||||
# it exclusively a missing entry/deadlock.
|
||||
pending =
|
||||
for {pid, _, _, _} <- queued,
|
||||
entry = waiting_on_without_definition(waiting, pid),
|
||||
{kind, _, ref, on, _} = entry,
|
||||
kind == :module,
|
||||
for {:module, _, ref, on, _} <- without_definition,
|
||||
do: {on, {ref, :not_found}}
|
||||
|
||||
# Instead of releasing all files at once, we release them in groups
|
||||
@@ -277,8 +281,16 @@ defmodule Kernel.ParallelCompiler do
|
||||
spawn_workers(refs, waiting, queued, result, warnings, state)
|
||||
|
||||
[] ->
|
||||
errors = handle_deadlock(waiting, queued)
|
||||
{:error, errors, warnings}
|
||||
# There is a deadlock. Instead of printing a deadlock, let's release
|
||||
# structs, as a missing struct error is clearer than a deadlock one.
|
||||
structs = for {:struct, _, ref, _, _} <- without_definition, do: {ref, :not_found}
|
||||
|
||||
if structs != [] do
|
||||
spawn_workers(structs, waiting, queued, result, warnings, state)
|
||||
else
|
||||
errors = handle_deadlock(waiting, queued)
|
||||
{:error, errors, warnings}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -379,7 +391,11 @@ defmodule Kernel.ParallelCompiler do
|
||||
discard_down(child_pid)
|
||||
print_error(file, kind, reason, stack)
|
||||
cancel_waiting_timer(queued, child_pid)
|
||||
terminate(queued)
|
||||
|
||||
queued
|
||||
|> List.keydelete(child_pid, 0)
|
||||
|> terminate()
|
||||
|
||||
{:error, [to_error(file, kind, reason, stack)], warnings}
|
||||
|
||||
{:DOWN, ref, :process, _pid, reason} ->
|
||||
@@ -402,9 +418,13 @@ defmodule Kernel.ParallelCompiler do
|
||||
|
||||
defp handle_down(queued, ref, reason) do
|
||||
case List.keyfind(queued, ref, 1) do
|
||||
{_child, ^ref, file, _timer_ref} ->
|
||||
{child_pid, ^ref, file, _timer_ref} ->
|
||||
print_error(file, :exit, reason, [])
|
||||
terminate(queued)
|
||||
|
||||
queued
|
||||
|> List.keydelete(child_pid, 0)
|
||||
|> terminate()
|
||||
|
||||
{:error, [to_error(file, :exit, reason, [])]}
|
||||
|
||||
_ ->
|
||||
@@ -450,9 +470,9 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
|
||||
defp terminate(queued) do
|
||||
for {pid, _, _, _} <- queued do
|
||||
Process.exit(pid, :kill)
|
||||
end
|
||||
for {pid, _, _, _} <- queued, do: Process.exit(pid, :kill)
|
||||
for {pid, _, _, _} <- queued, do: discard_down(pid)
|
||||
:ok
|
||||
end
|
||||
|
||||
defp print_error(file, kind, reason, stack) do
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
defmodule Kernel.ParallelRequire do
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
# TODO: Remove on 2.0
|
||||
@moduledoc false
|
||||
|
||||
@deprecated "Use Kernel.ParallelCompiler.require/2 instead"
|
||||
def files(files, callbacks \\ [])
|
||||
|
||||
def files(files, callback) when is_function(callback, 1) do
|
||||
|
||||
@@ -4,7 +4,7 @@ defmodule Kernel.SpecialForms do
|
||||
cannot be overridden by the developer.
|
||||
|
||||
We define them in this module. Some of these forms are lexical (like
|
||||
`alias/2`, `case/2`, etc). The macros `{}/1` and `<<>>/1` are also special
|
||||
`alias/2`, `case/2`, etc.). The macros `{}/1` and `<<>>/1` are also special
|
||||
forms used to define tuple and binary data structures respectively.
|
||||
|
||||
This module also documents macros that return information about Elixir's
|
||||
@@ -239,6 +239,24 @@ defmodule Kernel.SpecialForms do
|
||||
iex> {name, species}
|
||||
{"Frank", "Walrus"}
|
||||
|
||||
The size can be a variable:
|
||||
|
||||
iex> name_size = 5
|
||||
iex> <<name::binary-size(name_size), " the ", species::binary>> = <<"Frank the Walrus">>
|
||||
iex> {name, species}
|
||||
{"Frank", "Walrus"}
|
||||
|
||||
And the variable can be defined in the match itself (prior to its use):
|
||||
|
||||
iex> <<name_size::size(8), name::binary-size(name_size), " the ", species::binary>> = <<5, "Frank the Walrus">>
|
||||
iex> {name, species}
|
||||
{"Frank", "Walrus"}
|
||||
|
||||
However, the size cannot be defined in the match outside the binary/bitstring match:
|
||||
|
||||
{name_size, <<name::binary-size(name_size), _rest::binary>>} = {5, <<"Frank the Walrus">>}
|
||||
** (CompileError): undefined variable "name_size" in bitstring segment
|
||||
|
||||
Failing to specify the size for the non-last causes compilation to fail:
|
||||
|
||||
<<name::binary, " the ", species::binary>> = <<"Frank the Walrus">>
|
||||
@@ -373,7 +391,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
## Syntax
|
||||
|
||||
The right side of `.` may be a word starting in upcase, which represents
|
||||
The right side of `.` may be a word starting with an uppercase letter, which represents
|
||||
an alias, a word starting with lowercase or underscore, any valid language
|
||||
operator or any name wrapped in single- or double-quotes. Those are all valid
|
||||
examples:
|
||||
@@ -390,7 +408,7 @@ defmodule Kernel.SpecialForms do
|
||||
iex> Kernel."+"(1, 2)
|
||||
3
|
||||
|
||||
Note that wrapping the function name in single- or double-quotes is always a
|
||||
Wrapping the function name in single- or double-quotes is always a
|
||||
remote call. Therefore `Kernel."Foo"` will attempt to call the function "Foo"
|
||||
and not return the alias `Kernel.Foo`. This is done by design as module names
|
||||
are more strict than function names.
|
||||
@@ -488,7 +506,7 @@ defmodule Kernel.SpecialForms do
|
||||
Keyword.values #=> uses MyKeyword.values
|
||||
Elixir.Keyword.values #=> uses Keyword.values
|
||||
|
||||
Notice that calling `alias` without the `as:` option automatically
|
||||
Notice that calling `alias` without the `:as` option automatically
|
||||
sets an alias based on the last part of the module. For example:
|
||||
|
||||
alias Foo.Bar.Baz
|
||||
@@ -548,7 +566,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
## Alias shortcut
|
||||
|
||||
`require/2` also accepts `as:` as an option so it automatically sets
|
||||
`require/2` also accepts `:as` as an option so it automatically sets
|
||||
up an alias. Please check `alias/2` for more information.
|
||||
|
||||
"""
|
||||
@@ -687,10 +705,13 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro __CALLER__, do: error!([])
|
||||
|
||||
@doc """
|
||||
Returns the stacktrace for the curently handled exception.
|
||||
Returns the stacktrace for the currently handled exception.
|
||||
|
||||
It is available only in the `catch` and `rescue` clauses of `try/1`
|
||||
expressions.
|
||||
|
||||
To retrieve the stacktrace of the current process, use
|
||||
`Process.info(self(), :current_stacktrace)` instead.
|
||||
"""
|
||||
defmacro __STACKTRACE__, do: error!([])
|
||||
|
||||
@@ -762,7 +783,7 @@ defmodule Kernel.SpecialForms do
|
||||
...> end
|
||||
{:sum, [], [1, 2, 3]}
|
||||
|
||||
## Explanation
|
||||
## Elixir's AST (Abstract Syntax Tree)
|
||||
|
||||
Any Elixir code can be represented using Elixir data structures.
|
||||
The building block of Elixir macros is a tuple with three elements,
|
||||
@@ -782,10 +803,35 @@ defmodule Kernel.SpecialForms do
|
||||
function call. The third argument may be an atom, which is
|
||||
usually a variable (or a local call).
|
||||
|
||||
Besides the tuple described above, Elixir has a few literals that
|
||||
are also part of its AST. Those literals return themselves when
|
||||
quoted. They are:
|
||||
|
||||
:sum #=> Atoms
|
||||
1 #=> Integers
|
||||
2.0 #=> Floats
|
||||
[1, 2] #=> Lists
|
||||
"strings" #=> Strings
|
||||
{key, value} #=> Tuples with two elements
|
||||
|
||||
Any other value, such as a map or a four-element tuple, must be escaped
|
||||
(`Macro.escape/1`) before being introduced into an AST.
|
||||
|
||||
## Options
|
||||
|
||||
* `:unquote` - when `false`, disables unquoting. Useful when you have a quote
|
||||
inside another quote and want to control what quote is able to unquote.
|
||||
* `:unquote` - when `false`, disables unquoting. This means any `unquote`
|
||||
call will be kept as is in the AST, instead of replaced by the `unquote`
|
||||
arguments. For example:
|
||||
|
||||
iex> quote do
|
||||
...> unquote("hello")
|
||||
...> end
|
||||
"hello"
|
||||
|
||||
iex> quote unquote: false do
|
||||
...> unquote("hello")
|
||||
...> end
|
||||
{:unquote, [], ["hello"]}
|
||||
|
||||
* `:location` - when set to `:keep`, keeps the current line and file from
|
||||
quote. Read the Stacktrace information section below for more
|
||||
@@ -802,22 +848,10 @@ defmodule Kernel.SpecialForms do
|
||||
* `:bind_quoted` - passes a binding to the macro. Whenever a binding is
|
||||
given, `unquote/1` is automatically disabled.
|
||||
|
||||
## Quote literals
|
||||
|
||||
Besides the tuple described above, Elixir has a few literals that
|
||||
when quoted return themselves. They are:
|
||||
|
||||
:sum #=> Atoms
|
||||
1 #=> Integers
|
||||
2.0 #=> Floats
|
||||
[1, 2] #=> Lists
|
||||
"strings" #=> Strings
|
||||
{key, value} #=> Tuples with two elements
|
||||
|
||||
## Quote and macros
|
||||
|
||||
`quote/2` is commonly used with macros for code generation. As an exercise,
|
||||
let's define a macro that multiplies a number by itself (squared). Note
|
||||
let's define a macro that multiplies a number by itself (squared). In practice,
|
||||
there is no reason to define such as a macro (and it would actually be
|
||||
seen as a bad practice), but it is simple enough that it allows us to focus
|
||||
on the important aspects of quotes and macros:
|
||||
@@ -956,8 +990,8 @@ defmodule Kernel.SpecialForms do
|
||||
NoHygiene.interference
|
||||
a #=> 1
|
||||
|
||||
Note that you cannot even access variables defined in the same
|
||||
module unless you explicitly give it a context:
|
||||
You cannot even access variables defined in the same module unless
|
||||
you explicitly give it a context:
|
||||
|
||||
defmodule Hygiene do
|
||||
defmacro write do
|
||||
@@ -1155,7 +1189,7 @@ defmodule Kernel.SpecialForms do
|
||||
When using `location: :keep` and invalid arguments are given to
|
||||
`Sample.add/2`, the stacktrace information will point to the file
|
||||
and line inside the quote. Without `location: :keep`, the error is
|
||||
reported to where `defadd` was invoked. Note `location: :keep` affects
|
||||
reported to where `defadd` was invoked. `location: :keep` affects
|
||||
only definitions inside the quote.
|
||||
|
||||
## Binding and unquote fragments
|
||||
@@ -1234,37 +1268,61 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro quote(opts, block), do: error!([opts, block])
|
||||
|
||||
@doc """
|
||||
Unquotes the given expression from inside a macro.
|
||||
Unquotes the given expression inside a quoted expression.
|
||||
|
||||
This function expects a valid Elixir AST, also known as
|
||||
quoted expression, as argument. If you would like to `unquote`
|
||||
any value, such as a map or a four-element tuple, you should
|
||||
call `Macro.escape/1` before unquoting.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine the situation you have a variable `value` and
|
||||
Imagine the situation you have a quoted expression and
|
||||
you want to inject it inside some quote. The first attempt
|
||||
would be:
|
||||
|
||||
value = 13
|
||||
value =
|
||||
quote do
|
||||
13
|
||||
end
|
||||
|
||||
quote do
|
||||
sum(1, value, 3)
|
||||
end
|
||||
|
||||
Which would then return:
|
||||
|
||||
{:sum, [], [1, {:value, [], quoted}, 3]}
|
||||
{:sum, [], [1, {:value, [], Elixir}, 3]}
|
||||
|
||||
Which is not the expected result. For this, we use unquote:
|
||||
Which is not the expected result. For this, we use `unquote`:
|
||||
|
||||
iex> value = 13
|
||||
iex> value =
|
||||
...> quote do
|
||||
...> 13
|
||||
...> end
|
||||
iex> quote do
|
||||
...> sum(1, unquote(value), 3)
|
||||
...> end
|
||||
{:sum, [], [1, 13, 3]}
|
||||
|
||||
If you want to unquote a value that is not a quoted expression,
|
||||
such as a map, you need to call `Macro.escape/1` before:
|
||||
|
||||
iex> value = %{foo: :bar}
|
||||
iex> quote do
|
||||
...> process_map(unquote(Macro.escape(value)))
|
||||
...> end
|
||||
{:process_map, [], [{:%{}, [], [foo: :bar]}]}
|
||||
|
||||
If you forget to escape it, Elixir will raise an error
|
||||
when compiling the code.
|
||||
"""
|
||||
defmacro unquote(:unquote)(expr), do: error!([expr])
|
||||
|
||||
@doc """
|
||||
Unquotes the given list expanding its arguments. Similar
|
||||
to `unquote/1`.
|
||||
Unquotes the given list expanding its arguments.
|
||||
|
||||
Similar to `unquote/1`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1303,7 +1361,7 @@ defmodule Kernel.SpecialForms do
|
||||
iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n
|
||||
[2, 4, 6]
|
||||
|
||||
Note generators can also be used to filter as it removes any value
|
||||
Generators can also be used to filter as it removes any value
|
||||
that doesn't match the pattern on the left side of `<-`:
|
||||
|
||||
iex> users = [user: "john", admin: "meg", guest: "barbara"]
|
||||
@@ -1323,7 +1381,7 @@ defmodule Kernel.SpecialForms do
|
||||
filters or inside the block, are not reflected outside of the
|
||||
comprehension.
|
||||
|
||||
## Into
|
||||
## The `:into` and `:uniq` options
|
||||
|
||||
In the examples above, the result returned by the comprehension was
|
||||
always a list. The returned result can be configured by passing an
|
||||
@@ -1343,18 +1401,57 @@ defmodule Kernel.SpecialForms do
|
||||
String.upcase(line)
|
||||
end
|
||||
|
||||
## Uniq
|
||||
|
||||
`uniq: true` can also be given to comprehensions to guarantee that
|
||||
that results are only added to the collection if they were not returned
|
||||
Similarly, `uniq: true` can also be given to comprehensions to guarantee
|
||||
the results are only added to the collection if they were not returned
|
||||
before. For example:
|
||||
|
||||
iex> for(x <- [1, 1, 2, 3], uniq: true, do: x * 2)
|
||||
iex> for x <- [1, 1, 2, 3], uniq: true, do: x * 2
|
||||
[2, 4, 6]
|
||||
|
||||
iex> for(<<x <- "abcabc">>, uniq: true, into: "", do: <<x - 32>>)
|
||||
iex> for <<x <- "abcabc">>, uniq: true, into: "", do: <<x - 32>>
|
||||
"ABC"
|
||||
|
||||
## The `:reduce` option
|
||||
|
||||
While the `:into` option allows us to customize the comprehension behaviour
|
||||
to a given data type, such as putting all of the values inside a map or inside
|
||||
a binary, it is not always enough.
|
||||
|
||||
For example, imagine that you have a binary with letters where you want to
|
||||
count how many times each lowercase letter happens, ignoring all uppercase
|
||||
ones. For instance, for the string `"AbCabCABc"`, we want to return the map
|
||||
`%{"a" => 1, "b" => 2, "c" => 1}`.
|
||||
|
||||
If we were to use `:into`, we would need a data type that computes the
|
||||
frequency of each element it holds. While there is no such data type in
|
||||
Elixir, you could implement one yourself.
|
||||
|
||||
A simpler option would be to use comprehensions for the mapping and
|
||||
filtering of letters, and then we invoke `Enum.reduce/3` to build a map,
|
||||
for example:
|
||||
|
||||
iex> letters = for <<x <- "AbCabCABc">>, x in ?a..?z, do: <<x>>
|
||||
iex> Enum.reduce(letters, %{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
|
||||
%{"a" => 1, "b" => 2, "c" => 1}
|
||||
|
||||
While the above is straight-forward, it has the downside of traversing the
|
||||
data at least twice. If you are expecting long strings as inputs, this can
|
||||
be quite expensive.
|
||||
|
||||
Luckily, comprehensions also support the `:reduce` option, which would allow
|
||||
us to fuse both steps above into a single step:
|
||||
|
||||
iex> for <<x <- "AbCabCABc">>, x in ?a..?z, reduce: %{} do
|
||||
...> acc -> Map.update(acc, <<x>>, 1, & &1 + 1)
|
||||
...> end
|
||||
%{"a" => 1, "b" => 2, "c" => 1}
|
||||
|
||||
When the `:reduce` key is given, its value is used as the initial accumulator
|
||||
and the `do` block must be changed to use `->` clauses, where the left side
|
||||
of `->` receives the accumulated value of the previous iteration and the
|
||||
expression on the right side must return the new accumulator value. Once there are no more
|
||||
elements, the final accumulated value is returned. If there are no elements
|
||||
at all, then the initial accumulator value is returned.
|
||||
"""
|
||||
defmacro for(args), do: error!([args])
|
||||
|
||||
@@ -1388,8 +1485,9 @@ defmodule Kernel.SpecialForms do
|
||||
...> end
|
||||
{:ok, "admin"}
|
||||
|
||||
As in `for/1`, variables bound inside `with/1` won't leak;
|
||||
"bare expressions" may also be inserted between the clauses:
|
||||
As in `for/1`, variables bound inside `with/1` won't leak.
|
||||
Expressions without `<-` may also be used in clauses. For instance,
|
||||
you can perform regular matches with the `=` operator:
|
||||
|
||||
iex> width = nil
|
||||
iex> opts = %{width: 10, height: 15}
|
||||
@@ -1402,8 +1500,9 @@ defmodule Kernel.SpecialForms do
|
||||
iex> width
|
||||
nil
|
||||
|
||||
Note that if a "bare expression" fails to match, it will raise a `MatchError`
|
||||
instead of returning the non-matched value:
|
||||
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
|
||||
@@ -1435,7 +1534,8 @@ defmodule Kernel.SpecialForms do
|
||||
...> end
|
||||
{:error, :wrong_data}
|
||||
|
||||
If there is no matching `else` condition, then a `WithClauseError` exception is raised.
|
||||
If an `else` block is used and there are no matching clauses, a `WithClauseError`
|
||||
exception is raised.
|
||||
"""
|
||||
defmacro with(args), do: error!([args])
|
||||
|
||||
@@ -1724,10 +1824,9 @@ defmodule Kernel.SpecialForms do
|
||||
the expression. `catch`, `rescue`, and `else` clauses work based on
|
||||
pattern matching (similar to the `case` special form).
|
||||
|
||||
Note that calls inside `try/1` are not tail recursive since the VM
|
||||
needs to keep the stacktrace in case an exception happens. To
|
||||
retrieve the stacktrace, access `__STACKTRACE__/0` inside the `rescue`
|
||||
or `catch` clause.
|
||||
Calls inside `try/1` are not tail recursive since the VM needs to keep
|
||||
the stacktrace in case an exception happens. To retrieve the stacktrace,
|
||||
access `__STACKTRACE__/0` inside the `rescue` or `catch` clause.
|
||||
|
||||
## `rescue` clauses
|
||||
|
||||
|
||||
+461
-241
File diff suppressed because it is too large
Load Diff
@@ -157,7 +157,7 @@ defmodule Kernel.Utils do
|
||||
macro.
|
||||
|
||||
Secondly, if the expression is being used outside of a guard, we want to unquote
|
||||
`value`––but only once, and then re-use the unquoted form throughout the expression.
|
||||
`value`, but only once, and then re-use the unquoted form throughout the expression.
|
||||
|
||||
This helper does exactly that: takes the AST for an expression and a list of
|
||||
variable references it should be aware of, and rewrites it into a new expression
|
||||
@@ -170,14 +170,17 @@ defmodule Kernel.Utils do
|
||||
> variable_references = [value: Elixir]
|
||||
> Kernel.Utils.defguard(expression, variable_references) |> Macro.to_string |> IO.puts
|
||||
|
||||
case Macro.Env.in_guard? __CALLER__ do
|
||||
true -> quote do
|
||||
is_integer(unquote(value)) and rem(unquote(value), 2) == 0
|
||||
end
|
||||
false -> quote do
|
||||
value = unquote(value)
|
||||
is_integer(value) and rem(value, 2) == 0
|
||||
end
|
||||
case Macro.Env.in_guard?(__CALLER__) do
|
||||
true ->
|
||||
quote do
|
||||
is_integer(unquote(value)) and rem(unquote(value), 2) == 0
|
||||
end
|
||||
|
||||
false ->
|
||||
quote do
|
||||
value = unquote(value)
|
||||
is_integer(value) and rem(value, 2) == 0
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -225,25 +228,36 @@ defmodule Kernel.Utils do
|
||||
|
||||
# Prefaces `guard` with unquoted versions of `refs`.
|
||||
defp unquote_refs_once(guard, refs) do
|
||||
{_, used_refs} =
|
||||
Macro.postwalk(guard, [], fn
|
||||
{guard, used_refs} =
|
||||
Macro.postwalk(guard, %{}, fn
|
||||
{ref, meta, context} = var, acc when is_atom(ref) and is_atom(context) ->
|
||||
pair = {ref, var_context(meta, context)}
|
||||
|
||||
case pair in refs and pair not in acc do
|
||||
true -> {var, [pair | acc]}
|
||||
false -> {var, acc}
|
||||
case pair in refs do
|
||||
true ->
|
||||
case acc do
|
||||
%{^pair => {new_var, _}} ->
|
||||
{new_var, acc}
|
||||
|
||||
%{} ->
|
||||
generated = String.to_atom("arg" <> Integer.to_string(map_size(acc)))
|
||||
new_var = Macro.var(generated, Elixir)
|
||||
{new_var, Map.put(acc, pair, {new_var, var})}
|
||||
end
|
||||
|
||||
false ->
|
||||
{var, acc}
|
||||
end
|
||||
|
||||
node, acc ->
|
||||
{node, acc}
|
||||
end)
|
||||
|
||||
vars = for {ref, context} <- :lists.reverse(used_refs), do: context_to_var(ref, context)
|
||||
exprs = for var <- vars, do: literal_unquote(var)
|
||||
all_used = for ref <- :lists.reverse(refs), used = :maps.get(ref, used_refs, nil), do: used
|
||||
{vars, exprs} = :lists.unzip(all_used)
|
||||
|
||||
quote do
|
||||
{unquote_splicing(vars)} = {unquote_splicing(exprs)}
|
||||
{unquote_splicing(vars)} = {unquote_splicing(Enum.map(exprs, &literal_unquote/1))}
|
||||
unquote(guard)
|
||||
end
|
||||
end
|
||||
@@ -256,9 +270,6 @@ defmodule Kernel.Utils do
|
||||
{:unquote, [], List.wrap(ast)}
|
||||
end
|
||||
|
||||
defp context_to_var(ref, ctx) when is_atom(ctx), do: {ref, [], ctx}
|
||||
defp context_to_var(ref, ctx) when is_integer(ctx), do: {ref, [counter: ctx], nil}
|
||||
|
||||
defp var_context(meta, kind) do
|
||||
case :lists.keyfind(:counter, 1, meta) do
|
||||
{:counter, counter} -> counter
|
||||
|
||||
+25
-22
@@ -20,15 +20,18 @@ defmodule Keyword do
|
||||
iex> [{:active, :once}]
|
||||
[active: :once]
|
||||
|
||||
The two syntaxes are completely equivalent. If the keyword has foreign
|
||||
characters, such as spaces, you can wrap it in quotes:
|
||||
The two syntaxes are completely equivalent. Like atoms, keywords
|
||||
must be composed of Unicode characters such as letters, numbers,
|
||||
underscore, and `@`. If the keyword has a character that does not
|
||||
belong to the category above, such as spaces, you can wrap it in
|
||||
quotes:
|
||||
|
||||
iex> ["exit on close": true]
|
||||
["exit on close": true]
|
||||
|
||||
Wrapping a keyword in quotes does not make it a string. Keywords are
|
||||
always atoms and quotes should only be used to handle foreign characters.
|
||||
In fact, if you attempt use quotes when not necessary, Elixir will warn.
|
||||
always atoms. If you use quotes when all characters are a valid part
|
||||
of a keyword without quotes, Elixir will warn.
|
||||
|
||||
Note that when keyword lists are passed as the last argument to a function,
|
||||
if the short-hand syntax is used then the square brackets around the keyword list
|
||||
@@ -81,7 +84,7 @@ defmodule Keyword do
|
||||
|
||||
iex> Keyword.keyword?([])
|
||||
true
|
||||
iex> Keyword.keyword?([a: 1])
|
||||
iex> Keyword.keyword?(a: 1)
|
||||
true
|
||||
iex> Keyword.keyword?([{Foo, 1}])
|
||||
true
|
||||
@@ -319,7 +322,7 @@ defmodule Keyword do
|
||||
{1, []}
|
||||
|
||||
"""
|
||||
@spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} | no_return when get: term
|
||||
@spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} when get: term
|
||||
def get_and_update!(keywords, key, fun) do
|
||||
get_and_update!(keywords, key, fun, [])
|
||||
end
|
||||
@@ -379,7 +382,7 @@ defmodule Keyword do
|
||||
** (KeyError) key :b not found in: [a: 1]
|
||||
|
||||
"""
|
||||
@spec fetch!(t, key) :: value | no_return
|
||||
@spec fetch!(t, key) :: value
|
||||
def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do
|
||||
case :lists.keyfind(key, 1, keywords) do
|
||||
{^key, value} -> value
|
||||
@@ -417,9 +420,9 @@ defmodule Keyword do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.keys([a: 1, b: 2])
|
||||
iex> Keyword.keys(a: 1, b: 2)
|
||||
[:a, :b]
|
||||
iex> Keyword.keys([a: 1, b: 2, a: 3])
|
||||
iex> Keyword.keys(a: 1, b: 2, a: 3)
|
||||
[:a, :b, :a]
|
||||
|
||||
"""
|
||||
@@ -435,9 +438,9 @@ defmodule Keyword do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.values([a: 1, b: 2])
|
||||
iex> Keyword.values(a: 1, b: 2)
|
||||
[1, 2]
|
||||
iex> Keyword.values([a: 1, b: 2, a: 3])
|
||||
iex> Keyword.values(a: 1, b: 2, a: 3)
|
||||
[1, 2, 3]
|
||||
|
||||
"""
|
||||
@@ -701,8 +704,8 @@ defmodule Keyword do
|
||||
@spec merge(t, t) :: t
|
||||
def merge(keywords1, keywords2)
|
||||
|
||||
def merge(keywords1, []), do: keywords1
|
||||
def merge([], keywords2), do: keywords2
|
||||
def merge(keywords1, []) when is_list(keywords1), do: keywords1
|
||||
def merge([], keywords2) when is_list(keywords2), do: keywords2
|
||||
|
||||
def merge(keywords1, keywords2) when is_list(keywords1) and is_list(keywords2) do
|
||||
if keyword?(keywords2) do
|
||||
@@ -712,13 +715,13 @@ defmodule Keyword do
|
||||
|
||||
_ ->
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the first argument, got: #{inspect(keywords1)}"
|
||||
"expected a keyword list as the first argument, got: #{inspect(keywords1)}"
|
||||
end
|
||||
|
||||
:lists.filter(fun, keywords1) ++ keywords2
|
||||
else
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the second argument, got: #{inspect(keywords2)}"
|
||||
"expected a keyword list as the second argument, got: #{inspect(keywords2)}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -741,17 +744,17 @@ defmodule Keyword do
|
||||
[b: 2, a: 4, d: 4]
|
||||
|
||||
iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->
|
||||
...> v1 + v2
|
||||
...> v1 + v2
|
||||
...> end)
|
||||
[b: 2, a: 4, d: 4, a: 5]
|
||||
|
||||
iex> Keyword.merge([a: 1, b: 2, a: 3], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->
|
||||
...> v1 + v2
|
||||
...> v1 + v2
|
||||
...> end)
|
||||
[b: 2, a: 4, d: 4, a: 8]
|
||||
|
||||
iex> Keyword.merge([a: 1, b: 2], [:a, :b], fn :a, v1, v2 ->
|
||||
...> v1 + v2
|
||||
...> v1 + v2
|
||||
...> end)
|
||||
** (ArgumentError) expected a keyword list as the second argument, got: [:a, :b]
|
||||
|
||||
@@ -763,7 +766,7 @@ defmodule Keyword do
|
||||
do_merge(keywords2, [], keywords1, keywords1, fun, keywords2)
|
||||
else
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the first argument, got: #{inspect(keywords1)}"
|
||||
"expected a keyword list as the first argument, got: #{inspect(keywords1)}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -785,7 +788,7 @@ defmodule Keyword do
|
||||
|
||||
defp do_merge(_other, _acc, _rest, _original, _fun, keywords2) do
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the second argument, got: #{inspect(keywords2)}"
|
||||
"expected a keyword list as the second argument, got: #{inspect(keywords2)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -823,7 +826,7 @@ defmodule Keyword do
|
||||
** (KeyError) key :b not found in: [a: 1]
|
||||
|
||||
"""
|
||||
@spec update!(t, key, (value -> value)) :: t | no_return
|
||||
@spec update!(t, key, (value -> value)) :: t
|
||||
def update!(keywords, key, fun) do
|
||||
update!(keywords, key, fun, keywords)
|
||||
end
|
||||
@@ -1035,7 +1038,7 @@ defmodule Keyword do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.to_list([a: 1])
|
||||
iex> Keyword.to_list(a: 1)
|
||||
[a: 1]
|
||||
|
||||
"""
|
||||
|
||||
+240
-88
@@ -63,7 +63,7 @@ defmodule List do
|
||||
iex> list ++ [4] # slow
|
||||
[1, 2, 3, 4]
|
||||
|
||||
Additonally, getting a list's length and accessing it by index are
|
||||
Additionally, getting a list's length and accessing it by index are
|
||||
linear time operations. Negative indexes are also supported but
|
||||
they imply the list will be iterated twice, once to calculate the
|
||||
proper index and another time to perform the operation.
|
||||
@@ -87,14 +87,16 @@ defmodule List do
|
||||
instead of Elixir strings. One example of such functions
|
||||
is `Application.loaded_applications/0`:
|
||||
|
||||
Application.loaded_applications
|
||||
#=> [{:stdlib, 'ERTS CXC 138 10', '2.6'},
|
||||
#=> {:compiler, 'ERTS CXC 138 10', '6.0.1'},
|
||||
#=> {:elixir, 'elixir', '1.0.0'},
|
||||
#=> {:kernel, 'ERTS CXC 138 10', '4.1'},
|
||||
#=> {:logger, 'logger', '1.0.0'}]
|
||||
Application.loaded_applications()
|
||||
#=> [
|
||||
#=> {:stdlib, 'ERTS CXC 138 10', '2.6'},
|
||||
#=> {:compiler, 'ERTS CXC 138 10', '6.0.1'},
|
||||
#=> {:elixir, 'elixir', '1.0.0'},
|
||||
#=> {:kernel, 'ERTS CXC 138 10', '4.1'},
|
||||
#=> {:logger, 'logger', '1.0.0'}
|
||||
#=> ]
|
||||
|
||||
A list can be checked if it is made of printable ascii
|
||||
A list can be checked if it is made of printable ASCII
|
||||
codepoints with `ascii_printable?/2`.
|
||||
"""
|
||||
|
||||
@@ -286,14 +288,17 @@ defmodule List do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives a list of tuples and replaces the item
|
||||
identified by `key` at `position` if it exists.
|
||||
Receives a list of tuples and if the identified item by `key` at `position`
|
||||
exists, it is replaced with `new_tuple`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.keyreplace([a: 1, b: 2], :a, 0, {:a, 3})
|
||||
[a: 3, b: 2]
|
||||
|
||||
iex> List.keyreplace([a: 1, b: 2], :a, 1, {:a, 3})
|
||||
[a: 1, b: 2]
|
||||
|
||||
"""
|
||||
@spec keyreplace([tuple], any, non_neg_integer, tuple) :: [tuple]
|
||||
def keyreplace(list, key, position, new_tuple) do
|
||||
@@ -320,7 +325,7 @@ defmodule List do
|
||||
|
||||
@doc """
|
||||
Receives a `list` of tuples and replaces the item
|
||||
identified by `key` at `position`.
|
||||
identified by `key` at `position` with `new_tuple`.
|
||||
|
||||
If the item does not exist, it is added to the end of the `list`.
|
||||
|
||||
@@ -443,14 +448,28 @@ defmodule List do
|
||||
do_zip(list_of_lists, [])
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if a list is a charlist made only of printable ASCII characters.
|
||||
|
||||
A printable charlist in Elixir contains only ASCII characters.
|
||||
@doc ~S"""
|
||||
Checks if `list` is a charlist made only of printable ASCII characters.
|
||||
|
||||
Takes an optional `limit` as a second argument. `ascii_printable?/2` only
|
||||
checks the printability of the list up to the `limit`.
|
||||
|
||||
A printable charlist in Elixir contains only the printable characters in the
|
||||
standard seven-bit ASCII character encoding, which are characters ranging from
|
||||
32 to 126 in decimal notation, plus the following control characters:
|
||||
|
||||
* `?\a` - Bell
|
||||
* `?\b` - Backspace
|
||||
* `?\t` - Horizontal tab
|
||||
* `?\n` - Line feed
|
||||
* `?\v` - Vertical tab
|
||||
* `?\f` - Form feed
|
||||
* `?\r` - Carriage return
|
||||
* `?\e` - Escape
|
||||
|
||||
For more information read the [Character groups](https://en.wikipedia.org/wiki/ASCII#Character_groups)
|
||||
section in the Wikipedia article of the [ASCII](https://en.wikipedia.org/wiki/ASCII) standard.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.ascii_printable?('abc')
|
||||
@@ -462,63 +481,85 @@ defmodule List do
|
||||
iex> List.ascii_printable?('abc' ++ [0], 2)
|
||||
true
|
||||
|
||||
Improper lists are not printable, even if made only of ascii characters:
|
||||
Improper lists are not printable, even if made only of ASCII characters:
|
||||
|
||||
iex> List.ascii_printable?('abc' ++ ?d)
|
||||
false
|
||||
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
def ascii_printable?(list, counter \\ :infinity)
|
||||
@spec ascii_printable?(list, limit) :: boolean
|
||||
when limit: :infinity | non_neg_integer
|
||||
def ascii_printable?(list, limit \\ :infinity)
|
||||
when is_list(list) and (limit == :infinity or (is_integer(limit) and limit >= 0)) do
|
||||
ascii_printable_guarded?(list, limit)
|
||||
end
|
||||
|
||||
def ascii_printable?(_, 0) do
|
||||
defp ascii_printable_guarded?(_, 0) do
|
||||
true
|
||||
end
|
||||
|
||||
def ascii_printable?([char | rest], counter)
|
||||
when is_integer(char) and char >= 32 and char <= 126 do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([char | rest], counter)
|
||||
when is_integer(char) and char >= 32 and char <= 126 do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\n | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\n | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\r | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\r | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\t | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\t | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\v | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\v | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\b | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\b | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\f | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\f | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\e | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\e | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\a | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
defp ascii_printable_guarded?([?\a | rest], counter) do
|
||||
ascii_printable_guarded?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([], _counter), do: true
|
||||
def ascii_printable?(_, _counter), do: false
|
||||
defp ascii_printable_guarded?([], _counter), do: true
|
||||
defp ascii_printable_guarded?(_, _counter), do: false
|
||||
|
||||
@compile {:inline, decrement: 1}
|
||||
defp decrement(:infinity), do: :infinity
|
||||
defp decrement(counter), do: counter - 1
|
||||
|
||||
@doc """
|
||||
Returns `true` if `list` is an improper list. Otherwise returns `false`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.improper?([1, 2 | 3])
|
||||
true
|
||||
|
||||
iex> List.improper?([1, 2, 3])
|
||||
false
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec improper?(maybe_improper_list) :: boolean
|
||||
def improper?(list) when is_list(list) and length(list) >= 0, do: false
|
||||
def improper?(list) when is_list(list), do: true
|
||||
|
||||
@doc """
|
||||
Returns a list with `value` inserted at the specified `index`.
|
||||
|
||||
@@ -541,11 +582,19 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec insert_at(list, integer, any) :: list
|
||||
def insert_at(list, index, value) when is_integer(index) do
|
||||
if index < 0 do
|
||||
do_insert_at(list, length(list) + index + 1, value)
|
||||
else
|
||||
do_insert_at(list, index, value)
|
||||
def insert_at(list, index, value) when is_list(list) and is_integer(index) do
|
||||
case index do
|
||||
-1 ->
|
||||
list ++ [value]
|
||||
|
||||
_ when index < 0 ->
|
||||
case length(list) + index + 1 do
|
||||
index when index < 0 -> [value | list]
|
||||
index -> do_insert_at(list, index, value)
|
||||
end
|
||||
|
||||
_ ->
|
||||
do_insert_at(list, index, value)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -571,9 +620,12 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec replace_at(list, integer, any) :: list
|
||||
def replace_at(list, index, value) when is_integer(index) do
|
||||
def replace_at(list, index, value) when is_list(list) and is_integer(index) do
|
||||
if index < 0 do
|
||||
do_replace_at(list, length(list) + index, value)
|
||||
case length(list) + index do
|
||||
index when index < 0 -> list
|
||||
index -> do_replace_at(list, index, value)
|
||||
end
|
||||
else
|
||||
do_replace_at(list, index, value)
|
||||
end
|
||||
@@ -601,9 +653,12 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec update_at([elem], integer, (elem -> any)) :: list when elem: var
|
||||
def update_at(list, index, fun) when is_function(fun, 1) and is_integer(index) do
|
||||
def update_at(list, index, fun) when is_list(list) and is_function(fun) and is_integer(index) do
|
||||
if index < 0 do
|
||||
do_update_at(list, length(list) + index, fun)
|
||||
case length(list) + index do
|
||||
index when index < 0 -> list
|
||||
index -> do_update_at(list, index, fun)
|
||||
end
|
||||
else
|
||||
do_update_at(list, index, fun)
|
||||
end
|
||||
@@ -693,15 +748,18 @@ defmodule List do
|
||||
@doc """
|
||||
Converts a charlist to an atom.
|
||||
|
||||
Currently Elixir does not support conversions from charlists
|
||||
which contains Unicode codepoints greater than 0xFF.
|
||||
Elixir supports conversions from charlists which contains any Unicode
|
||||
codepoint.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.to_atom('elixir')
|
||||
:elixir
|
||||
iex> List.to_atom('Elixir')
|
||||
:Elixir
|
||||
|
||||
iex> List.to_atom('🌢 Elixir')
|
||||
:"🌢 Elixir"
|
||||
|
||||
"""
|
||||
@spec to_atom(charlist) :: atom
|
||||
@@ -713,8 +771,8 @@ defmodule List do
|
||||
Converts a charlist to an existing atom. Raises an `ArgumentError`
|
||||
if the atom does not exist.
|
||||
|
||||
Currently Elixir does not support conversions from charlists
|
||||
which contains Unicode codepoints greater than 0xFF.
|
||||
Elixir supports conversions from charlists which contains any Unicode
|
||||
codepoint.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
@@ -724,6 +782,10 @@ defmodule List do
|
||||
iex> List.to_existing_atom('my_atom')
|
||||
:my_atom
|
||||
|
||||
iex> _ = :"🌢 Elixir"
|
||||
iex> List.to_existing_atom('🌢 Elixir')
|
||||
:"🌢 Elixir"
|
||||
|
||||
iex> List.to_existing_atom('this_atom_will_never_exist')
|
||||
** (ArgumentError) argument error
|
||||
|
||||
@@ -848,6 +910,58 @@ defmodule List do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a list of integers representing codepoints, lists or
|
||||
strings into a charlist.
|
||||
|
||||
Notice that this function expects a list of integers representing
|
||||
UTF-8 codepoints. If you have a list of bytes, you must instead use
|
||||
the [`:binary` module](http://www.erlang.org/doc/man/binary.html).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.to_charlist([0x00E6, 0x00DF])
|
||||
'æß'
|
||||
|
||||
iex> List.to_charlist([0x0061, "bc"])
|
||||
'abc'
|
||||
|
||||
iex> List.to_charlist([0x0064, "ee", ['p']])
|
||||
'deep'
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec to_charlist(:unicode.charlist()) :: charlist()
|
||||
def to_charlist(list) when is_list(list) do
|
||||
try do
|
||||
:unicode.characters_to_list(list)
|
||||
rescue
|
||||
ArgumentError ->
|
||||
raise ArgumentError, """
|
||||
cannot convert the given list to a charlist.
|
||||
|
||||
To be converted to a charlist, a list must contain only:
|
||||
|
||||
* strings
|
||||
* integers representing Unicode codepoints
|
||||
* or a list containing one of these three elements
|
||||
|
||||
Please check the given list or call inspect/1 to get the list representation, got:
|
||||
|
||||
#{inspect(list)}
|
||||
"""
|
||||
else
|
||||
result when is_list(result) ->
|
||||
result
|
||||
|
||||
{:error, encoded, rest} ->
|
||||
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :invalid
|
||||
|
||||
{:incomplete, encoded, rest} ->
|
||||
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :incomplete
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a keyword list that represents an *edit script*.
|
||||
|
||||
@@ -861,6 +975,8 @@ defmodule List do
|
||||
corresponding key is `:del`), or left alone (if the corresponding key is
|
||||
`:eq`) in `list1` in order to be closer to `list2`.
|
||||
|
||||
See `myers_difference/3` if you want to handle nesting in the diff scripts.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.myers_difference([1, 4, 2, 3], [1, 2, 3, 4])
|
||||
@@ -870,19 +986,49 @@ defmodule List do
|
||||
@doc since: "1.4.0"
|
||||
@spec myers_difference(list, list) :: [{:eq | :ins | :del, list}]
|
||||
def myers_difference(list1, list2) when is_list(list1) and is_list(list2) do
|
||||
path = {0, list1, list2, []}
|
||||
find_script(0, length(list1) + length(list2), [path])
|
||||
myers_difference_with_diff_script(list1, list2, nil)
|
||||
end
|
||||
|
||||
defp find_script(envelope, max, paths) do
|
||||
case each_diagonal(-envelope, envelope, paths, []) do
|
||||
@doc """
|
||||
Returns a keyword list that represents an *edit script* with nested diffs.
|
||||
|
||||
This is an extension of `myers_difference/2` where a `diff_script` function
|
||||
can be given in case it is desired to compute nested differences. The function
|
||||
may return a list with the inner edit script or `nil` in case there is no
|
||||
such script. The returned inner edit script will be under the `:diff` key.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.myers_difference(["a", "db", "c"], ["a", "bc"], &String.myers_difference/2)
|
||||
[eq: ["a"], diff: [del: "d", eq: "b", ins: "c"], del: ["c"]]
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec myers_difference(list, list, (term, term -> script | nil)) :: script
|
||||
when script: [{:eq | :ins | :del | :diff, list}]
|
||||
def myers_difference(list1, list2, diff_script)
|
||||
when is_list(list1) and is_list(list2) and is_function(diff_script) do
|
||||
myers_difference_with_diff_script(list1, list2, diff_script)
|
||||
end
|
||||
|
||||
defp myers_difference_with_diff_script(list1, list2, diff_script) do
|
||||
path = {0, list1, list2, []}
|
||||
find_script(0, length(list1) + length(list2), [path], diff_script)
|
||||
end
|
||||
|
||||
defp find_script(envelope, max, paths, diff_script) do
|
||||
case each_diagonal(-envelope, envelope, paths, [], diff_script) do
|
||||
{:done, edits} -> compact_reverse(edits, [])
|
||||
{:next, paths} -> find_script(envelope + 1, max, paths)
|
||||
{:next, paths} -> find_script(envelope + 1, max, paths, diff_script)
|
||||
end
|
||||
end
|
||||
|
||||
defp compact_reverse([], acc), do: acc
|
||||
|
||||
defp compact_reverse([{:diff, _} = fragment | rest], acc) do
|
||||
compact_reverse(rest, [fragment | acc])
|
||||
end
|
||||
|
||||
defp compact_reverse([{kind, elem} | rest], [{kind, result} | acc]) do
|
||||
compact_reverse(rest, [{kind, [elem | result]} | acc])
|
||||
end
|
||||
@@ -895,50 +1041,68 @@ defmodule List do
|
||||
compact_reverse(rest, [{kind, [elem]} | acc])
|
||||
end
|
||||
|
||||
defp each_diagonal(diag, limit, _paths, next_paths) when diag > limit do
|
||||
defp each_diagonal(diag, limit, _paths, next_paths, _diff_script) when diag > limit do
|
||||
{:next, :lists.reverse(next_paths)}
|
||||
end
|
||||
|
||||
defp each_diagonal(diag, limit, paths, next_paths) do
|
||||
{path, rest} = proceed_path(diag, limit, paths)
|
||||
defp each_diagonal(diag, limit, paths, next_paths, diff_script) do
|
||||
{path, rest} = proceed_path(diag, limit, paths, diff_script)
|
||||
|
||||
case follow_snake(path) do
|
||||
{:cont, path} -> each_diagonal(diag + 2, limit, rest, [path | next_paths])
|
||||
{:cont, path} -> each_diagonal(diag + 2, limit, rest, [path | next_paths], diff_script)
|
||||
{:done, edits} -> {:done, edits}
|
||||
end
|
||||
end
|
||||
|
||||
defp proceed_path(0, 0, [path]), do: {path, []}
|
||||
defp proceed_path(0, 0, [path], _diff_script), do: {path, []}
|
||||
|
||||
defp proceed_path(diag, limit, [path | _] = paths) when diag == -limit do
|
||||
{move_down(path), paths}
|
||||
defp proceed_path(diag, limit, [path | _] = paths, diff_script) when diag == -limit do
|
||||
{move_down(path, diff_script), paths}
|
||||
end
|
||||
|
||||
defp proceed_path(diag, limit, [path]) when diag == limit do
|
||||
{move_right(path), []}
|
||||
defp proceed_path(diag, limit, [path], diff_script) when diag == limit do
|
||||
{move_right(path, diff_script), []}
|
||||
end
|
||||
|
||||
defp proceed_path(_diag, _limit, [path1, path2 | rest]) do
|
||||
defp proceed_path(_diag, _limit, [path1, path2 | rest], diff_script) do
|
||||
if elem(path1, 0) > elem(path2, 0) do
|
||||
{move_right(path1), [path2 | rest]}
|
||||
{move_right(path1, diff_script), [path2 | rest]}
|
||||
else
|
||||
{move_down(path2), [path2 | rest]}
|
||||
{move_down(path2, diff_script), [path2 | rest]}
|
||||
end
|
||||
end
|
||||
|
||||
defp move_right({y, list1, [elem | rest], edits}) do
|
||||
defp move_right({y, [elem1 | rest1] = list1, [elem2 | rest2], edits}, diff_script)
|
||||
when diff_script != nil do
|
||||
if diff = diff_script.(elem1, elem2) do
|
||||
{y + 1, rest1, rest2, [{:diff, diff} | edits]}
|
||||
else
|
||||
{y, list1, rest2, [{:ins, elem2} | edits]}
|
||||
end
|
||||
end
|
||||
|
||||
defp move_right({y, list1, [elem | rest], edits}, _diff_script) do
|
||||
{y, list1, rest, [{:ins, elem} | edits]}
|
||||
end
|
||||
|
||||
defp move_right({y, list1, [], edits}) do
|
||||
defp move_right({y, list1, [], edits}, _diff_script) do
|
||||
{y, list1, [], edits}
|
||||
end
|
||||
|
||||
defp move_down({y, [elem | rest], list2, edits}) do
|
||||
defp move_down({y, [elem1 | rest1], [elem2 | rest2] = list2, edits}, diff_script)
|
||||
when diff_script != nil do
|
||||
if diff = diff_script.(elem1, elem2) do
|
||||
{y + 1, rest1, rest2, [{:diff, diff} | edits]}
|
||||
else
|
||||
{y + 1, rest1, list2, [{:del, elem1} | edits]}
|
||||
end
|
||||
end
|
||||
|
||||
defp move_down({y, [elem | rest], list2, edits}, _diff_script) do
|
||||
{y + 1, rest, list2, [{:del, elem} | edits]}
|
||||
end
|
||||
|
||||
defp move_down({y, [], list2, edits}) do
|
||||
defp move_down({y, [], list2, edits}, _diff_script) do
|
||||
{y + 1, [], list2, edits}
|
||||
end
|
||||
|
||||
@@ -962,10 +1126,6 @@ defmodule List do
|
||||
[]
|
||||
end
|
||||
|
||||
defp do_replace_at(list, index, _value) when index < 0 do
|
||||
list
|
||||
end
|
||||
|
||||
defp do_replace_at([_old | rest], 0, value) do
|
||||
[value | rest]
|
||||
end
|
||||
@@ -980,7 +1140,7 @@ defmodule List do
|
||||
[value]
|
||||
end
|
||||
|
||||
defp do_insert_at(list, index, value) when index <= 0 do
|
||||
defp do_insert_at(list, 0, value) do
|
||||
[value | list]
|
||||
end
|
||||
|
||||
@@ -994,10 +1154,6 @@ defmodule List do
|
||||
[fun.(value) | list]
|
||||
end
|
||||
|
||||
defp do_update_at(list, index, _fun) when index < 0 do
|
||||
list
|
||||
end
|
||||
|
||||
defp do_update_at([head | tail], index, fun) do
|
||||
[head | do_update_at(tail, index - 1, fun)]
|
||||
end
|
||||
@@ -1012,10 +1168,6 @@ defmodule List do
|
||||
{default, :lists.reverse(acc)}
|
||||
end
|
||||
|
||||
defp do_pop_at(list, index, default, []) when index < 0 do
|
||||
{default, list}
|
||||
end
|
||||
|
||||
defp do_pop_at([head | tail], 0, _default, acc) do
|
||||
{head, :lists.reverse(acc, tail)}
|
||||
end
|
||||
|
||||
+77
-27
@@ -95,7 +95,7 @@ defmodule Macro do
|
||||
`div/2` function, so that the AST for that function will become `{:div, [],
|
||||
[100, 5]}` (`div(100, 5)`).
|
||||
"""
|
||||
@spec unpipe(Macro.t()) :: [Macro.t()]
|
||||
@spec unpipe(t()) :: [t()]
|
||||
def unpipe(expr) do
|
||||
:lists.reverse(unpipe(expr, []))
|
||||
end
|
||||
@@ -111,7 +111,7 @@ defmodule Macro do
|
||||
@doc """
|
||||
Pipes `expr` into the `call_args` at the given `position`.
|
||||
"""
|
||||
@spec pipe(Macro.t(), Macro.t(), integer) :: Macro.t() | no_return
|
||||
@spec pipe(t(), t(), integer) :: t()
|
||||
def pipe(expr, call_args, position)
|
||||
|
||||
def pipe(expr, {:&, _, _} = call_args, _integer) do
|
||||
@@ -131,13 +131,17 @@ defmodule Macro do
|
||||
raise ArgumentError, bad_pipe(expr, call_args)
|
||||
end
|
||||
|
||||
def pipe(expr, {unquote, _, []}, _integer) when unquote in [:unquote, :unquote_splicing] do
|
||||
raise ArgumentError,
|
||||
"cannot pipe #{to_string(expr)} into the special form #{unquote}/1 " <>
|
||||
"since #{unquote}/1 is used to build the Elixir AST itself"
|
||||
end
|
||||
|
||||
# {:fn, _, _} is what we get when we pipe into an anonymous function without
|
||||
# calling it, e.g., `:foo |> (fn x -> x end)`.
|
||||
def pipe(expr, {:fn, _, _}, _integer) do
|
||||
expr_str = to_string(expr)
|
||||
|
||||
raise ArgumentError,
|
||||
"cannot pipe #{expr_str} into an anonymous function without" <>
|
||||
"cannot pipe #{to_string(expr)} into an anonymous function without" <>
|
||||
" calling the function; use something like (fn ... end).() or" <>
|
||||
" define the anonymous function as a regular private function"
|
||||
end
|
||||
@@ -162,7 +166,7 @@ defmodule Macro do
|
||||
|
||||
defp bad_pipe(expr, call_args) do
|
||||
"cannot pipe #{to_string(expr)} into #{to_string(call_args)}, " <>
|
||||
"can only pipe into local calls foo(), remote calls Foo.bar() or anonymous functions calls foo.()"
|
||||
"can only pipe into local calls foo(), remote calls Foo.bar() or anonymous function calls foo.()"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -198,7 +202,7 @@ defmodule Macro do
|
||||
## Examples
|
||||
|
||||
iex> Macro.generate_arguments(2, __MODULE__)
|
||||
[{:var1, [], __MODULE__}, {:var2, [], __MODULE__}]
|
||||
[{:arg1, [], __MODULE__}, {:arg2, [], __MODULE__}]
|
||||
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@@ -206,7 +210,7 @@ defmodule Macro do
|
||||
|
||||
def generate_arguments(amount, context)
|
||||
when is_integer(amount) and amount > 0 and is_atom(context) do
|
||||
for id <- 1..amount, do: Macro.var(String.to_atom("var" <> Integer.to_string(id)), context)
|
||||
for id <- 1..amount, do: var(String.to_atom("arg" <> Integer.to_string(id)), context)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -342,7 +346,7 @@ defmodule Macro do
|
||||
:error
|
||||
|
||||
"""
|
||||
@spec decompose_call(Macro.t()) :: {atom, [Macro.t()]} | {Macro.t(), atom, [Macro.t()]} | :error
|
||||
@spec decompose_call(t()) :: {atom, [t()]} | {t(), atom, [t()]} | :error
|
||||
def decompose_call(ast)
|
||||
|
||||
def decompose_call({{:., _, [remote, function]}, _, args})
|
||||
@@ -356,12 +360,7 @@ defmodule Macro do
|
||||
def decompose_call(_), do: :error
|
||||
|
||||
@doc """
|
||||
Recursively escapes a value so it can be inserted
|
||||
into a syntax tree.
|
||||
|
||||
One may pass `unquote: true` to `escape/2`
|
||||
which leaves `unquote/1` statements unescaped, effectively
|
||||
unquoting the contents on escape.
|
||||
Recursively escapes a value so it can be inserted into a syntax tree.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -374,7 +373,27 @@ defmodule Macro do
|
||||
iex> Macro.escape({:unquote, [], [1]}, unquote: true)
|
||||
1
|
||||
|
||||
## Comparison to `Kernel.quote/2`
|
||||
## Options
|
||||
|
||||
* `:unquote` - when true, this function leaves `unquote/1` and
|
||||
`unquote_splicing/1` statements unescaped, effectively unquoting
|
||||
the contents on escape. This option is useful only when escaping
|
||||
ASTs which may have quoted fragments in them. Defaults to false.
|
||||
|
||||
* `:prune_metadata` - when true, removes metadata from escaped AST
|
||||
nodes. Note this option changes the semantics of escaped code and
|
||||
it should only be used when escaping ASTs, never values. Defaults
|
||||
to false.
|
||||
|
||||
As an example, `ExUnit` stores the AST of every assertion, so when
|
||||
an assertion fails we can show code snippets to users. Without this
|
||||
option, each time the test module is compiled, we get a different
|
||||
MD5 of the module byte code, because the AST contains metadata,
|
||||
such as counters, specific to the compilation environment. By pruning
|
||||
the metadata, we ensure that the module is deterministic and reduce
|
||||
the amount of data `ExUnit` needs to keep around.
|
||||
|
||||
## Comparison to `Kernel.SpecialForms.quote/2`
|
||||
|
||||
The `escape/2` function is sometimes confused with `Kernel.SpecialForms.quote/2`,
|
||||
because the above examples behave the same with both. The key difference is
|
||||
@@ -400,9 +419,29 @@ defmodule Macro do
|
||||
bound), while `Kernel.SpecialForms.quote/2` produces syntax trees for
|
||||
expressions.
|
||||
"""
|
||||
@spec escape(term, keyword) :: Macro.t()
|
||||
@spec escape(term, keyword) :: t()
|
||||
def escape(expr, opts \\ []) do
|
||||
elem(:elixir_quote.escape(expr, Keyword.get(opts, :unquote, false)), 0)
|
||||
unquote = Keyword.get(opts, :unquote, false)
|
||||
kind = if Keyword.get(opts, :prune_metadata, false), do: :prune_metadata, else: :default
|
||||
:elixir_quote.escape(expr, kind, unquote)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Expands the struct given by `module` in the given `env`.
|
||||
|
||||
This is useful when a struct needs to be expanded at
|
||||
compilation time and the struct being expanded may or may
|
||||
not have been compiled. This function is even capable of
|
||||
expanding structs defined under the module being compiled.
|
||||
|
||||
It will raise `CompileError` if the struct is not available.
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec struct!(module, Macro.Env.t()) :: %{__struct__: module} when module: module()
|
||||
def struct!(module, env) when is_atom(module) do
|
||||
if module == env.module do
|
||||
Module.get_attribute(module, :struct)
|
||||
end || :elixir_map.load_struct([line: env.line], module, [], env)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -508,7 +547,7 @@ defmodule Macro do
|
||||
def unescape_map(?s), do: ?\s
|
||||
def unescape_map(?t), do: ?\t
|
||||
def unescape_map(?v), do: ?\v
|
||||
def unescape_map(e), do: e
|
||||
def unescape_map(e), do: e
|
||||
|
||||
If the `unescape_map/1` function returns `false`, the char is
|
||||
not escaped and the backslash is kept in the string.
|
||||
@@ -521,7 +560,7 @@ defmodule Macro do
|
||||
|
||||
Using the `unescape_map/1` function defined above is easy:
|
||||
|
||||
Macro.unescape_string "example\\n", &unescape_map(&1)
|
||||
Macro.unescape_string("example\\n", &unescape_map(&1))
|
||||
|
||||
"""
|
||||
@spec unescape_string(String.t(), (non_neg_integer -> non_neg_integer | false)) :: String.t()
|
||||
@@ -570,7 +609,7 @@ defmodule Macro do
|
||||
"one + two"
|
||||
|
||||
"""
|
||||
@spec to_string(Macro.t(), (Macro.t(), String.t() -> String.t())) :: String.t()
|
||||
@spec to_string(t(), (t(), String.t() -> String.t())) :: String.t()
|
||||
def to_string(tree, fun \\ fn _ast, string -> string end)
|
||||
|
||||
# Variables
|
||||
@@ -719,9 +758,13 @@ defmodule Macro do
|
||||
{list, last} = split_last(args)
|
||||
|
||||
result =
|
||||
case kw_blocks?(last) do
|
||||
true -> call_to_string_with_args(target, list, fun) <> kw_blocks_to_string(last, fun)
|
||||
false -> call_to_string_with_args(target, args, fun)
|
||||
if kw_blocks?(last) do
|
||||
case list do
|
||||
[] -> call_to_string(target, fun) <> kw_blocks_to_string(last, fun)
|
||||
_ -> call_to_string_with_args(target, list, fun) <> kw_blocks_to_string(last, fun)
|
||||
end
|
||||
else
|
||||
call_to_string_with_args(target, args, fun)
|
||||
end
|
||||
|
||||
fun.(ast, result)
|
||||
@@ -1148,7 +1191,7 @@ defmodule Macro do
|
||||
|
||||
defmacro defmodule_with_length(name, do: block) do
|
||||
expanded = Macro.expand(name, __CALLER__)
|
||||
length = length(Atom.to_charlist(expanded))
|
||||
length = length(Atom.to_charlist(expanded))
|
||||
|
||||
quote do
|
||||
defmodule unquote(name) do
|
||||
@@ -1235,9 +1278,15 @@ defmodule Macro do
|
||||
|
||||
case expand do
|
||||
{:ok, receiver, quoted} ->
|
||||
next = :erlang.unique_integer()
|
||||
next = :elixir_module.next_counter(module)
|
||||
{:elixir_quote.linify_with_context_counter(0, {receiver, next}, quoted), true}
|
||||
|
||||
{:ok, Kernel, op, [arg]} when op in [:+, :-] ->
|
||||
case expand_once(arg, env) do
|
||||
integer when is_integer(integer) -> {apply(Kernel, op, [integer]), true}
|
||||
_ -> {original, false}
|
||||
end
|
||||
|
||||
{:ok, _receiver, _name, _args} ->
|
||||
{original, false}
|
||||
|
||||
@@ -1260,7 +1309,7 @@ defmodule Macro do
|
||||
|
||||
case expand do
|
||||
{:ok, receiver, quoted} ->
|
||||
next = :erlang.unique_integer()
|
||||
next = :elixir_module.next_counter(env.module)
|
||||
{:elixir_quote.linify_with_context_counter(0, {receiver, next}, quoted), true}
|
||||
|
||||
:error ->
|
||||
@@ -1359,6 +1408,7 @@ defmodule Macro do
|
||||
"Hello10"
|
||||
|
||||
"""
|
||||
@spec underscore(atom | String.t()) :: String.t()
|
||||
def underscore(atom) when is_atom(atom) do
|
||||
"Elixir." <> rest = Atom.to_string(atom)
|
||||
underscore(rest)
|
||||
|
||||
@@ -28,7 +28,7 @@ defmodule Macro.Env do
|
||||
element is the function name and the second its arity; returns
|
||||
`nil` if not inside a function
|
||||
* `context` - the context of the environment; it can be `nil`
|
||||
(default context), inside a guard or inside a match
|
||||
(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
|
||||
@@ -45,6 +45,7 @@ defmodule Macro.Env do
|
||||
* `current_vars`
|
||||
* `unused_vars`
|
||||
* `prematch_vars`
|
||||
* `contextual_vars`
|
||||
|
||||
The following fields are deprecated and must not be accessed or relied on:
|
||||
|
||||
@@ -56,20 +57,20 @@ defmodule Macro.Env do
|
||||
@type file :: binary
|
||||
@type line :: non_neg_integer
|
||||
@type aliases :: [{module, module}]
|
||||
@type macro_aliases :: [{module, {integer, 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 var :: {atom, atom | non_neg_integer}
|
||||
@type variable :: {atom, atom | term}
|
||||
|
||||
@typep vars :: [var]
|
||||
@typep vars :: [variable]
|
||||
@typep var_type :: :term
|
||||
@typep var_version :: non_neg_integer
|
||||
@typep unused_vars :: %{{var, var_version} => non_neg_integer | false}
|
||||
@typep current_vars :: %{var => {var_version, var_type}}
|
||||
@typep unused_vars :: %{{variable, var_version} => non_neg_integer | false}
|
||||
@typep current_vars :: %{variable => {var_version, var_type}}
|
||||
@typep prematch_vars :: current_vars | :warn | :raise | :pin | :apply
|
||||
@typep contextual_vars :: [atom]
|
||||
|
||||
@@ -131,7 +132,7 @@ defmodule Macro.Env do
|
||||
atom or an integer.
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec vars(t) :: [var]
|
||||
@spec vars(t) :: [variable]
|
||||
def vars(env)
|
||||
|
||||
def vars(%{__struct__: Macro.Env, current_vars: current_vars}) do
|
||||
@@ -142,7 +143,7 @@ defmodule Macro.Env do
|
||||
Checks if a variable belongs to the environment.
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec has_var?(t, var) :: boolean()
|
||||
@spec has_var?(t, variable) :: boolean()
|
||||
def has_var?(env, var)
|
||||
|
||||
def has_var?(%{__struct__: Macro.Env, current_vars: current_vars}, var) do
|
||||
|
||||
@@ -165,7 +165,7 @@ defmodule Map do
|
||||
|
||||
iex> Map.new([{:b, 1}, {:a, 2}])
|
||||
%{a: 2, b: 1}
|
||||
iex> Map.new([a: 1, a: 2, a: 3])
|
||||
iex> Map.new(a: 1, a: 2, a: 3)
|
||||
%{a: 3}
|
||||
|
||||
"""
|
||||
@@ -262,7 +262,7 @@ defmodule Map do
|
||||
** (KeyError) key :b not found in: %{a: 1}
|
||||
|
||||
"""
|
||||
@spec fetch!(map, key) :: value | no_return
|
||||
@spec fetch!(map, key) :: value
|
||||
def fetch!(map, key) do
|
||||
:maps.get(key, map)
|
||||
end
|
||||
@@ -506,7 +506,6 @@ defmodule Map do
|
||||
iex> Map.delete(%{b: 2}, :a)
|
||||
%{b: 2}
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec delete(map, key) :: map
|
||||
def delete(map, key), do: :maps.remove(key, map)
|
||||
@@ -825,7 +824,7 @@ defmodule Map do
|
||||
{1, %{}}
|
||||
|
||||
"""
|
||||
@spec get_and_update!(map, key, (value -> {get, value} | :pop)) :: {get, map} | no_return
|
||||
@spec get_and_update!(map, key, (value -> {get, value} | :pop)) :: {get, map}
|
||||
when get: term
|
||||
def get_and_update!(map, key, fun) when is_function(fun, 1) do
|
||||
value = fetch!(map, key)
|
||||
|
||||
@@ -398,6 +398,7 @@ defmodule MapSet do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(map_set, opts) do
|
||||
opts = %Inspect.Opts{opts | charlists: :as_lists}
|
||||
concat(["#MapSet<", Inspect.List.inspect(MapSet.to_list(map_set), opts), ">"])
|
||||
end
|
||||
end
|
||||
|
||||
+103
-81
@@ -41,7 +41,7 @@ defmodule Module do
|
||||
@callback default_port() :: integer
|
||||
|
||||
@doc "Parses the given URL"
|
||||
@callback parse(uri_info :: URI.t) :: URI.t
|
||||
@callback parse(uri_info :: URI.t()) :: URI.t()
|
||||
end
|
||||
|
||||
And then a module may use it as:
|
||||
@@ -60,14 +60,25 @@ defmodule Module do
|
||||
To aid in the correct implementation of behaviours, you may optionally declare
|
||||
`@impl` for implemented callbacks of a behaviour. This makes callbacks
|
||||
explicit and can help you to catch errors in your code. The compiler will warn
|
||||
you if you mark a function as `@impl` when in fact it is not a callback, and
|
||||
vice-versa. It also helps with maintainability by making it clear to other
|
||||
developers that the function's purpose is to implement a callback.
|
||||
in these cases:
|
||||
|
||||
Using `@impl` the example above can be rewritten as:
|
||||
* if you mark a function with `@impl` when that function is not a callback.
|
||||
|
||||
* if you don't mark a function with `@impl` when other functions are marked
|
||||
with `@impl`. If you mark one function with `@impl`, you must mark all
|
||||
other callbacks for that behaviour as `@impl`.
|
||||
|
||||
`@impl` works on a per-context basis. If you generate a function through a macro
|
||||
and mark it with `@impl`, that won't affect the module where that function is
|
||||
generated in.
|
||||
|
||||
`@impl` also helps with maintainability by making it clear to other developers
|
||||
that the function is implementing a callback.
|
||||
|
||||
Using `@impl`, the example above can be rewritten as:
|
||||
|
||||
defmodule URI.HTTP do
|
||||
@behaviour URI.parser
|
||||
@behaviour URI.Parser
|
||||
|
||||
@impl true
|
||||
def default_port(), do: 80
|
||||
@@ -82,14 +93,16 @@ defmodule Module do
|
||||
@behaviour Bar
|
||||
@behaviour Baz
|
||||
|
||||
@impl true # will warn if neither Bar nor Baz specify a callback named bar/0
|
||||
# Will warn if neither Bar nor Baz specify a callback named bar/0.
|
||||
@impl true
|
||||
def bar(), do: :ok
|
||||
|
||||
@impl Baz # will warn if Baz does not specify a callback named baz/0
|
||||
# Will warn if Baz does not specify a callback named baz/0.
|
||||
@impl Baz
|
||||
def baz(), do: :ok
|
||||
end
|
||||
|
||||
Readability of the code is increased, as it is now clear which functions are
|
||||
The code is now more readable, as it is now clear which functions are
|
||||
part of your API and which ones are callback implementations. To reinforce this
|
||||
idea, `@impl true` automatically marks the function as `@doc false`, disabling
|
||||
documentation unless `@doc` is explicitly set.
|
||||
@@ -128,7 +141,7 @@ defmodule Module do
|
||||
Using the `@deprecated` attribute will also be reflected in the
|
||||
documentation of the given function and macro. You can choose between
|
||||
the `@deprecated` attribute and the documentation metadata to provide
|
||||
hard-deprecations (with warnings) and soft-deprecations (with warnings):
|
||||
hard-deprecations (with warnings) and soft-deprecations (without warnings):
|
||||
|
||||
This is a soft-deprecation as it simply annotates the documentation
|
||||
as deprecated:
|
||||
@@ -276,9 +289,9 @@ defmodule Module do
|
||||
|
||||
Accepts the function name (as an atom) of a function in the current module or
|
||||
`{function_name, 0}` tuple where `function_name` is the name of a function in
|
||||
the current module. The function must have arity 0 (no arguments) and has to
|
||||
return `:ok`, otherwise the loading of the module will be aborted. For
|
||||
example:
|
||||
the current module. The function must be public and have an arity of 0 (no
|
||||
arguments). If the function does not return `:ok`, the loading of the module
|
||||
will be aborted. For example:
|
||||
|
||||
defmodule MyModule do
|
||||
@on_load :load_check
|
||||
@@ -356,7 +369,7 @@ defmodule Module do
|
||||
@after_compile __MODULE__
|
||||
|
||||
def __after_compile__(env, _bytecode) do
|
||||
IO.inspect env
|
||||
IO.inspect(env)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -432,12 +445,12 @@ defmodule Module do
|
||||
|
||||
defmodule Hooks do
|
||||
def on_def(_env, kind, name, args, guards, body) do
|
||||
IO.puts "Defining #{kind} named #{name} with args:"
|
||||
IO.inspect args
|
||||
IO.puts "and guards"
|
||||
IO.inspect guards
|
||||
IO.puts "and body"
|
||||
IO.puts Macro.to_string(body)
|
||||
IO.puts("Defining #{kind} named #{name} with args:")
|
||||
IO.inspect(args)
|
||||
IO.puts("and guards")
|
||||
IO.inspect(guards)
|
||||
IO.puts("and body")
|
||||
IO.puts(Macro.to_string(body))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -466,7 +479,8 @@ defmodule Module do
|
||||
of the corresponding setting in `Code.compiler_options/1`
|
||||
|
||||
* `@compile {:inline, some_fun: 2, other_fun: 3}` - inlines the given
|
||||
name/arity pairs
|
||||
name/arity pairs. Inlining is applied locally, calls from another
|
||||
module are not affected by this option
|
||||
|
||||
* `@compile {:autoload, false}` - disables automatic loading of
|
||||
modules after compilation. Instead, the module will be loaded after
|
||||
@@ -499,7 +513,7 @@ defmodule Module do
|
||||
* `:attributes` - a list with all persisted attributes
|
||||
|
||||
"""
|
||||
def __info__(kind)
|
||||
@callback __info__(:functions | :macros | :module | :md5 | :compile | :attributes) :: term()
|
||||
|
||||
@doc """
|
||||
Checks if a module is open.
|
||||
@@ -523,11 +537,16 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule Foo do
|
||||
contents = quote do: (def sum(a, b), do: a + b)
|
||||
Module.eval_quoted __MODULE__, contents
|
||||
contents =
|
||||
quote do
|
||||
def sum(a, b), do: a + b
|
||||
end
|
||||
|
||||
Module.eval_quoted(__MODULE__, contents)
|
||||
end
|
||||
|
||||
Foo.sum(1, 2) #=> 3
|
||||
Foo.sum(1, 2)
|
||||
#=> 3
|
||||
|
||||
For convenience, you can pass any `Macro.Env` struct, such
|
||||
as `__ENV__/0`, as the first argument or as options. Both
|
||||
@@ -535,11 +554,16 @@ defmodule Module do
|
||||
from the environment:
|
||||
|
||||
defmodule Foo do
|
||||
contents = quote do: (def sum(a, b), do: a + b)
|
||||
Module.eval_quoted __ENV__, contents
|
||||
contents =
|
||||
quote do
|
||||
def sum(a, b), do: a + b
|
||||
end
|
||||
|
||||
Module.eval_quoted(__ENV__, contents)
|
||||
end
|
||||
|
||||
Foo.sum(1, 2) #=> 3
|
||||
Foo.sum(1, 2)
|
||||
#=> 3
|
||||
|
||||
Note that if you pass a `Macro.Env` struct as first argument
|
||||
while also passing `opts`, they will be merged with `opts`
|
||||
@@ -594,7 +618,8 @@ defmodule Module do
|
||||
|
||||
Module.create(Hello, contents, Macro.Env.location(__ENV__))
|
||||
|
||||
Hello.world #=> true
|
||||
Hello.world()
|
||||
#=> true
|
||||
|
||||
## Differences from `defmodule`
|
||||
|
||||
@@ -621,7 +646,7 @@ defmodule Module do
|
||||
raise ArgumentError, "expected :file to be given as option"
|
||||
end
|
||||
|
||||
next = :erlang.unique_integer()
|
||||
next = :elixir_module.next_counter(nil)
|
||||
line = Keyword.get(opts, :line, 0)
|
||||
quoted = :elixir_quote.linify_with_context_counter(line, {module, next}, quoted)
|
||||
:elixir_module.compile(module, quoted, [], :elixir.env_for_eval(opts))
|
||||
@@ -880,9 +905,9 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule Example do
|
||||
Module.defines? __MODULE__, {:version, 0} #=> false
|
||||
Module.defines?(__MODULE__, {:version, 0}) #=> false
|
||||
def version, do: 1
|
||||
Module.defines? __MODULE__, {:version, 0} #=> true
|
||||
Module.defines?(__MODULE__, {:version, 0}) #=> true
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -906,9 +931,9 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule Example do
|
||||
Module.defines? __MODULE__, {:version, 0}, :defp #=> false
|
||||
Module.defines?(__MODULE__, {:version, 0}, :def) #=> false
|
||||
def version, do: 1
|
||||
Module.defines? __MODULE__, {:version, 0}, :defp #=> false
|
||||
Module.defines?(__MODULE__, {:version, 0}, :def) #=> true
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -954,7 +979,7 @@ defmodule Module do
|
||||
|
||||
defmodule Example do
|
||||
def version, do: 1
|
||||
Module.definitions_in __MODULE__ #=> [{:version, 0}]
|
||||
Module.definitions_in(__MODULE__) #=> [{:version, 0}]
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -973,8 +998,8 @@ defmodule Module do
|
||||
|
||||
defmodule Example do
|
||||
def version, do: 1
|
||||
Module.definitions_in __MODULE__, :def #=> [{:version, 0}]
|
||||
Module.definitions_in __MODULE__, :defp #=> []
|
||||
Module.definitions_in(__MODULE__, :def) #=> [{:version, 0}]
|
||||
Module.definitions_in(__MODULE__, :defp) #=> []
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -1113,7 +1138,7 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule MyModule do
|
||||
Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10
|
||||
Module.put_attribute(__MODULE__, :custom_threshold_for_lib, 10)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -1142,12 +1167,12 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule Foo do
|
||||
Module.put_attribute __MODULE__, :value, 1
|
||||
Module.get_attribute __MODULE__, :value #=> 1
|
||||
Module.put_attribute(__MODULE__, :value, 1)
|
||||
Module.get_attribute(__MODULE__, :value) #=> 1
|
||||
|
||||
Module.register_attribute __MODULE__, :value, accumulate: true
|
||||
Module.put_attribute __MODULE__, :value, 1
|
||||
Module.get_attribute __MODULE__, :value #=> [1]
|
||||
Module.register_attribute(__MODULE__, :value, accumulate: true)
|
||||
Module.put_attribute(__MODULE__, :value, 1)
|
||||
Module.get_attribute(__MODULE__, :value) #=> [1]
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -1164,8 +1189,8 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule MyModule do
|
||||
Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10
|
||||
Module.delete_attribute __MODULE__, :custom_threshold_for_lib
|
||||
Module.put_attribute(__MODULE__, :custom_threshold_for_lib, 10)
|
||||
Module.delete_attribute(__MODULE__, :custom_threshold_for_lib)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -1201,7 +1226,7 @@ defmodule Module do
|
||||
When registering an attribute, two options can be given:
|
||||
|
||||
* `:accumulate` - several calls to the same attribute will
|
||||
accumulate instead of override the previous one. New attributes
|
||||
accumulate instead of overriding the previous one. New attributes
|
||||
are always added to the top of the accumulated list.
|
||||
|
||||
* `:persist` - the attribute will be persisted in the Erlang
|
||||
@@ -1212,9 +1237,7 @@ defmodule Module do
|
||||
## Examples
|
||||
|
||||
defmodule MyModule do
|
||||
Module.register_attribute __MODULE__,
|
||||
:custom_threshold_for_lib,
|
||||
accumulate: true, persist: false
|
||||
Module.register_attribute(__MODULE__, :custom_threshold_for_lib, accumulate: true)
|
||||
|
||||
@custom_threshold_for_lib 10
|
||||
@custom_threshold_for_lib 20
|
||||
@@ -1319,7 +1342,7 @@ defmodule Module do
|
||||
end
|
||||
end
|
||||
|
||||
defp compile_doc(table, line, kind, name, arity, args, body, doc, doc_meta, env, impl) do
|
||||
defp compile_doc(table, line, kind, name, arity, args, _body, doc, doc_meta, env, impl) do
|
||||
key = {doc_key(kind), name, arity}
|
||||
signature = build_signature(args, env)
|
||||
|
||||
@@ -1330,16 +1353,6 @@ defmodule Module do
|
||||
|
||||
[{_, current_line, current_sign, current_doc, current_doc_meta}] ->
|
||||
signature = merge_signatures(current_sign, signature, 1)
|
||||
|
||||
if is_binary(doc) and is_binary(current_doc) and not is_nil(body) do
|
||||
message =
|
||||
"redefining @doc attribute previously set at line #{current_line}. " <>
|
||||
"If you want to redefine a previously specified doc, " <>
|
||||
"use a definition without a body after the original documentation"
|
||||
|
||||
:elixir_errors.warn(line, env.file, message)
|
||||
end
|
||||
|
||||
doc = if is_nil(doc), do: current_doc, else: doc
|
||||
doc = if is_nil(doc) && impl, do: false, else: doc
|
||||
doc_meta = Map.merge(current_doc_meta, doc_meta)
|
||||
@@ -1450,9 +1463,7 @@ defmodule Module do
|
||||
message =
|
||||
"@behaviour #{inspect(behaviour)} does not exist (in module #{inspect(env.module)})"
|
||||
|
||||
unless standard_behaviour?(behaviour) do
|
||||
:elixir_errors.warn(env.line, env.file, message)
|
||||
end
|
||||
:elixir_errors.warn(env.line, env.file, message)
|
||||
|
||||
acc
|
||||
|
||||
@@ -1460,9 +1471,7 @@ defmodule Module do
|
||||
message =
|
||||
"module #{inspect(behaviour)} is not a behaviour (in module #{inspect(env.module)})"
|
||||
|
||||
unless standard_behaviour?(behaviour) do
|
||||
:elixir_errors.warn(env.line, env.file, message)
|
||||
end
|
||||
:elixir_errors.warn(env.line, env.file, message)
|
||||
|
||||
acc
|
||||
|
||||
@@ -1493,16 +1502,6 @@ defmodule Module do
|
||||
Map.put(acc, callback, {kind, behaviour, original in optional_callbacks})
|
||||
end
|
||||
|
||||
defp standard_behaviour?(behaviour) do
|
||||
behaviour in [
|
||||
Collectable,
|
||||
Enumerable,
|
||||
Inspect,
|
||||
List.Chars,
|
||||
String.Chars
|
||||
]
|
||||
end
|
||||
|
||||
defp check_callbacks(env, callbacks, all_definitions) do
|
||||
for {callback, {kind, behaviour, optional?}} <- callbacks do
|
||||
case :lists.keyfind(callback, 1, all_definitions) do
|
||||
@@ -1767,9 +1766,8 @@ defmodule Module do
|
||||
end
|
||||
end
|
||||
|
||||
# This is the same list of attributes as in :elixir_module.
|
||||
# We do not insert into the :attributes key in the bag table
|
||||
# because those attributes are deleted on every definition.
|
||||
# Optimize some attributes by avoiding writing to the attributes key
|
||||
# in the bag table since we handle them internally.
|
||||
defp put_attribute(module, key, value, line, set, _bag)
|
||||
when key in [:doc, :typedoc, :moduledoc, :impl, :deprecated] do
|
||||
try do
|
||||
@@ -1788,6 +1786,18 @@ defmodule Module do
|
||||
:ets.insert(set, {key, value, line})
|
||||
end
|
||||
|
||||
defp put_attribute(_module, :on_load, value, line, set, bag) do
|
||||
try do
|
||||
:ets.lookup_element(set, :on_load, 3)
|
||||
catch
|
||||
:error, :badarg ->
|
||||
:ets.insert(set, {:on_load, value, line})
|
||||
:ets.insert(bag, {:attributes, :on_load})
|
||||
else
|
||||
_ -> raise ArgumentError, "the @on_load attribute can only be set once per module"
|
||||
end
|
||||
end
|
||||
|
||||
defp put_attribute(_module, key, value, line, set, bag) do
|
||||
try do
|
||||
:ets.lookup_element(set, key, 3)
|
||||
@@ -1873,9 +1883,9 @@ defmodule Module do
|
||||
do: {atom, :__on_definition__}
|
||||
|
||||
defp preprocess_attribute(key, _value)
|
||||
when key in [:type, :typep, :export_type, :opaque, :callback, :macrocallback] do
|
||||
when key in [:type, :typep, :opaque, :spec, :callback, :macrocallback] do
|
||||
raise ArgumentError,
|
||||
"attributes type, typep, export_type, opaque, callback, and macrocallback" <>
|
||||
"attributes type, typep, opaque, spec, callback, and macrocallback " <>
|
||||
"must be set directly via the @ notation"
|
||||
end
|
||||
|
||||
@@ -1937,6 +1947,18 @@ defmodule Module do
|
||||
"representing the replacement for the deprecated entity, got: #{inspect(value)}"
|
||||
end
|
||||
|
||||
defp validate_doc_meta(:delegate_to, value) do
|
||||
case value do
|
||||
{m, f, a} when is_atom(m) and is_atom(f) and is_integer(a) and a >= 0 ->
|
||||
:ok
|
||||
|
||||
_ ->
|
||||
raise ArgumentError,
|
||||
":delegate_to is a built-in documentation metadata key. It should be a three-element " <>
|
||||
"tuple in the form of {module, function, arity}, got: #{inspect(value)}"
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_doc_meta(_, _), do: :ok
|
||||
|
||||
defp get_doc_info(table, env) do
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#
|
||||
# ## Implementation
|
||||
#
|
||||
# The implementation uses ets to track all dependencies
|
||||
# The implementation uses ETS to track all dependencies
|
||||
# resembling a graph. The keys and what they point to are:
|
||||
#
|
||||
# * `:reattach` points to `{name, arity}`
|
||||
@@ -18,9 +18,9 @@ defmodule Module.LocalsTracker do
|
||||
@doc """
|
||||
Adds and tracks defaults for a definition into the tracker.
|
||||
"""
|
||||
def add_defaults({_set, bag}, _kind, {name, arity} = pair, defaults) do
|
||||
def add_defaults({_set, bag}, _kind, {name, arity} = pair, defaults, meta) do
|
||||
for i <- :lists.seq(arity - defaults, arity - 1) do
|
||||
put_edge(bag, {:local, {name, i}}, pair)
|
||||
put_edge(bag, {:local, {name, i}}, {pair, get_line(meta)})
|
||||
end
|
||||
|
||||
:ok
|
||||
@@ -29,9 +29,9 @@ defmodule Module.LocalsTracker do
|
||||
@doc """
|
||||
Adds a local dispatch from-to the given target.
|
||||
"""
|
||||
def add_local({_set, bag}, from, to) when is_tuple(from) and is_tuple(to) do
|
||||
def add_local({_set, bag}, from, to, meta) when is_tuple(from) and is_tuple(to) do
|
||||
if from != to do
|
||||
put_edge(bag, {:local, from}, to)
|
||||
put_edge(bag, {:local, from}, {to, get_line(meta)})
|
||||
end
|
||||
|
||||
:ok
|
||||
@@ -56,14 +56,14 @@ defmodule Module.LocalsTracker do
|
||||
@doc """
|
||||
Reattach a previously yanked node.
|
||||
"""
|
||||
def reattach({_set, bag}, tuple, _kind, function, out_neigh) do
|
||||
for to <- out_neigh do
|
||||
put_edge(bag, {:local, function}, to)
|
||||
def reattach({_set, bag}, tuple, _kind, function, out_neighbours, meta) do
|
||||
for out_neighbour <- out_neighbours do
|
||||
put_edge(bag, {:local, function}, out_neighbour)
|
||||
end
|
||||
|
||||
# Make a call from the old function to the new one
|
||||
if function != tuple do
|
||||
put_edge(bag, {:local, function}, tuple)
|
||||
put_edge(bag, {:local, function}, {tuple, get_line(meta)})
|
||||
end
|
||||
|
||||
# Finally marked the new one as reattached
|
||||
@@ -98,6 +98,19 @@ defmodule Module.LocalsTracker do
|
||||
{unreachable(reachable, reattached, private), collect_warnings(reachable, private)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Collect undefined functions based on local calls and existing definitions
|
||||
"""
|
||||
def collect_undefined_locals({set, bag}, all_defined) do
|
||||
undefined =
|
||||
for {pair, _, _, _} <- all_defined,
|
||||
{local, line} <- out_neighbours(bag, {:local, pair}),
|
||||
not :ets.member(set, {:def, local}),
|
||||
do: {build_meta(line), local}
|
||||
|
||||
:lists.usort(undefined)
|
||||
end
|
||||
|
||||
defp unreachable(reachable, reattached, private) do
|
||||
for {tuple, kind, _, _} <- private,
|
||||
not reachable?(tuple, kind, reachable, reattached),
|
||||
@@ -170,7 +183,7 @@ defmodule Module.LocalsTracker do
|
||||
defp reachable_from(bag, local, vertices) do
|
||||
vertices = Map.put(vertices, local, true)
|
||||
|
||||
Enum.reduce(out_neighbours(bag, {:local, local}), vertices, fn {_, _} = local, acc ->
|
||||
Enum.reduce(out_neighbours(bag, {:local, local}), vertices, fn {local, _line}, acc ->
|
||||
case acc do
|
||||
%{^local => true} -> acc
|
||||
_ -> reachable_from(bag, local, acc)
|
||||
@@ -178,6 +191,11 @@ defmodule Module.LocalsTracker do
|
||||
end)
|
||||
end
|
||||
|
||||
defp get_line(meta), do: Keyword.get(meta, :line)
|
||||
|
||||
defp build_meta(nil), do: []
|
||||
defp build_meta(line), do: [line: line]
|
||||
|
||||
## Lightweight digraph implementation
|
||||
|
||||
defp put_edge(d, from, to) do
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
defmodule OptionParser do
|
||||
@moduledoc """
|
||||
This module contains functions to parse command line options.
|
||||
Functions for parsing command line options.
|
||||
|
||||
The main function in this module is `parse/2`, which allows
|
||||
developers to parse a list of arguments into options:
|
||||
|
||||
iex> OptionParser.parse(["--debug"], strict: [debug: :boolean])
|
||||
{[debug: true], [], []}
|
||||
|
||||
`OptionParser` provides some conveniences out of the box,
|
||||
such as aliases and automatic handling of negation switches.
|
||||
|
||||
The `parse_head/2` function is an alternative to `parse/2`
|
||||
which stops parsing as soon as it finds a value that is not
|
||||
a switch nor a value for a previous switch.
|
||||
|
||||
This module also provides low-level functions, such as `next/2`,
|
||||
for parsing switches manually, as well as `split/1` and `to_argv/1`
|
||||
for parsing from and converting switches to strings.
|
||||
"""
|
||||
|
||||
@type argv :: [String.t()]
|
||||
@@ -40,8 +57,10 @@ defmodule OptionParser do
|
||||
iex> OptionParser.parse(["--source", "lib"], strict: [source: :string])
|
||||
{[source: "lib"], [], []}
|
||||
|
||||
iex> OptionParser.parse(["--source-path", "lib", "test/enum_test.exs", "--verbose"],
|
||||
...> strict: [source_path: :string, verbose: :boolean])
|
||||
iex> OptionParser.parse(
|
||||
...> ["--source-path", "lib", "test/enum_test.exs", "--verbose"],
|
||||
...> strict: [source_path: :string, verbose: :boolean]
|
||||
...> )
|
||||
{[source_path: "lib", verbose: true], ["test/enum_test.exs"], []}
|
||||
|
||||
We will explore the valid switches and operation modes of option parser below.
|
||||
@@ -63,10 +82,9 @@ defmodule OptionParser do
|
||||
* `:switches` - defines some switches and their types. This function
|
||||
still attempts to parse switches that are not in this list.
|
||||
|
||||
Both these options accept a keyword list of `{name, type}` tuples where `name`
|
||||
is an atom defining the name of the switch and `type` is an atom that
|
||||
specifies the type for the value of this switch (see the "Types" section below
|
||||
for the possible types and more information about type casting).
|
||||
Both these options accept a keyword list where the key is an atom
|
||||
defining the name of the switch and value is the `type` of the
|
||||
switch (see the "Types" section below for more information).
|
||||
|
||||
Note that you should only supply the `:switches` or the `:strict` option.
|
||||
If you supply both, an `ArgumentError` exception will be raised.
|
||||
@@ -165,8 +183,10 @@ defmodule OptionParser do
|
||||
iex> OptionParser.parse(["--unlock", "path/to/file"], strict: [unlock: :boolean])
|
||||
{[unlock: true], ["path/to/file"], []}
|
||||
|
||||
iex> OptionParser.parse(["--unlock", "--limit", "0", "path/to/file"],
|
||||
...> strict: [unlock: :boolean, limit: :integer])
|
||||
iex> OptionParser.parse(
|
||||
...> ["--unlock", "--limit", "0", "path/to/file"],
|
||||
...> strict: [unlock: :boolean, limit: :integer]
|
||||
...> )
|
||||
{[unlock: true, limit: 0], ["path/to/file"], []}
|
||||
|
||||
iex> OptionParser.parse(["--limit", "3"], strict: [limit: :integer])
|
||||
@@ -184,11 +204,16 @@ defmodule OptionParser do
|
||||
iex> OptionParser.parse(["--unknown", "xyz"], strict: [])
|
||||
{[], ["xyz"], [{"--unknown", nil}]}
|
||||
|
||||
iex> OptionParser.parse(["--limit", "3", "--unknown", "xyz"],
|
||||
...> switches: [limit: :integer])
|
||||
iex> OptionParser.parse(
|
||||
...> ["--limit", "3", "--unknown", "xyz"],
|
||||
...> switches: [limit: :integer]
|
||||
...> )
|
||||
{[limit: 3, unknown: "xyz"], [], []}
|
||||
|
||||
iex> OptionParser.parse(["--unlock", "path/to/file", "--unlock", "path/to/another/file"], strict: [unlock: :keep])
|
||||
iex> OptionParser.parse(
|
||||
...> ["--unlock", "path/to/file", "--unlock", "path/to/another/file"],
|
||||
...> strict: [unlock: :keep]
|
||||
...> )
|
||||
{[unlock: "path/to/file", unlock: "path/to/another/file"], [], []}
|
||||
|
||||
"""
|
||||
@@ -219,14 +244,17 @@ defmodule OptionParser do
|
||||
** (OptionParser.ParseError) 1 error found!
|
||||
--unknown : Unknown option
|
||||
|
||||
iex> OptionParser.parse!(["-l", "xyz", "-f", "bar"],
|
||||
...> switches: [limit: :integer, foo: :integer], aliases: [l: :limit, f: :foo])
|
||||
iex> OptionParser.parse!(
|
||||
...> ["-l", "xyz", "-f", "bar"],
|
||||
...> switches: [limit: :integer, foo: :integer],
|
||||
...> aliases: [l: :limit, f: :foo]
|
||||
...> )
|
||||
** (OptionParser.ParseError) 2 errors found!
|
||||
-l : Expected type integer, got "xyz"
|
||||
-f : Expected type integer, got "bar"
|
||||
|
||||
"""
|
||||
@spec parse!(argv, options) :: {parsed, argv} | no_return
|
||||
@spec parse!(argv, options) :: {parsed, argv}
|
||||
def parse!(argv, opts \\ []) when is_list(argv) and is_list(opts) do
|
||||
case parse(argv, opts) do
|
||||
{parsed, args, []} -> {parsed, args}
|
||||
@@ -242,12 +270,16 @@ defmodule OptionParser do
|
||||
|
||||
## Example
|
||||
|
||||
iex> OptionParser.parse_head(["--source", "lib", "test/enum_test.exs", "--verbose"],
|
||||
...> switches: [source: :string, verbose: :boolean])
|
||||
iex> OptionParser.parse_head(
|
||||
...> ["--source", "lib", "test/enum_test.exs", "--verbose"],
|
||||
...> switches: [source: :string, verbose: :boolean]
|
||||
...> )
|
||||
{[source: "lib"], ["test/enum_test.exs", "--verbose"], []}
|
||||
|
||||
iex> OptionParser.parse_head(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
|
||||
...> switches: [source: :string, verbose: :boolean, unlock: :boolean])
|
||||
iex> OptionParser.parse_head(
|
||||
...> ["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
|
||||
...> switches: [source: :string, verbose: :boolean, unlock: :boolean]
|
||||
...> )
|
||||
{[verbose: true, source: "lib"], ["test/enum_test.exs", "--unlock"], []}
|
||||
|
||||
"""
|
||||
@@ -267,23 +299,29 @@ defmodule OptionParser do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> OptionParser.parse_head!(["--source", "lib", "path/to/file", "--verbose"],
|
||||
...> switches: [source: :string, verbose: :boolean])
|
||||
iex> OptionParser.parse_head!(
|
||||
...> ["--source", "lib", "path/to/file", "--verbose"],
|
||||
...> switches: [source: :string, verbose: :boolean]
|
||||
...> )
|
||||
{[source: "lib"], ["path/to/file", "--verbose"]}
|
||||
|
||||
iex> OptionParser.parse_head!(["--number", "lib", "test/enum_test.exs", "--verbose"],
|
||||
...> strict: [number: :integer])
|
||||
iex> OptionParser.parse_head!(
|
||||
...> ["--number", "lib", "test/enum_test.exs", "--verbose"],
|
||||
...> strict: [number: :integer]
|
||||
...> )
|
||||
** (OptionParser.ParseError) 1 error found!
|
||||
--number : Expected type integer, got "lib"
|
||||
|
||||
iex> OptionParser.parse_head!(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
|
||||
...> strict: [verbose: :integer, source: :integer])
|
||||
iex> OptionParser.parse_head!(
|
||||
...> ["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
|
||||
...> strict: [verbose: :integer, source: :integer]
|
||||
...> )
|
||||
** (OptionParser.ParseError) 2 errors found!
|
||||
--verbose : Missing argument of type integer
|
||||
--source : Expected type integer, got "lib"
|
||||
|
||||
"""
|
||||
@spec parse_head!(argv, options) :: {parsed, argv} | no_return
|
||||
@spec parse_head!(argv, options) :: {parsed, argv}
|
||||
def parse_head!(argv, opts \\ []) when is_list(argv) and is_list(opts) do
|
||||
case parse_head(argv, opts) do
|
||||
{parsed, args, []} -> {parsed, args}
|
||||
@@ -447,7 +485,7 @@ defmodule OptionParser do
|
||||
|
||||
It is advised to pass to `to_argv/2` the same set of `options`
|
||||
given to `parse/2`. Some switches can only be reconstructed
|
||||
correctly with the `switches` information in hand.
|
||||
correctly with the `:switches` information in hand.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -457,7 +495,7 @@ defmodule OptionParser do
|
||||
["--bool", "--no-bool"]
|
||||
|
||||
Some switches will output different values based on the switches
|
||||
flag:
|
||||
types:
|
||||
|
||||
iex> OptionParser.to_argv([number: 2], switches: [])
|
||||
["--number", "2"]
|
||||
@@ -466,8 +504,8 @@ defmodule OptionParser do
|
||||
|
||||
"""
|
||||
@spec to_argv(Enumerable.t(), options) :: argv
|
||||
def to_argv(enum, opts \\ []) do
|
||||
switches = Keyword.get(opts, :switches, [])
|
||||
def to_argv(enum, options \\ []) do
|
||||
switches = Keyword.get(options, :switches, [])
|
||||
|
||||
Enum.flat_map(enum, fn
|
||||
{_key, nil} -> []
|
||||
@@ -559,7 +597,7 @@ defmodule OptionParser do
|
||||
|
||||
true ->
|
||||
# TODO: Remove this in Elixir v2.0
|
||||
IO.warn("Not passing the :switches or :strict option to OptionParser is deprecated")
|
||||
IO.warn("not passing the :switches or :strict option to OptionParser is deprecated")
|
||||
{[], false}
|
||||
end
|
||||
|
||||
|
||||
+14
-8
@@ -12,7 +12,7 @@ defmodule Path do
|
||||
that require it (like `wildcard/2` and `expand/1`).
|
||||
"""
|
||||
|
||||
@type t :: :unicode.chardata()
|
||||
@type t :: IO.chardata()
|
||||
|
||||
@doc """
|
||||
Converts the given path to an absolute one. Unlike
|
||||
@@ -30,15 +30,16 @@ defmodule Path do
|
||||
|
||||
### Windows
|
||||
|
||||
Path.absname("foo").
|
||||
Path.absname("foo")
|
||||
#=> "D:/usr/local/foo"
|
||||
Path.absname("../x").
|
||||
|
||||
Path.absname("../x")
|
||||
#=> "D:/usr/local/../x"
|
||||
|
||||
"""
|
||||
@spec absname(t) :: binary
|
||||
def absname(path) do
|
||||
absname(path, System.cwd!())
|
||||
absname(path, File.cwd!())
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -150,7 +151,7 @@ defmodule Path do
|
||||
"""
|
||||
@spec expand(t) :: binary
|
||||
def expand(path) do
|
||||
expand_dot(absname(expand_home(path), System.cwd!()))
|
||||
expand_dot(absname(expand_home(path), File.cwd!()))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -171,14 +172,15 @@ defmodule Path do
|
||||
#=> "/quux/baz/foo/bar"
|
||||
|
||||
Path.expand("foo/bar/../bar", "/baz")
|
||||
"/baz/foo/bar"
|
||||
#=> "/baz/foo/bar"
|
||||
|
||||
Path.expand("/foo/bar/../bar", "/baz")
|
||||
"/foo/bar"
|
||||
#=> "/foo/bar"
|
||||
|
||||
"""
|
||||
@spec expand(t, t) :: binary
|
||||
def expand(path, relative_to) do
|
||||
expand_dot(absname(absname(expand_home(path), expand_home(relative_to)), System.cwd!()))
|
||||
expand_dot(absname(absname(expand_home(path), expand_home(relative_to)), File.cwd!()))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -616,6 +618,10 @@ defmodule Path do
|
||||
exactly the same character in the same position will match. Note
|
||||
that matching is case-sensitive: `"a"` will not match `"A"`.
|
||||
|
||||
Directory separators must always be written as `/`, even on Windows.
|
||||
You may call `Path.expand/1` to normalize the path before invoking
|
||||
this function.
|
||||
|
||||
By default, the patterns `*` and `?` do not match files starting
|
||||
with a dot `.`. See the `:match_dot` option in the "Options" section
|
||||
below.
|
||||
|
||||
+14
-10
@@ -127,11 +127,11 @@ defmodule Port do
|
||||
While most UNIX command line tools will exit once its communication channels
|
||||
are closed, not all command line applications will do so. While we encourage
|
||||
graceful termination by detecting if stdin/stdout has been closed, we do not
|
||||
always have control over how 3rd party software terminates. In those cases,
|
||||
always have control over how third-party software terminates. In those cases,
|
||||
you can wrap the application in a script that checks for stdin. Here is such
|
||||
script in bash:
|
||||
script in Bash:
|
||||
|
||||
#!/bin/sh
|
||||
#!/bin/bash
|
||||
"$@" &
|
||||
pid=$!
|
||||
while read line ; do
|
||||
@@ -141,13 +141,17 @@ defmodule Port do
|
||||
|
||||
Now instead of:
|
||||
|
||||
Port.open({:spawn_executable, "/path/to/program"},
|
||||
[args: ["a", "b", "c"]])
|
||||
Port.open(
|
||||
{:spawn_executable, "/path/to/program"},
|
||||
args: ["a", "b", "c"]
|
||||
)
|
||||
|
||||
You may invoke:
|
||||
|
||||
Port.open({:spawn_executable, "/path/to/wrapper"},
|
||||
[args: ["/path/to/program", "a", "b", "c"]])
|
||||
Port.open(
|
||||
{:spawn_executable, "/path/to/wrapper"},
|
||||
args: ["/path/to/program", "a", "b", "c"]
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
@@ -261,12 +265,12 @@ defmodule Port do
|
||||
or `{name, node}` (when monitoring by a port name);
|
||||
* `reason` is the exit reason.
|
||||
|
||||
See `:erlang.monitor/2` for more info.
|
||||
See `:erlang.monitor/2` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@doc since: "1.6.0"
|
||||
@spec monitor(port | {name :: atom, node :: atom} | name :: atom) :: reference
|
||||
@spec monitor(port | {name, node} | name) :: reference when name: atom
|
||||
def monitor(port) do
|
||||
:erlang.monitor(:port, port)
|
||||
end
|
||||
@@ -278,7 +282,7 @@ defmodule Port do
|
||||
obtained by calling `monitor/1`, that monitoring is turned off.
|
||||
If the monitoring is already turned off, nothing happens.
|
||||
|
||||
See `:erlang.demonitor/2` for more info.
|
||||
See `:erlang.demonitor/2` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
|
||||
+150
-45
@@ -14,11 +14,19 @@ defmodule Process do
|
||||
|
||||
While this module provides low-level conveniences to work with processes,
|
||||
developers typically use abstractions such as `Agent`, `GenServer`,
|
||||
`Registry`, `Supervisor` and `Task` for building their systems and
|
||||
`Registry`, `Supervisor` and `Task` for building their systems and
|
||||
resort to this module for gathering information, trapping exits, links
|
||||
and monitoring.
|
||||
"""
|
||||
|
||||
@typedoc """
|
||||
A process destination.
|
||||
|
||||
A remote or local PID, a local port, a locally registered name, or a tuple in
|
||||
the form of `{registered_name, node}` for a registered name at another node.
|
||||
"""
|
||||
@type dest :: pid | port | (registered_name :: atom) | {registered_name :: atom, node}
|
||||
|
||||
@doc """
|
||||
Tells whether the given process is alive on the local node.
|
||||
|
||||
@@ -30,15 +38,6 @@ defmodule Process do
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
|
||||
@typedoc """
|
||||
A process destination.
|
||||
|
||||
A remote or local PID, a local port, a locally registered name, or a tuple in
|
||||
the form of `{registered_name, node}` for a registered name at another node.
|
||||
"""
|
||||
@type dest :: pid | port | registered_name :: atom | {registered_name :: atom, node}
|
||||
|
||||
@spec alive?(pid) :: boolean
|
||||
defdelegate alive?(pid), to: :erlang, as: :is_process_alive
|
||||
|
||||
@@ -53,6 +52,17 @@ defmodule Process do
|
||||
@doc """
|
||||
Returns the value for the given `key` in the process dictionary,
|
||||
or `default` if `key` is not set.
|
||||
|
||||
## Examples
|
||||
|
||||
# Assuming :locale was not set
|
||||
iex> Process.get(:locale, "pt")
|
||||
"pt"
|
||||
iex> Process.put(:locale, "fr")
|
||||
nil
|
||||
iex> Process.get(:locale, "pt")
|
||||
"fr"
|
||||
|
||||
"""
|
||||
@spec get(term, default :: term) :: term
|
||||
def get(key, default \\ nil) do
|
||||
@@ -66,6 +76,17 @@ defmodule Process do
|
||||
Returns all keys in the process dictionary.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
# Assuming :locale was not set
|
||||
iex> :locale in Process.get_keys()
|
||||
false
|
||||
iex> Process.put(:locale, "pt")
|
||||
nil
|
||||
iex> :locale in Process.get_keys()
|
||||
true
|
||||
|
||||
"""
|
||||
@spec get_keys() :: [term]
|
||||
defdelegate get_keys(), to: :erlang
|
||||
@@ -82,15 +103,15 @@ defmodule Process do
|
||||
Stores the given `key`-`value` pair in the process dictionary.
|
||||
|
||||
The return value of this function is the value that was previously stored
|
||||
under `key`, or `nil` in case no value was stored under `key`.
|
||||
under `key`, or `nil` in case no value was stored under it.
|
||||
|
||||
## Examples
|
||||
|
||||
# Assuming :locale was not set
|
||||
Process.put(:locale, "en")
|
||||
#=> nil
|
||||
Process.put(:locale, "fr")
|
||||
#=> "en"
|
||||
iex> Process.put(:locale, "en")
|
||||
nil
|
||||
iex> Process.put(:locale, "fr")
|
||||
"en"
|
||||
|
||||
"""
|
||||
@spec put(term, term) :: term | nil
|
||||
@@ -106,11 +127,11 @@ defmodule Process do
|
||||
|
||||
## Examples
|
||||
|
||||
Process.put(:comments, ["comment", "other comment"])
|
||||
Process.delete(:comments)
|
||||
#=> ["comment", "other comment"]
|
||||
Process.delete(:comments)
|
||||
#=> nil
|
||||
iex> Process.put(:comments, ["comment", "other comment"])
|
||||
iex> Process.delete(:comments)
|
||||
["comment", "other comment"]
|
||||
iex> Process.delete(:comments)
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec delete(term) :: term | nil
|
||||
@@ -170,10 +191,10 @@ defmodule Process do
|
||||
|
||||
In other words, **do not**:
|
||||
|
||||
Task.start_link fn ->
|
||||
Task.start_link(fn ->
|
||||
do_something()
|
||||
...
|
||||
end
|
||||
end)
|
||||
|
||||
# Wait until work is done
|
||||
Process.sleep(2000)
|
||||
@@ -181,16 +202,18 @@ defmodule Process do
|
||||
But **do**:
|
||||
|
||||
parent = self()
|
||||
Task.start_link fn ->
|
||||
|
||||
Task.start_link(fn ->
|
||||
do_something()
|
||||
send parent, :work_is_done
|
||||
send(parent, :work_is_done)
|
||||
...
|
||||
end
|
||||
end)
|
||||
|
||||
receive do
|
||||
:work_is_done -> :ok
|
||||
after
|
||||
30_000 -> :timeout # Optional timeout
|
||||
# Optional timeout
|
||||
30_000 -> :timeout
|
||||
end
|
||||
|
||||
For cases like the one above, `Task.async/1` and `Task.await/2` are
|
||||
@@ -199,9 +222,9 @@ defmodule Process do
|
||||
Similarly, if you are waiting for a process to terminate,
|
||||
monitor that process instead of sleeping. **Do not**:
|
||||
|
||||
Task.start_link fn ->
|
||||
Task.start_link(fn ->
|
||||
...
|
||||
end
|
||||
end)
|
||||
|
||||
# Wait until task terminates
|
||||
Process.sleep(2000)
|
||||
@@ -209,15 +232,17 @@ defmodule Process do
|
||||
Instead **do**:
|
||||
|
||||
{:ok, pid} =
|
||||
Task.start_link fn ->
|
||||
Task.start_link(fn ->
|
||||
...
|
||||
end
|
||||
end)
|
||||
|
||||
ref = Process.monitor(pid)
|
||||
|
||||
receive do
|
||||
{:DOWN, ^ref, _, _, _} -> :task_is_down
|
||||
after
|
||||
30_000 -> :timeout # Optional timeout
|
||||
# Optional timeout
|
||||
30_000 -> :timeout
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -268,6 +293,9 @@ defmodule Process do
|
||||
which is looked up at the time of delivery. No error is produced if the name does
|
||||
not refer to a process.
|
||||
|
||||
The message is not sent immediately. Therefore, `dest` can receive other messages
|
||||
in-between even when `time` is `0`.
|
||||
|
||||
This function returns a timer reference, which can be read with `read_timer/1`
|
||||
or canceled with `cancel_timer/1`.
|
||||
|
||||
@@ -373,6 +401,14 @@ defmodule Process do
|
||||
check `:erlang.spawn_opt/4`.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.spawn(fn -> 1 + 2 end, [:monitor])
|
||||
#=> {#PID<0.93.0>, #Reference<0.18808174.1939079169.202418>}
|
||||
Process.spawn(fn -> 1 + 2 end, [:link])
|
||||
#=> #PID<0.95.0>
|
||||
|
||||
"""
|
||||
@spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}
|
||||
defdelegate spawn(fun, opts), to: :erlang, as: :spawn_opt
|
||||
@@ -412,12 +448,26 @@ defmodule Process do
|
||||
If the process is already dead when calling `Process.monitor/1`, a
|
||||
`:DOWN` message is delivered immediately.
|
||||
|
||||
See [the need for monitoring](http://elixir-lang.org/getting-started/mix-otp/genserver.html#the-need-for-monitoring)
|
||||
for an example. See `:erlang.monitor/2` for more info.
|
||||
See [the need for monitoring](https://elixir-lang.org/getting-started/mix-otp/genserver.html#the-need-for-monitoring)
|
||||
for an example. See `:erlang.monitor/2` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
pid = spawn(fn -> 1 + 2 end)
|
||||
#=> #PID<0.118.0>
|
||||
Process.monitor(pid)
|
||||
#=> #Reference<0.906660723.3006791681.40191>
|
||||
Process.exit(pid, :kill)
|
||||
#=> true
|
||||
receive do
|
||||
msg -> msg
|
||||
end
|
||||
#=> {:DOWN, #Reference<0.906660723.3006791681.40191>, :process, #PID<0.118.0>, :noproc}
|
||||
|
||||
"""
|
||||
@spec monitor(pid | {name :: atom, node :: atom} | name :: atom) :: reference
|
||||
@spec monitor(pid | {name, node} | name) :: reference when name: atom
|
||||
def monitor(item) do
|
||||
:erlang.monitor(:process, item)
|
||||
end
|
||||
@@ -429,9 +479,17 @@ defmodule Process do
|
||||
obtained by calling `monitor/1`, that monitoring is turned off.
|
||||
If the monitoring is already turned off, nothing happens.
|
||||
|
||||
See `:erlang.demonitor/2` for more info.
|
||||
See `:erlang.demonitor/2` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
pid = spawn(fn -> 1 + 2 end)
|
||||
ref = Process.monitor(pid)
|
||||
Process.demonitor(ref)
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@spec demonitor(reference, options :: [:flush | :info]) :: boolean
|
||||
defdelegate demonitor(monitor_ref, options \\ []), to: :erlang
|
||||
@@ -444,9 +502,15 @@ defmodule Process do
|
||||
alive. This means that for such process, `alive?/1` will return `false` but
|
||||
its PID will be part of the list of PIDs returned by this function.
|
||||
|
||||
See `:erlang.processes/0` for more info.
|
||||
See `:erlang.processes/0` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.list()
|
||||
#=> [#PID<0.0.0>, #PID<0.1.0>, #PID<0.2.0>, #PID<0.3.0>, ...]
|
||||
|
||||
"""
|
||||
@spec list() :: [pid]
|
||||
defdelegate list(), to: :erlang, as: :processes
|
||||
@@ -469,7 +533,7 @@ defmodule Process do
|
||||
emit an exit signal to all its other linked processes. The behaviour when
|
||||
`pid1` is trapping exits is described in `exit/2`.
|
||||
|
||||
See `:erlang.link/1` for more info.
|
||||
See `:erlang.link/1` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -485,7 +549,7 @@ defmodule Process do
|
||||
|
||||
The return value of this function is always `true`.
|
||||
|
||||
See `:erlang.unlink/1` for more info.
|
||||
See `:erlang.unlink/1` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -512,6 +576,15 @@ defmodule Process do
|
||||
* `true`
|
||||
* `:undefined`
|
||||
|
||||
## Examples
|
||||
|
||||
Process.register(self(), :test)
|
||||
#=> true
|
||||
send(:test, :hello)
|
||||
#=> :hello
|
||||
send(:wrong_name, :hello)
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec register(pid | port, atom) :: true
|
||||
def register(pid_or_port, name)
|
||||
@@ -539,6 +612,16 @@ defmodule Process do
|
||||
to any PID or port.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.register(self(), :test)
|
||||
#=> true
|
||||
Process.unregister(:test)
|
||||
#=> true
|
||||
Process.unregister(:wrong_name)
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec unregister(atom) :: true
|
||||
defdelegate unregister(name), to: :erlang
|
||||
@@ -547,7 +630,16 @@ defmodule Process do
|
||||
Returns the PID or port identifier registered under `name` or `nil` if the
|
||||
name is not registered.
|
||||
|
||||
See `:erlang.whereis/1` for more info.
|
||||
See `:erlang.whereis/1` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.register(self(), :test)
|
||||
Process.whereis(:test)
|
||||
#=> #PID<0.84.0>
|
||||
Process.whereis(:wrong_name)
|
||||
#=> nil
|
||||
|
||||
"""
|
||||
@spec whereis(atom) :: pid | port | nil
|
||||
def whereis(name) do
|
||||
@@ -558,6 +650,12 @@ defmodule Process do
|
||||
Returns the PID of the group leader for the calling process.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.group_leader()
|
||||
#=> #PID<0.53.0>
|
||||
|
||||
"""
|
||||
@spec group_leader() :: pid
|
||||
defdelegate group_leader(), to: :erlang
|
||||
@@ -579,6 +677,13 @@ defmodule Process do
|
||||
Returns a list of names which have been registered using `register/2`.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.register(self(), :test)
|
||||
Process.registered()
|
||||
#=> [:test, :elixir_config, :inet_db, ...]
|
||||
|
||||
"""
|
||||
@spec registered() :: [atom]
|
||||
defdelegate registered(), to: :erlang
|
||||
@@ -594,7 +699,7 @@ defmodule Process do
|
||||
|
||||
Returns the old value of `flag`.
|
||||
|
||||
See `:erlang.process_flag/2` for more info.
|
||||
See `:erlang.process_flag/2` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -621,7 +726,7 @@ defmodule Process do
|
||||
The allowed values for `flag` are only a subset of those allowed in `flag/2`,
|
||||
namely `:save_calls`.
|
||||
|
||||
See `:erlang.process_flag/3` for more info.
|
||||
See `:erlang.process_flag/3` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -634,9 +739,9 @@ defmodule Process do
|
||||
|
||||
Use this only for debugging information.
|
||||
|
||||
See `:erlang.process_info/1` for more info.
|
||||
See `:erlang.process_info/1` for more information.
|
||||
"""
|
||||
@spec info(pid) :: keyword
|
||||
@spec info(pid) :: keyword | nil
|
||||
def info(pid) do
|
||||
nillify(:erlang.process_info(pid))
|
||||
end
|
||||
@@ -645,7 +750,7 @@ defmodule Process do
|
||||
Returns information about the process identified by `pid`,
|
||||
or returns `nil` if the process is not alive.
|
||||
|
||||
See `:erlang.process_info/2` for more info.
|
||||
See `:erlang.process_info/2` for more information.
|
||||
"""
|
||||
@spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil
|
||||
def info(pid, spec)
|
||||
@@ -670,7 +775,7 @@ defmodule Process do
|
||||
which is useful if the process does not expect to receive any messages
|
||||
in the near future.
|
||||
|
||||
See `:erlang.hibernate/3` for more info.
|
||||
See `:erlang.hibernate/3` for more information.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
|
||||
+79
-154
@@ -22,7 +22,7 @@ defmodule Protocol do
|
||||
type_args = :lists.map(fn _ -> quote(do: term) end, :lists.seq(2, arity))
|
||||
type_args = [quote(do: t) | type_args]
|
||||
|
||||
varify = fn pos -> Macro.var(String.to_atom("var" <> Integer.to_string(pos)), __MODULE__) end
|
||||
varify = fn pos -> Macro.var(String.to_atom("arg" <> Integer.to_string(pos)), __MODULE__) end
|
||||
|
||||
call_args = :lists.map(varify, :lists.seq(2, arity))
|
||||
call_args = [quote(do: term) | call_args]
|
||||
@@ -58,7 +58,7 @@ defmodule Protocol do
|
||||
|
||||
Returns `:ok` if so, otherwise raises `ArgumentError`.
|
||||
"""
|
||||
@spec assert_protocol!(module) :: :ok | no_return
|
||||
@spec assert_protocol!(module) :: :ok
|
||||
def assert_protocol!(module) do
|
||||
assert_protocol!(module, "")
|
||||
end
|
||||
@@ -85,7 +85,7 @@ defmodule Protocol do
|
||||
|
||||
Returns `:ok` if so, otherwise raises `ArgumentError`.
|
||||
"""
|
||||
@spec assert_impl!(module, module) :: :ok | no_return
|
||||
@spec assert_impl!(module, module) :: :ok
|
||||
def assert_impl!(protocol, base) do
|
||||
assert_impl!(protocol, base, "")
|
||||
end
|
||||
@@ -168,8 +168,7 @@ defmodule Protocol do
|
||||
"""
|
||||
defmacro derive(protocol, module, options \\ []) do
|
||||
quote do
|
||||
module = unquote(module)
|
||||
Protocol.__derive__([{unquote(protocol), unquote(options)}], module, __ENV__)
|
||||
Protocol.__derive__([{unquote(protocol), unquote(options)}], unquote(module), __ENV__)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -186,7 +185,7 @@ defmodule Protocol do
|
||||
|
||||
## Examples
|
||||
|
||||
# Get Elixir's ebin and retrieve all protocols
|
||||
# Get Elixir's ebin directory path and retrieve all protocols
|
||||
iex> path = :code.lib_dir(:elixir, :ebin)
|
||||
iex> mods = Protocol.extract_protocols([path])
|
||||
iex> Enumerable in mods
|
||||
@@ -215,7 +214,7 @@ defmodule Protocol do
|
||||
|
||||
## Examples
|
||||
|
||||
# Get Elixir's ebin and retrieve all protocols
|
||||
# Get Elixir's ebin directory path and retrieve all protocols
|
||||
iex> path = :code.lib_dir(:elixir, :ebin)
|
||||
iex> mods = Protocol.extract_impls(Enumerable, [path])
|
||||
iex> List in mods
|
||||
@@ -284,15 +283,15 @@ defmodule Protocol do
|
||||
are retrieved with the help of `extract_impls/2`.
|
||||
|
||||
It returns the updated version of the protocol bytecode.
|
||||
If the first element of the tuple is `:ok`, it means
|
||||
the protocol was consolidated.
|
||||
|
||||
A given bytecode or protocol implementation can be checked
|
||||
to be consolidated or not by analyzing the protocol
|
||||
attribute:
|
||||
|
||||
Protocol.consolidated?(Enumerable)
|
||||
|
||||
If the first element of the tuple is `true`, it means
|
||||
the protocol was consolidated.
|
||||
|
||||
This function does not load the protocol at any point
|
||||
nor loads the new bytecode for the compiled module.
|
||||
However each implementation must be available and
|
||||
@@ -303,30 +302,24 @@ defmodule Protocol do
|
||||
| {:error, :not_a_protocol}
|
||||
| {:error, :no_beam_info}
|
||||
def consolidate(protocol, types) when is_atom(protocol) do
|
||||
with {:ok, ast_info, chunks_info} <- beam_protocol(protocol),
|
||||
{:ok, code} <- change_debug_info(ast_info, types),
|
||||
do: compile(protocol, code, chunks_info)
|
||||
with {:ok, ast_info, specs, compile_info} <- beam_protocol(protocol),
|
||||
{:ok, definitions} <- change_debug_info(protocol, ast_info, types),
|
||||
do: compile(definitions, specs, compile_info)
|
||||
end
|
||||
|
||||
defp beam_protocol(protocol) do
|
||||
chunk_ids = [:abstract_code, :attributes, :compile_info, 'Docs', 'ExDp']
|
||||
chunk_ids = [:debug_info, 'Docs', 'ExDp']
|
||||
opts = [:allow_missing_chunks]
|
||||
|
||||
case :beam_lib.chunks(beam_file(protocol), chunk_ids, opts) do
|
||||
{:ok, {^protocol, entries}} ->
|
||||
[
|
||||
{:abstract_code, {_raw, abstract_code}},
|
||||
{:attributes, attributes},
|
||||
{:compile_info, compile_info} | extra_chunks
|
||||
] = entries
|
||||
|
||||
extra_chunks =
|
||||
for {name, contents} when is_binary(contents) <- extra_chunks,
|
||||
do: {List.to_string(name), contents}
|
||||
{:ok, {^protocol, [{:debug_info, debug_info} | chunks]}} ->
|
||||
{:debug_info_v1, _backend, {:elixir_v1, info, specs}} = debug_info
|
||||
%{attributes: attributes, definitions: definitions} = info
|
||||
chunks = :lists.map(fn {name, value} -> {List.to_string(name), value} end, chunks)
|
||||
|
||||
case attributes[:protocol] do
|
||||
[fallback_to_any: any] ->
|
||||
{:ok, {protocol, any, abstract_code}, {compile_info, extra_chunks}}
|
||||
{:ok, {any, definitions}, specs, {info, chunks}}
|
||||
|
||||
_ ->
|
||||
{:error, :not_a_protocol}
|
||||
@@ -346,148 +339,83 @@ defmodule Protocol do
|
||||
|
||||
# Change the debug information to the optimized
|
||||
# impl_for/1 dispatch version.
|
||||
defp change_debug_info({protocol, any, code}, types) do
|
||||
defp change_debug_info(protocol, {any, definitions}, types) do
|
||||
types = if any, do: types, else: List.delete(types, Any)
|
||||
all = [Any] ++ for {_guard, mod} <- __builtin__(), do: mod
|
||||
all = [Any] ++ for {_guard, mod} <- __built_in__(), do: mod
|
||||
structs = types -- all
|
||||
|
||||
case change_impl_for(code, protocol, types, structs, false, []) do
|
||||
{:ok, ret} -> {:ok, ret}
|
||||
other -> other
|
||||
case List.keytake(definitions, {:__protocol__, 1}, 0) do
|
||||
{protocol_def, definitions} ->
|
||||
{impl_for, definitions} = List.keytake(definitions, {:impl_for, 1}, 0)
|
||||
{struct_impl_for, definitions} = List.keytake(definitions, {:struct_impl_for, 1}, 0)
|
||||
|
||||
protocol_def = change_protocol(protocol_def, types)
|
||||
impl_for = change_impl_for(impl_for, protocol, types)
|
||||
struct_impl_for = change_struct_impl_for(struct_impl_for, protocol, types, structs)
|
||||
|
||||
{:ok, [protocol_def, impl_for, struct_impl_for] ++ definitions}
|
||||
|
||||
nil ->
|
||||
{:error, :not_a_protocol}
|
||||
end
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:function, line, :__protocol__, 1, clauses} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
_,
|
||||
acc
|
||||
) do
|
||||
abstract_types = :erl_parse.abstract(:lists.usort(types))
|
||||
|
||||
defp change_protocol({_name, _kind, meta, clauses}, types) do
|
||||
clauses =
|
||||
Enum.map(clauses, fn
|
||||
{:clause, l, [{:atom, _, :consolidated?}], [], [{:atom, _, _}]} ->
|
||||
{:clause, l, [{:atom, 0, :consolidated?}], [], [{:atom, 0, true}]}
|
||||
|
||||
{:clause, l, [{:atom, _, :impls}], [], [{:atom, _, _}]} ->
|
||||
tuple = {:tuple, 0, [{:atom, 0, :consolidated}, abstract_types]}
|
||||
{:clause, l, [{:atom, 0, :impls}], [], [tuple]}
|
||||
|
||||
{:clause, _, _, _, _} = c ->
|
||||
c
|
||||
{meta, [:consolidated?], [], _} -> {meta, [:consolidated?], [], true}
|
||||
{meta, [:impls], [], _} -> {meta, [:impls], [], {:consolidated, types}}
|
||||
clause -> clause
|
||||
end)
|
||||
|
||||
acc = [{:function, line, :__protocol__, 1, clauses} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, true, acc)
|
||||
{{:__protocol__, 1}, :def, meta, clauses}
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:function, line, :impl_for, 1, _} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
protocol?,
|
||||
acc
|
||||
) do
|
||||
defp change_impl_for({_name, _kind, meta, _clauses}, protocol, types) do
|
||||
fallback = if Any in types, do: load_impl(protocol, Any)
|
||||
line = meta[:line]
|
||||
|
||||
clauses =
|
||||
for {guard, mod} <- __builtin__(),
|
||||
for {guard, mod} <- __built_in__(),
|
||||
mod in types,
|
||||
do: builtin_clause_for(mod, guard, protocol, line)
|
||||
do: built_in_clause_for(mod, guard, protocol, meta, line)
|
||||
|
||||
clauses =
|
||||
[struct_clause_for(line) | clauses] ++ [fallback_clause_for(fallback, protocol, line)]
|
||||
struct_clause = struct_clause_for(meta, line)
|
||||
fallback_clause = fallback_clause_for(fallback, protocol, meta)
|
||||
clauses = [struct_clause] ++ clauses ++ [fallback_clause]
|
||||
|
||||
acc = [{:function, line, :impl_for, 1, clauses} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, protocol?, acc)
|
||||
{{:impl_for, 1}, :def, meta, clauses}
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:function, line, :struct_impl_for, 1, _} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
protocol?,
|
||||
acc
|
||||
) do
|
||||
defp change_struct_impl_for({_name, _kind, meta, _clauses}, protocol, types, structs) do
|
||||
fallback = if Any in types, do: load_impl(protocol, Any)
|
||||
clauses = for struct <- structs, do: each_struct_clause_for(struct, protocol, line)
|
||||
clauses = clauses ++ [fallback_clause_for(fallback, protocol, line)]
|
||||
clauses = for struct <- structs, do: each_struct_clause_for(struct, protocol, meta)
|
||||
clauses = clauses ++ [fallback_clause_for(fallback, protocol, meta)]
|
||||
|
||||
acc = [{:function, line, :struct_impl_for, 1, clauses} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, protocol?, acc)
|
||||
{{:struct_impl_for, 1}, :defp, meta, clauses}
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:attribute, line, :spec, {{:__protocol__, 1}, funspecs}} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
protocol?,
|
||||
acc
|
||||
) do
|
||||
new_specs =
|
||||
for spec <- funspecs do
|
||||
case spec do
|
||||
{:type, line, :fun, [{:type, _, :product, [{:atom, _, :consolidated?}]}, _]} ->
|
||||
product = {:type, line, :product, [{:atom, 0, :consolidated?}]}
|
||||
{:type, line, :fun, [product, {:atom, 0, true}]}
|
||||
|
||||
{:type, line, :fun, [{:type, _, :product, [{:atom, _, :impls}]}, _]} ->
|
||||
impls = for mod <- types, do: {:atom, 0, mod}
|
||||
list = {:type, 0, :list, [{:type, 0, :union, impls}]}
|
||||
tuple = {:type, 0, :tuple, [{:atom, 0, :consolidated}, list]}
|
||||
{:type, line, :fun, [{:type, line, :product, [{:atom, 0, :impls}]}, tuple]}
|
||||
|
||||
other ->
|
||||
other
|
||||
end
|
||||
end
|
||||
|
||||
acc = [{:attribute, line, :spec, {{:__protocol__, 1}, new_specs}} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, protocol?, acc)
|
||||
defp built_in_clause_for(mod, guard, protocol, meta, line) do
|
||||
x = quote(line: line, do: x)
|
||||
guard = quote(line: line, do: :erlang.unquote(guard)(unquote(x)))
|
||||
body = load_impl(protocol, mod)
|
||||
{meta, [x], [guard], body}
|
||||
end
|
||||
|
||||
defp change_impl_for([head | tail], protocol, info, types, protocol?, acc) do
|
||||
change_impl_for(tail, protocol, info, types, protocol?, [head | acc])
|
||||
defp struct_clause_for(meta, line) do
|
||||
x = quote(line: line, do: x)
|
||||
head = quote(line: line, do: %{__struct__: unquote(x)})
|
||||
guard = quote(line: line, do: :erlang.is_atom(unquote(x)))
|
||||
body = quote(line: line, do: struct_impl_for(unquote(x)))
|
||||
{meta, [head], [guard], body}
|
||||
end
|
||||
|
||||
defp change_impl_for([], _protocol, _info, _types, protocol?, acc) do
|
||||
if protocol? do
|
||||
{:ok, Enum.reverse(acc)}
|
||||
else
|
||||
{:error, :not_a_protocol}
|
||||
end
|
||||
defp each_struct_clause_for(struct, protocol, meta) do
|
||||
{meta, [struct], [], load_impl(protocol, struct)}
|
||||
end
|
||||
|
||||
defp builtin_clause_for(mod, guard, protocol, line) do
|
||||
remote = {:remote, line, {:atom, line, :erlang}, {:atom, line, guard}}
|
||||
guard = {:call, line, remote, [{:var, line, :x}]}
|
||||
body = {:atom, line, load_impl(protocol, mod)}
|
||||
{:clause, line, [{:var, line, :x}], [[guard]], [body]}
|
||||
end
|
||||
|
||||
defp struct_clause_for(line) do
|
||||
map_field_exact = {:map_field_exact, line, {:atom, line, :__struct__}, {:var, line, :x}}
|
||||
arg = {:map, line, [map_field_exact]}
|
||||
|
||||
is_atom = {:remote, line, {:atom, line, :erlang}, {:atom, line, :is_atom}}
|
||||
guard = {:call, line, is_atom, [{:var, line, :x}]}
|
||||
|
||||
body = {:call, line, {:atom, line, :struct_impl_for}, [{:var, line, :x}]}
|
||||
{:clause, line, [arg], [[guard]], [body]}
|
||||
end
|
||||
|
||||
defp each_struct_clause_for(struct, protocol, line) do
|
||||
{:clause, line, [{:atom, line, struct}], [], [{:atom, line, load_impl(protocol, struct)}]}
|
||||
end
|
||||
|
||||
defp fallback_clause_for(value, _protocol, line) do
|
||||
{:clause, line, [{:var, line, :_}], [], [{:atom, line, value}]}
|
||||
defp fallback_clause_for(value, _protocol, meta) do
|
||||
{meta, [quote(do: _)], [], value}
|
||||
end
|
||||
|
||||
defp load_impl(protocol, for) do
|
||||
@@ -495,11 +423,9 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
# Finally compile the module and emit its bytecode.
|
||||
defp compile(protocol, code, {compile_info, extra_chunks}) do
|
||||
opts = Keyword.take(compile_info, [:source])
|
||||
opts = if Code.compiler_options()[:debug_info], do: [:debug_info | opts], else: opts
|
||||
{:ok, ^protocol, binary, _warnings} = :compile.forms(code, [:return | opts])
|
||||
{:ok, :elixir_erl.add_beam_chunks(binary, extra_chunks)}
|
||||
defp compile(definitions, specs, {info, chunks}) do
|
||||
info = %{info | definitions: definitions}
|
||||
{:ok, :elixir_erl.consolidate(info, specs, chunks)}
|
||||
end
|
||||
|
||||
## Definition callbacks
|
||||
@@ -541,7 +467,7 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
defp after_defprotocol do
|
||||
quote bind_quoted: [builtin: __builtin__()] do
|
||||
quote bind_quoted: [built_in: __built_in__()] do
|
||||
any_impl_for =
|
||||
if @fallback_to_any do
|
||||
quote do: unquote(__MODULE__.Any).__impl__(:target)
|
||||
@@ -549,6 +475,10 @@ defmodule Protocol do
|
||||
nil
|
||||
end
|
||||
|
||||
# Disable dialyzer checks - before and after consolidation
|
||||
# the types could be more strict
|
||||
@dialyzer {:nowarn_function, __protocol__: 1, impl_for: 1, impl_for!: 1}
|
||||
|
||||
@doc false
|
||||
@spec impl_for(term) :: atom | nil
|
||||
Kernel.def(impl_for(data))
|
||||
@@ -557,7 +487,7 @@ defmodule Protocol do
|
||||
#
|
||||
# It simply delegates to struct_impl_for which is then
|
||||
# optimized during protocol consolidation.
|
||||
Kernel.def impl_for(%{__struct__: struct}) when :erlang.is_atom(struct) do
|
||||
Kernel.def impl_for(%struct{}) do
|
||||
struct_impl_for(struct)
|
||||
end
|
||||
|
||||
@@ -574,7 +504,7 @@ defmodule Protocol do
|
||||
end
|
||||
end
|
||||
end,
|
||||
builtin
|
||||
built_in
|
||||
)
|
||||
|
||||
# Define a catch-all impl_for/1 clause to pacify Dialyzer (since
|
||||
@@ -624,8 +554,8 @@ defmodule Protocol do
|
||||
@doc false
|
||||
@spec __protocol__(:module) :: __MODULE__
|
||||
@spec __protocol__(:functions) :: unquote(Protocol.__functions_spec__(@functions))
|
||||
@spec __protocol__(:consolidated?) :: false
|
||||
@spec __protocol__(:impls) :: :not_consolidated
|
||||
@spec __protocol__(:consolidated?) :: boolean
|
||||
@spec __protocol__(:impls) :: :not_consolidated | {:consolidated, [module]}
|
||||
Kernel.def(__protocol__(:module), do: __MODULE__)
|
||||
Kernel.def(__protocol__(:functions), do: unquote(:lists.sort(@functions)))
|
||||
Kernel.def(__protocol__(:consolidated?), do: false)
|
||||
@@ -688,12 +618,7 @@ defmodule Protocol do
|
||||
|
||||
@doc false
|
||||
def __derive__(derives, for, %Macro.Env{} = env) when is_atom(for) do
|
||||
struct =
|
||||
if for == env.module do
|
||||
Module.get_attribute(for, :struct) || raise "struct is not defined for #{inspect(for)}"
|
||||
else
|
||||
for.__struct__
|
||||
end
|
||||
struct = Macro.struct!(for, env)
|
||||
|
||||
foreach = fn
|
||||
proto when is_atom(proto) ->
|
||||
@@ -760,7 +685,7 @@ defmodule Protocol do
|
||||
## Helpers
|
||||
|
||||
@doc false
|
||||
def __builtin__ do
|
||||
def __built_in__ do
|
||||
[
|
||||
is_tuple: Tuple,
|
||||
is_atom: Atom,
|
||||
|
||||
+35
-4
@@ -2,8 +2,8 @@ defmodule Range do
|
||||
@moduledoc """
|
||||
Defines a range.
|
||||
|
||||
A range represents a discrete number of values where
|
||||
the first and last values are integers.
|
||||
A range represents a sequence of one or many,
|
||||
ascending or descending, consecutive integers.
|
||||
|
||||
Ranges can be either increasing (`first <= last`) or
|
||||
decreasing (`first > last`). Ranges are also always
|
||||
@@ -36,12 +36,16 @@ defmodule Range do
|
||||
iex> Enum.member?(range, 8)
|
||||
true
|
||||
|
||||
Such function calls are efficient memory-wise no matter the
|
||||
size of the range. The implementation of the `Enumerable`
|
||||
protocol uses logic based solely on the endpoints and does
|
||||
not materialize the whole list of integers.
|
||||
"""
|
||||
|
||||
defstruct first: nil, last: nil
|
||||
|
||||
@type t :: %Range{first: integer, last: integer}
|
||||
@type t(first, last) :: %Range{first: first, last: last}
|
||||
@type t :: %__MODULE__{first: integer, last: integer}
|
||||
@type t(first, last) :: %__MODULE__{first: first, last: last}
|
||||
|
||||
@doc """
|
||||
Creates a new range.
|
||||
@@ -57,6 +61,33 @@ defmodule Range do
|
||||
"got: #{inspect(first)}..#{inspect(last)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if two ranges are disjoint.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Range.disjoint?(1..5, 6..9)
|
||||
true
|
||||
iex> Range.disjoint?(5..1, 6..9)
|
||||
true
|
||||
iex> Range.disjoint?(1..5, 5..9)
|
||||
false
|
||||
iex> Range.disjoint?(1..5, 2..7)
|
||||
false
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec disjoint?(t, t) :: boolean
|
||||
def disjoint?(first1..last1, first2..last2) do
|
||||
{first1, last1} = normalize(first1, last1)
|
||||
{first2, last2} = normalize(first2, last2)
|
||||
last2 < first1 or last1 < first2
|
||||
end
|
||||
|
||||
@compile inline: [normalize: 2]
|
||||
defp normalize(first, last) when first > last, do: {last, first}
|
||||
defp normalize(first, last), do: {first, last}
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
@doc false
|
||||
@deprecated "Pattern match on first..last instead"
|
||||
|
||||
+116
-73
@@ -28,10 +28,10 @@ defmodule Record do
|
||||
|
||||
defmodule MyModule do
|
||||
require Record
|
||||
Record.defrecord :user, name: "john", age: 25
|
||||
Record.defrecord(:user, name: "john", age: 25)
|
||||
|
||||
@type user :: record(:user, name: String.t, age: integer)
|
||||
# expands to: "@type user :: {:user, String.t, integer}"
|
||||
@type user :: record(:user, name: String.t(), age: integer)
|
||||
# expands to: "@type user :: {:user, String.t(), integer}"
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -62,11 +62,11 @@ defmodule Record do
|
||||
|
||||
* `:includes` - (a list of directories as binaries) if the record being
|
||||
extracted depends on relative includes, this option allows developers
|
||||
to specify the directory those relative includes exist
|
||||
to specify the directory where those relative includes exist.
|
||||
|
||||
* `:macros` - (keyword list of macro names and values) if the record
|
||||
being extract depends on the values of macros, this option allows
|
||||
the value of those macros to be set
|
||||
being extracted depends on the values of macros, this option allows
|
||||
the value of those macros to be set.
|
||||
|
||||
These options are expected to be literals (including the binary values) at
|
||||
compile time.
|
||||
@@ -74,10 +74,21 @@ defmodule Record do
|
||||
## Examples
|
||||
|
||||
iex> Record.extract(:file_info, from_lib: "kernel/include/file.hrl")
|
||||
[size: :undefined, type: :undefined, access: :undefined, atime: :undefined,
|
||||
mtime: :undefined, ctime: :undefined, mode: :undefined, links: :undefined,
|
||||
major_device: :undefined, minor_device: :undefined, inode: :undefined,
|
||||
uid: :undefined, gid: :undefined]
|
||||
[
|
||||
size: :undefined,
|
||||
type: :undefined,
|
||||
access: :undefined,
|
||||
atime: :undefined,
|
||||
mtime: :undefined,
|
||||
ctime: :undefined,
|
||||
mode: :undefined,
|
||||
links: :undefined,
|
||||
major_device: :undefined,
|
||||
minor_device: :undefined,
|
||||
inode: :undefined,
|
||||
uid: :undefined,
|
||||
gid: :undefined
|
||||
]
|
||||
|
||||
"""
|
||||
@spec extract(name :: atom, keyword) :: keyword
|
||||
@@ -101,6 +112,7 @@ defmodule Record do
|
||||
that contains the record definitions to extract; with this option, this
|
||||
function uses the same path lookup used by the `-include` attribute used in
|
||||
Erlang modules.
|
||||
|
||||
* `:from_lib` - (binary representing a path to a file) path to the Erlang
|
||||
file that contains the record definitions to extract; with this option,
|
||||
this function uses the same path lookup used by the `-include_lib`
|
||||
@@ -175,7 +187,7 @@ defmodule Record do
|
||||
|
||||
defmodule User do
|
||||
require Record
|
||||
Record.defrecord :user, [name: "meg", age: "25"]
|
||||
Record.defrecord(:user, name: "meg", age: "25")
|
||||
end
|
||||
|
||||
In the example above, a set of macros named `user` but with different
|
||||
@@ -215,7 +227,7 @@ defmodule Record do
|
||||
|
||||
defmodule User do
|
||||
require Record
|
||||
Record.defrecord :user, Customer, name: nil
|
||||
Record.defrecord(:user, Customer, name: nil)
|
||||
end
|
||||
|
||||
require User
|
||||
@@ -228,7 +240,7 @@ defmodule Record do
|
||||
a record after extracting it from an Erlang library that uses anonymous
|
||||
functions for defaults.
|
||||
|
||||
Record.defrecord :my_rec, Record.extract(...)
|
||||
Record.defrecord(:my_rec, Record.extract(...))
|
||||
#=> ** (ArgumentError) invalid value for record field fun_field,
|
||||
#=> cannot escape #Function<12.90072148/2 in :erl_eval.expr/5>.
|
||||
|
||||
@@ -237,14 +249,25 @@ defmodule Record do
|
||||
|
||||
defmodule MyRec do
|
||||
require Record
|
||||
Record.defrecord :my_rec, Record.extract(...) |> Keyword.merge(fun_field: &__MODULE__.foo/2)
|
||||
Record.defrecord(:my_rec, Record.extract(...) |> Keyword.merge(fun_field: &__MODULE__.foo/2))
|
||||
def foo(bar, baz), do: IO.inspect({bar, baz})
|
||||
end
|
||||
|
||||
"""
|
||||
defmacro defrecord(name, tag \\ nil, kv) do
|
||||
quote bind_quoted: [name: name, tag: tag, kv: kv] do
|
||||
defined_arity =
|
||||
Enum.find(0..2, fn arity ->
|
||||
Module.defines?(__MODULE__, {name, arity})
|
||||
end)
|
||||
|
||||
if defined_arity do
|
||||
raise ArgumentError,
|
||||
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
|
||||
end
|
||||
|
||||
tag = tag || name
|
||||
|
||||
fields = Record.__fields__(:defrecord, kv)
|
||||
|
||||
defmacro unquote(name)(args \\ []) do
|
||||
@@ -262,7 +285,18 @@ defmodule Record do
|
||||
"""
|
||||
defmacro defrecordp(name, tag \\ nil, kv) do
|
||||
quote bind_quoted: [name: name, tag: tag, kv: kv] do
|
||||
defined_arity =
|
||||
Enum.find(0..2, fn arity ->
|
||||
Module.defines?(__MODULE__, {name, arity})
|
||||
end)
|
||||
|
||||
if defined_arity do
|
||||
raise ArgumentError,
|
||||
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
|
||||
end
|
||||
|
||||
tag = tag || name
|
||||
|
||||
fields = Record.__fields__(:defrecordp, kv)
|
||||
|
||||
defmacrop unquote(name)(args \\ []) do
|
||||
@@ -345,38 +379,30 @@ defmodule Record do
|
||||
|
||||
# Gets the index of field.
|
||||
defp index(tag, fields, field) do
|
||||
if index = find_index(fields, field, 0) do
|
||||
# Convert to Elixir index
|
||||
index - 1
|
||||
else
|
||||
find_index(fields, field, 1) ||
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(field)}"
|
||||
end
|
||||
end
|
||||
|
||||
# Creates a new record with the given default fields and keyword values.
|
||||
defp create(tag, fields, keyword, caller) do
|
||||
in_match = Macro.Env.in_match?(caller)
|
||||
keyword = apply_underscore(fields, keyword)
|
||||
# Using {} here is safe, since it's not valid AST
|
||||
default = if Macro.Env.in_match?(caller), do: {:_, [], nil}, else: {}
|
||||
{default, keyword} = Keyword.pop(keyword, :_, default)
|
||||
|
||||
{match, remaining} =
|
||||
Enum.map_reduce(fields, keyword, fn {field, default}, each_keyword ->
|
||||
new_fields =
|
||||
case Keyword.fetch(each_keyword, field) do
|
||||
{:ok, value} -> value
|
||||
:error when in_match -> {:_, [], nil}
|
||||
:error -> Macro.escape(default)
|
||||
end
|
||||
|
||||
{new_fields, Keyword.delete(each_keyword, field)}
|
||||
{elements, remaining} =
|
||||
Enum.map_reduce(fields, keyword, fn {key, field_default}, remaining ->
|
||||
case Keyword.pop(remaining, key, default) do
|
||||
{{}, remaining} -> {Macro.escape(field_default), remaining}
|
||||
{default, remaining} -> {default, remaining}
|
||||
end
|
||||
end)
|
||||
|
||||
case remaining do
|
||||
[] ->
|
||||
{:{}, [], [tag | match]}
|
||||
quote(do: {unquote(tag), unquote_splicing(elements)})
|
||||
|
||||
_ ->
|
||||
keys = for {key, _} <- remaining, do: key
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(hd(keys))}"
|
||||
[{key, _} | _] ->
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -386,35 +412,65 @@ defmodule Record do
|
||||
raise ArgumentError, "cannot invoke update style macro inside match"
|
||||
end
|
||||
|
||||
keyword = apply_underscore(fields, keyword)
|
||||
|
||||
Enum.reduce(keyword, var, fn {key, value}, acc ->
|
||||
index = find_index(fields, key, 0)
|
||||
|
||||
if index do
|
||||
quote do
|
||||
:erlang.setelement(unquote(index), unquote(acc), unquote(value))
|
||||
end
|
||||
else
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
# Gets a record key from the given var.
|
||||
defp get(tag, fields, var, key) do
|
||||
index = find_index(fields, key, 0)
|
||||
|
||||
if index do
|
||||
quote do
|
||||
:erlang.element(unquote(index), unquote(var))
|
||||
end
|
||||
if Keyword.has_key?(keyword, :_) do
|
||||
message = "updating a record with a default (:_) is equivalent to creating a new record"
|
||||
IO.warn(message, Macro.Env.stacktrace(caller))
|
||||
create(tag, fields, keyword, caller)
|
||||
else
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
case build_updates(keyword, fields, [], [], []) do
|
||||
{updates, [], []} ->
|
||||
build_update(updates, var)
|
||||
|
||||
{updates, vars, exprs} ->
|
||||
quote do
|
||||
{unquote_splicing(:lists.reverse(vars))} = {unquote_splicing(:lists.reverse(exprs))}
|
||||
unquote(build_update(updates, var))
|
||||
end
|
||||
|
||||
{:error, key} ->
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp find_index([{k, _} | _], k, i), do: i + 2
|
||||
defp build_update(updates, initial) do
|
||||
updates
|
||||
|> Enum.sort(fn {left, _}, {right, _} -> right <= left end)
|
||||
|> Enum.reduce(initial, fn {key, value}, acc ->
|
||||
quote(do: :erlang.setelement(unquote(key), unquote(acc), unquote(value)))
|
||||
end)
|
||||
end
|
||||
|
||||
defp build_updates([{key, value} | rest], fields, updates, vars, exprs) do
|
||||
if index = find_index(fields, key, 2) do
|
||||
if simple_argument?(value) do
|
||||
build_updates(rest, fields, [{index, value} | updates], vars, exprs)
|
||||
else
|
||||
var = Macro.var(key, __MODULE__)
|
||||
build_updates(rest, fields, [{index, var} | updates], [var | vars], [value | exprs])
|
||||
end
|
||||
else
|
||||
{:error, key}
|
||||
end
|
||||
end
|
||||
|
||||
defp build_updates([], _fields, updates, vars, exprs), do: {updates, vars, exprs}
|
||||
|
||||
defp simple_argument?({name, _, ctx}) when is_atom(name) and is_atom(ctx), do: true
|
||||
defp simple_argument?(other), do: Macro.quoted_literal?(other)
|
||||
|
||||
# Gets a record key from the given var.
|
||||
defp get(tag, fields, var, key) do
|
||||
index =
|
||||
find_index(fields, key, 2) ||
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
|
||||
|
||||
quote do
|
||||
:erlang.element(unquote(index), unquote(var))
|
||||
end
|
||||
end
|
||||
|
||||
defp find_index([{k, _} | _], k, i), do: i
|
||||
defp find_index([{_, _} | t], k, i), do: find_index(t, k, i + 1)
|
||||
defp find_index([], _k, _i), do: nil
|
||||
|
||||
@@ -446,17 +502,4 @@ defmodule Record do
|
||||
|
||||
defp join_keyword([], [], acc), do: :lists.reverse(acc)
|
||||
defp join_keyword(rest_fields, _rest_values, acc), do: length(acc) + length(rest_fields)
|
||||
|
||||
defp apply_underscore(fields, keyword) do
|
||||
case Keyword.fetch(keyword, :_) do
|
||||
{:ok, default} ->
|
||||
fields
|
||||
|> Enum.map(fn {k, _} -> {k, default} end)
|
||||
|> Keyword.merge(keyword)
|
||||
|> Keyword.delete(:_)
|
||||
|
||||
:error ->
|
||||
keyword
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+8
-13
@@ -7,7 +7,7 @@ defmodule Regex do
|
||||
in the [`:re` module documentation](http://www.erlang.org/doc/man/re.html).
|
||||
|
||||
Regular expressions in Elixir can be created using the sigils
|
||||
[`~r`](`Kernel.sigil_r/2`) or [`~R`](`Kernel.sigil_R/2`):
|
||||
`~r` (see `Kernel.sigil_r/2`) or `~R` (see `Kernel.sigil_R/2`):
|
||||
|
||||
# A simple regular expression that matches foo anywhere in the string
|
||||
~r/foo/
|
||||
@@ -58,7 +58,7 @@ defmodule Regex do
|
||||
|
||||
* `dotall` (s) - causes dot to match newlines and also set newline to
|
||||
anycrlf; the new line setting can be overridden by setting `(*CR)` or
|
||||
`(*LF)` or `(*CRLF)` or `(*ANY)` according to re documentation
|
||||
`(*LF)` or `(*CRLF)` or `(*ANY)` according to `:re` documentation
|
||||
|
||||
* `multiline` (m) - causes `^` and `$` to mark the beginning and end of
|
||||
each line; use `\A` and `\z` to match the end or beginning of the string
|
||||
@@ -79,7 +79,7 @@ defmodule Regex do
|
||||
* `no_auto_capture` - not available, use `?:` instead
|
||||
* `newline` - not available, use `(*CR)` or `(*LF)` or `(*CRLF)` or
|
||||
`(*ANYCRLF)` or `(*ANY)` at the beginning of the regexp according to the
|
||||
re documentation
|
||||
`:re` documentation
|
||||
|
||||
## Captures
|
||||
|
||||
@@ -118,7 +118,7 @@ defmodule Regex do
|
||||
|
||||
The given options can either be a binary with the characters
|
||||
representing the same regex options given to the
|
||||
[`~r`](`Kernel.sigil_r/2`) sigil, or a list of options, as
|
||||
`~r` (see `Kernel.sigil_r/2`) sigil, or a list of options, as
|
||||
expected by the Erlang's `:re` module.
|
||||
|
||||
It returns `{:ok, regex}` in case of success,
|
||||
@@ -134,7 +134,7 @@ defmodule Regex do
|
||||
|
||||
"""
|
||||
@spec compile(binary, binary | [term]) :: {:ok, t} | {:error, any}
|
||||
def compile(source, options \\ "") do
|
||||
def compile(source, options \\ "") when is_binary(source) do
|
||||
compile(source, options, version())
|
||||
end
|
||||
|
||||
@@ -152,7 +152,7 @@ defmodule Regex do
|
||||
compile(source, options, "", version)
|
||||
end
|
||||
|
||||
defp compile(source, opts, doc_opts, version) when is_binary(source) do
|
||||
defp compile(source, opts, doc_opts, version) do
|
||||
case :re.compile(source, opts) do
|
||||
{:ok, re_pattern} ->
|
||||
{:ok, %Regex{re_pattern: re_pattern, re_version: version, source: source, opts: doc_opts}}
|
||||
@@ -166,7 +166,7 @@ defmodule Regex do
|
||||
Compiles the regular expression and raises `Regex.CompileError` in case of errors.
|
||||
"""
|
||||
@spec compile!(binary, binary | [term]) :: t
|
||||
def compile!(source, options \\ "") do
|
||||
def compile!(source, options \\ "") when is_binary(source) do
|
||||
case compile(source, options) do
|
||||
{:ok, regex} -> regex
|
||||
{:error, {reason, at}} -> raise Regex.CompileError, "#{reason} at position #{at}"
|
||||
@@ -211,13 +211,8 @@ defmodule Regex do
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec version :: term()
|
||||
# TODO: No longer check for function_exported? on OTP 20+.
|
||||
def version do
|
||||
if function_exported?(:re, :version, 0) do
|
||||
{:re.version(), :erlang.system_info(:endian)}
|
||||
else
|
||||
{"8.33 2013-05-29", :erlang.system_info(:endian)}
|
||||
end
|
||||
{:re.version(), :erlang.system_info(:endian)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
||||
+60
-31
@@ -32,10 +32,26 @@ defmodule Registry do
|
||||
{:ok, _} = Agent.start_link(fn -> 0 end, name: name)
|
||||
Agent.get(name, & &1)
|
||||
#=> 0
|
||||
Agent.update(name, & &1 + 1)
|
||||
Agent.update(name, &(&1 + 1))
|
||||
Agent.get(name, & &1)
|
||||
#=> 1
|
||||
|
||||
In the previous example, we were not interested in associating a value to the
|
||||
process:
|
||||
|
||||
Registry.lookup(Registry.ViaTest, "agent")
|
||||
#=> [{self(), nil}]
|
||||
|
||||
However, in some cases it may be desired to associate a value to the process
|
||||
using the alternate `{:via, Registry, {registry, key, value}}` tuple:
|
||||
|
||||
{:ok, _} = Registry.start_link(keys: :unique, name: Registry.ViaTest)
|
||||
name = {:via, Registry, {Registry.ViaTest, "agent", :hello}}
|
||||
{:ok, _} = Agent.start_link(fn -> 0 end, name: name)
|
||||
Registry.lookup(Registry.ViaTest, "agent")
|
||||
#=> [{self(), :hello}]
|
||||
|
||||
To this point, we have been starting `Registry` using `start_link/1`.
|
||||
Typically the registry is started as part of a supervision tree though:
|
||||
|
||||
{Registry, keys: :unique, name: Registry.ViaTest}
|
||||
@@ -83,6 +99,7 @@ defmodule Registry do
|
||||
errors:
|
||||
|
||||
require Logger
|
||||
|
||||
Registry.dispatch(Registry.DispatcherTest, "hello", fn entries ->
|
||||
for {pid, {module, function}} <- entries do
|
||||
try do
|
||||
@@ -90,7 +107,7 @@ defmodule Registry do
|
||||
catch
|
||||
kind, reason ->
|
||||
formatted = Exception.format(kind, reason, __STACKTRACE__)
|
||||
Logger.error "Registry.dispatch/3 failed with #{formatted}"
|
||||
Logger.error("Registry.dispatch/3 failed with #{formatted}")
|
||||
end
|
||||
end
|
||||
end)
|
||||
@@ -111,9 +128,15 @@ defmodule Registry do
|
||||
schedulers online, which will make the registry more performant on highly
|
||||
concurrent environments:
|
||||
|
||||
{:ok, _} = Registry.start_link(keys: :duplicate, name: Registry.PubSubTest,
|
||||
partitions: System.schedulers_online)
|
||||
{:ok, _} =
|
||||
Registry.start_link(
|
||||
keys: :duplicate,
|
||||
name: Registry.PubSubTest,
|
||||
partitions: System.schedulers_online()
|
||||
)
|
||||
|
||||
{:ok, _} = Registry.register(Registry.PubSubTest, "hello", [])
|
||||
|
||||
Registry.dispatch(Registry.PubSubTest, "hello", fn entries ->
|
||||
for {pid, _} <- entries, do: send(pid, {:broadcast, "world"})
|
||||
end)
|
||||
@@ -183,8 +206,10 @@ defmodule Registry do
|
||||
## Via callbacks
|
||||
|
||||
@doc false
|
||||
@doc since: "1.4.0"
|
||||
def whereis_name({registry, key}) do
|
||||
def whereis_name({registry, key}), do: whereis_name(registry, key)
|
||||
def whereis_name({registry, key, _value}), do: whereis_name(registry, key)
|
||||
|
||||
defp whereis_name(registry, key) do
|
||||
case key_info!(registry) do
|
||||
{:unique, partitions, key_ets} ->
|
||||
key_ets = key_ets || key_ets!(registry, key, partitions)
|
||||
@@ -203,16 +228,17 @@ defmodule Registry do
|
||||
end
|
||||
|
||||
@doc false
|
||||
@doc since: "1.4.0"
|
||||
def register_name({registry, key}, pid) when pid == self() do
|
||||
case register(registry, key, nil) do
|
||||
def register_name({registry, key}, pid), do: register_name(registry, key, nil, pid)
|
||||
def register_name({registry, key, value}, pid), do: register_name(registry, key, value, pid)
|
||||
|
||||
defp register_name(registry, key, value, pid) when pid == self() do
|
||||
case register(registry, key, value) do
|
||||
{:ok, _} -> :yes
|
||||
{:error, _} -> :no
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
@doc since: "1.4.0"
|
||||
def send({registry, key}, msg) do
|
||||
case lookup(registry, key) do
|
||||
[{pid, _}] -> Kernel.send(pid, msg)
|
||||
@@ -221,7 +247,6 @@ defmodule Registry do
|
||||
end
|
||||
|
||||
@doc false
|
||||
@doc since: "1.4.0"
|
||||
def unregister_name({registry, key}) do
|
||||
unregister(registry, key)
|
||||
end
|
||||
@@ -239,21 +264,23 @@ defmodule Registry do
|
||||
|
||||
Supervisor.start_link([
|
||||
{Registry, keys: :unique, name: MyApp.Registry}
|
||||
])
|
||||
], strategy: :one_for_one)
|
||||
|
||||
For intensive workloads, the registry may also be partitioned (by specifying
|
||||
the `:partitions` option). If partitioning is required then a good default is to
|
||||
set the number of partitions to the number of schedulers available:
|
||||
|
||||
Registry.start_link(keys: :unique, name: MyApp.Registry,
|
||||
partitions: System.schedulers_online())
|
||||
Registry.start_link(
|
||||
keys: :unique,
|
||||
name: MyApp.Registry,
|
||||
partitions: System.schedulers_online()
|
||||
)
|
||||
|
||||
or:
|
||||
|
||||
Supervisor.start_link([
|
||||
{Registry, keys: :unique, name: MyApp.Registry,
|
||||
partitions: System.schedulers_online()}
|
||||
])
|
||||
{Registry, keys: :unique, name: MyApp.Registry, partitions: System.schedulers_online()}
|
||||
], strategy: :one_for_one)
|
||||
|
||||
## Options
|
||||
|
||||
@@ -583,9 +610,11 @@ defmodule Registry do
|
||||
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
|
||||
iex> Registry.match(Registry.MatchTest, "hello", {:"$1", :_, :"$1"}) |> Enum.sort()
|
||||
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
|
||||
iex> Registry.match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
|
||||
iex> guards = [{:>, :"$1", 1}]
|
||||
iex> Registry.match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, guards)
|
||||
[{self(), {2, :atom, 2}}]
|
||||
iex> Registry.match(Registry.MatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}]) |> Enum.sort()
|
||||
iex> guards = [{:is_atom, :"$1"}]
|
||||
iex> Registry.match(Registry.MatchTest, "hello", {:_, :"$1", :_}, guards) |> Enum.sort()
|
||||
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
|
||||
|
||||
"""
|
||||
@@ -878,7 +907,7 @@ defmodule Registry do
|
||||
key_ets = key_ets || key_ets!(registry, key_partition)
|
||||
{pid_server, pid_ets} = pid_ets || pid_ets!(registry, pid_partition)
|
||||
|
||||
# Notice we write first to the pid ets table because it will
|
||||
# Notice we write first to the pid_ets table because it will
|
||||
# always be able to do the cleanup. If we register first to the
|
||||
# key one and the process crashes, the key will stay there forever.
|
||||
Process.link(pid_server)
|
||||
@@ -1060,20 +1089,20 @@ defmodule Registry do
|
||||
In the example below we register the current process under the same
|
||||
key in a duplicate registry but with different values:
|
||||
|
||||
iex> Registry.start_link(keys: :duplicate, name: Registry.MatchTest)
|
||||
iex> {:ok, _} = Registry.register(Registry.MatchTest, "hello", {1, :atom, 1})
|
||||
iex> {:ok, _} = Registry.register(Registry.MatchTest, "hello", {2, :atom, 2})
|
||||
iex> Registry.count_match(Registry.MatchTest, "hello", {1, :_, :_})
|
||||
iex> Registry.start_link(keys: :duplicate, name: Registry.CountMatchTest)
|
||||
iex> {:ok, _} = Registry.register(Registry.CountMatchTest, "hello", {1, :atom, 1})
|
||||
iex> {:ok, _} = Registry.register(Registry.CountMatchTest, "hello", {2, :atom, 2})
|
||||
iex> Registry.count_match(Registry.CountMatchTest, "hello", {1, :_, :_})
|
||||
1
|
||||
iex> Registry.count_match(Registry.MatchTest, "hello", {2, :_, :_})
|
||||
iex> Registry.count_match(Registry.CountMatchTest, "hello", {2, :_, :_})
|
||||
1
|
||||
iex> Registry.count_match(Registry.MatchTest, "hello", {:_, :atom, :_})
|
||||
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:_, :atom, :_})
|
||||
2
|
||||
iex> Registry.count_match(Registry.MatchTest, "hello", {:"$1", :_, :"$1"})
|
||||
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:"$1", :_, :"$1"})
|
||||
2
|
||||
iex> Registry.count_match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
|
||||
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
|
||||
1
|
||||
iex> Registry.count_match(Registry.MatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}])
|
||||
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}])
|
||||
2
|
||||
|
||||
"""
|
||||
@@ -1204,7 +1233,7 @@ end
|
||||
defmodule Registry.Partition do
|
||||
@moduledoc false
|
||||
|
||||
# This process owns the equivalent key and pid ets tables
|
||||
# This process owns the equivalent key and pid ETS tables
|
||||
# and is responsible for monitoring processes that map to
|
||||
# its own pid table.
|
||||
use GenServer
|
||||
@@ -1296,7 +1325,7 @@ defmodule Registry.Partition do
|
||||
for {_pid, key, key_ets} <- entries do
|
||||
key_ets =
|
||||
case key_ets do
|
||||
# In case the fake key ets is being used. See unregister_match/2.
|
||||
# In case the fake key_ets is being used. See unregister_match/2.
|
||||
{key_ets, _} ->
|
||||
key_ets
|
||||
|
||||
|
||||
+27
-12
@@ -95,7 +95,10 @@ defmodule Stream do
|
||||
|
||||
@type acc :: any
|
||||
@type element :: any
|
||||
|
||||
@typedoc "Zero-based index."
|
||||
@type index :: non_neg_integer
|
||||
|
||||
@type default :: any
|
||||
|
||||
# Require Stream.Reducers and its callbacks
|
||||
@@ -1241,7 +1244,8 @@ defmodule Stream do
|
||||
fn acc, fun ->
|
||||
inner = &do_cycle_each(&1, &2, fun)
|
||||
outer = &Enumerable.reduce(enumerable, &1, inner)
|
||||
do_cycle(outer, outer, acc)
|
||||
reduce = check_cycle_first_element(outer)
|
||||
do_cycle(reduce, outer, acc)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1260,9 +1264,6 @@ defmodule Stream do
|
||||
{:stream_cycle, acc} ->
|
||||
{:halted, acc}
|
||||
else
|
||||
{state, []} when state in [:done, :halted] ->
|
||||
raise ArgumentError, "cannot cycle over empty enumerable"
|
||||
|
||||
{state, acc} when state in [:done, :halted] ->
|
||||
do_cycle(cycle, cycle, {:cont, acc})
|
||||
|
||||
@@ -1278,6 +1279,18 @@ defmodule Stream do
|
||||
end
|
||||
end
|
||||
|
||||
defp check_cycle_first_element(reduce) do
|
||||
fn acc ->
|
||||
case reduce.(acc) do
|
||||
{state, []} when state in [:done, :halted] ->
|
||||
raise ArgumentError, "cannot cycle over empty enumerable"
|
||||
|
||||
other ->
|
||||
other
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Emits a sequence of values, starting with `start_value`. Successive
|
||||
values are generated by calling `next_fun` on the previous value.
|
||||
@@ -1346,14 +1359,16 @@ defmodule Stream do
|
||||
|
||||
## Examples
|
||||
|
||||
Stream.resource(fn -> File.open!("sample") end,
|
||||
fn file ->
|
||||
case IO.read(file, :line) do
|
||||
data when is_binary(data) -> {[data], file}
|
||||
_ -> {:halt, file}
|
||||
end
|
||||
end,
|
||||
fn file -> File.close(file) end)
|
||||
Stream.resource(
|
||||
fn -> File.open!("sample") end,
|
||||
fn file ->
|
||||
case IO.read(file, :line) do
|
||||
data when is_binary(data) -> {[data], file}
|
||||
_ -> {:halt, file}
|
||||
end
|
||||
end,
|
||||
fn file -> File.close(file) end
|
||||
)
|
||||
|
||||
"""
|
||||
@spec resource((() -> acc), (acc -> {[element], acc} | {:halt, acc}), (acc -> term)) ::
|
||||
|
||||
@@ -25,7 +25,7 @@ defmodule Stream.Reducers do
|
||||
end
|
||||
|
||||
after_fun = fn {acc_buffer, acc_count} ->
|
||||
if leftover == :discard or acc_count == 0 or (step > count and acc_count >= count) do
|
||||
if leftover == :discard or acc_count == 0 or acc_count >= count do
|
||||
{:cont, []}
|
||||
else
|
||||
{:cont, :lists.reverse(acc_buffer, Enum.take(leftover, count - acc_count)), []}
|
||||
|
||||
+160
-36
@@ -183,7 +183,7 @@ defmodule String do
|
||||
## Patterns
|
||||
|
||||
Many functions in this module work with patterns. For example,
|
||||
`String.split/2` can split a string into multiple patterns given
|
||||
`String.split/2` can split a string into multiple strings given
|
||||
a pattern. This pattern can be a string, a list of strings or
|
||||
a compiled pattern:
|
||||
|
||||
@@ -198,15 +198,15 @@ defmodule String do
|
||||
["foo", "bar", ""]
|
||||
|
||||
The compiled pattern is useful when the same match will
|
||||
be done over and over again. Note though the compiled
|
||||
be done over and over again. Note though that the compiled
|
||||
pattern cannot be stored in a module attribute as the pattern
|
||||
is generated at runtime and does not survive compile term.
|
||||
is generated at runtime and does not survive compile time.
|
||||
"""
|
||||
|
||||
@typedoc """
|
||||
A UTF-8 encoded binary.
|
||||
|
||||
Note `String.t()` and `binary()` are equivalent to analysis tools.
|
||||
The types `String.t()` and `binary()` are equivalent to analysis tools.
|
||||
Although, for those reading the documentation, `String.t()` implies
|
||||
it is a UTF-8 encoded binary.
|
||||
"""
|
||||
@@ -307,9 +307,9 @@ defmodule String do
|
||||
defdelegate split(binary), to: String.Break
|
||||
|
||||
@doc ~S"""
|
||||
Divides a string into substrings based on a pattern.
|
||||
Divides a string into parts based on a pattern.
|
||||
|
||||
Returns a list of these substrings. The pattern can
|
||||
Returns a list of these parts. The pattern can
|
||||
be a string, a list of strings, a regular expression,
|
||||
or a compiled pattern.
|
||||
|
||||
@@ -387,15 +387,15 @@ defmodule String do
|
||||
iex> String.split("abc", "", parts: 3)
|
||||
["", "a", "bc"]
|
||||
|
||||
Note this function can split within or across grapheme boundaries.
|
||||
Be aware that this function can split within or across grapheme boundaries.
|
||||
For example, take the grapheme "é" which is made of the characters
|
||||
"e" and the acute accent. The following returns `true`:
|
||||
"e" and the acute accent. The following will split the string into two parts:
|
||||
|
||||
iex> String.split(String.normalize("é", :nfd), "e")
|
||||
["", "́"]
|
||||
|
||||
However, if "é" is represented by the single character "e with acute"
|
||||
accent, then it will return `false`:
|
||||
accent, then it will split the string into just one part:
|
||||
|
||||
iex> String.split(String.normalize("é", :nfc), "e")
|
||||
["é"]
|
||||
@@ -460,10 +460,10 @@ defmodule String do
|
||||
This is in contrast to `split/3` which splits the
|
||||
entire string upfront.
|
||||
|
||||
Note splitter does not support regular expressions
|
||||
(as it is often more efficient to have the regular
|
||||
expressions traverse the string at once than in
|
||||
multiple passes).
|
||||
This function does not support regular expressions
|
||||
by design. When using regular expressions, it is often
|
||||
more efficient to have the regular expressions traverse
|
||||
the string at once than in parts, like this function does.
|
||||
|
||||
## Options
|
||||
|
||||
@@ -632,8 +632,24 @@ defmodule String do
|
||||
"leña"
|
||||
|
||||
"""
|
||||
@spec normalize(t, atom) :: t
|
||||
defdelegate normalize(string, form), to: String.Normalizer
|
||||
# TODO: Fully deprecate it on v1.10
|
||||
@doc deprecated:
|
||||
"Use :unicode.characters_to_nfc_binary/1 or :unicode.characters_to_nfd_binary/1 instead"
|
||||
def normalize(string, form)
|
||||
|
||||
def normalize(string, :nfd) do
|
||||
case :unicode.characters_to_nfd_binary(string) do
|
||||
string when is_binary(string) -> string
|
||||
{:error, bad, rest} -> bad <> normalize(rest, :nfd)
|
||||
end
|
||||
end
|
||||
|
||||
def normalize(string, :nfc) do
|
||||
case :unicode.characters_to_nfc_binary(string) do
|
||||
string when is_binary(string) -> string
|
||||
{:error, bad, rest} -> bad <> normalize(rest, :nfc)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts all characters in the given string to uppercase according to `mode`.
|
||||
@@ -816,7 +832,7 @@ defmodule String do
|
||||
"ola ola world"
|
||||
|
||||
"""
|
||||
@spec replace_leading(t, t, t) :: t | no_return
|
||||
@spec replace_leading(t, t, t) :: t
|
||||
def replace_leading(string, match, replacement)
|
||||
when is_binary(string) and is_binary(match) and is_binary(replacement) do
|
||||
if match == "" do
|
||||
@@ -873,7 +889,7 @@ defmodule String do
|
||||
"hello mundo mundo"
|
||||
|
||||
"""
|
||||
@spec replace_trailing(t, t, t) :: t | no_return
|
||||
@spec replace_trailing(t, t, t) :: t
|
||||
def replace_trailing(string, match, replacement)
|
||||
when is_binary(string) and is_binary(match) and is_binary(replacement) do
|
||||
if match == "" do
|
||||
@@ -1129,7 +1145,7 @@ defmodule String do
|
||||
When `count` is less than or equal to the length of `string`,
|
||||
given `string` is returned.
|
||||
|
||||
Raises `ArgumentError` if the given `padding` contains non-string element.
|
||||
Raises `ArgumentError` if the given `padding` contains a non-string element.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1171,7 +1187,7 @@ defmodule String do
|
||||
When `count` is less than or equal to the length of `string`,
|
||||
given `string` is returned.
|
||||
|
||||
Raises `ArgumentError` if the given `padding` contains non-string element.
|
||||
Raises `ArgumentError` if the given `padding` contains a non-string element.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1471,23 +1487,46 @@ defmodule String do
|
||||
@spec codepoints(t) :: [codepoint]
|
||||
defdelegate codepoints(string), to: String.Unicode
|
||||
|
||||
@doc """
|
||||
@doc ~S"""
|
||||
Returns the next codepoint in a string.
|
||||
|
||||
The result is a tuple with the codepoint and the
|
||||
remainder of the string or `nil` in case
|
||||
the string reached its end.
|
||||
|
||||
As with other functions in the String module, this
|
||||
function does not check for the validity of the codepoint.
|
||||
That said, if an invalid codepoint is found, it will
|
||||
be returned by this function.
|
||||
As with other functions in the `String` module, `next_codepoint/1`
|
||||
works with binaries that are invalid UTF-8. If the string starts
|
||||
with a sequence of bytes that is not valid in UTF-8 encoding, the
|
||||
first element of the returned tuple is a binary with the first byte.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> String.next_codepoint("olá")
|
||||
{"o", "lá"}
|
||||
|
||||
iex> invalid = "\x80\x80OK" # first two bytes are invalid in UTF-8
|
||||
iex> {_, rest} = String.next_codepoint(invalid)
|
||||
{<<128>>, <<128, 79, 75>>}
|
||||
iex> String.next_codepoint(rest)
|
||||
{<<128>>, "OK"}
|
||||
|
||||
## Comparison with binary pattern matching
|
||||
|
||||
Binary pattern matching provides a similar way to decompose
|
||||
a string:
|
||||
|
||||
iex> <<codepoint::utf8, rest::binary>> = "Elixir"
|
||||
"Elixir"
|
||||
iex> codepoint
|
||||
69
|
||||
iex> rest
|
||||
"lixir"
|
||||
|
||||
though not entirely equivalent because `codepoint` comes as
|
||||
an integer, and the pattern won't match invalid UTF-8.
|
||||
|
||||
Binary pattern matching, however, is simpler and more efficient,
|
||||
so pick the option that better suits your use case.
|
||||
"""
|
||||
@compile {:inline, next_codepoint: 1}
|
||||
@spec next_codepoint(t) :: {codepoint, t} | nil
|
||||
@@ -2062,17 +2101,17 @@ defmodule String do
|
||||
iex> String.contains?("elixir of life", ["", "other"])
|
||||
true
|
||||
|
||||
Note this function can match within or across grapheme boundaries.
|
||||
Be aware that this function can match within or across grapheme boundaries.
|
||||
For example, take the grapheme "é" which is made of the characters
|
||||
"e" and the acute accent. The following returns `true`:
|
||||
|
||||
iex> String.contains?(String.normalize("é", :nfd), "e")
|
||||
iex> String.contains?(:unicode.characters_to_nfd_binary("é"), "e")
|
||||
true
|
||||
|
||||
However, if "é" is represented by the single character "e with acute"
|
||||
accent, then it will return `false`:
|
||||
|
||||
iex> String.contains?(String.normalize("é", :nfc), "e")
|
||||
iex> String.contains?(:unicode.characters_to_nfc_binary("é"), "e")
|
||||
false
|
||||
|
||||
"""
|
||||
@@ -2092,7 +2131,7 @@ defmodule String do
|
||||
@doc """
|
||||
Converts a string into a charlist.
|
||||
|
||||
Specifically, this functions takes a UTF-8 encoded binary and returns a list of its integer
|
||||
Specifically, this function takes a UTF-8 encoded binary and returns a list of its integer
|
||||
codepoints. It is similar to `codepoints/1` except that the latter returns a list of codepoints as
|
||||
strings.
|
||||
|
||||
@@ -2130,8 +2169,7 @@ defmodule String do
|
||||
By default, the maximum number of atoms is `1_048_576`. This limit
|
||||
can be raised or lowered using the VM option `+t`.
|
||||
|
||||
The maximum atom size is of 255 characters. Prior to Erlang/OTP 20,
|
||||
only latin1 characters are allowed.
|
||||
The maximum atom size is of 255 Unicode codepoints.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
@@ -2149,8 +2187,7 @@ defmodule String do
|
||||
@doc """
|
||||
Converts a string to an existing atom.
|
||||
|
||||
The maximum atom size is of 255 characters. Prior to Erlang/OTP 20,
|
||||
only latin1 characters are allowed.
|
||||
The maximum atom size is of 255 Unicode codepoints.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
@@ -2172,6 +2209,11 @@ defmodule String do
|
||||
@doc """
|
||||
Returns an integer whose text representation is `string`.
|
||||
|
||||
`string` must be the string representation of an integer.
|
||||
Otherwise, an `ArgumentError` will be raised. If you want
|
||||
to parse a string that may contain an ill-formatted integer,
|
||||
use `Integer.parse/1`.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
@@ -2179,6 +2221,11 @@ defmodule String do
|
||||
iex> String.to_integer("123")
|
||||
123
|
||||
|
||||
Passing a string that does not represent an integer leads to an error:
|
||||
|
||||
String.to_integer("invalid data")
|
||||
#=> ** (ArgumentError) argument error
|
||||
|
||||
"""
|
||||
@spec to_integer(String.t()) :: integer
|
||||
def to_integer(string) do
|
||||
@@ -2228,18 +2275,95 @@ defmodule String do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a float value between 0 (equates to no similarity) and 1 (is an exact match)
|
||||
representing [Jaro](https://en.wikipedia.org/wiki/Jaro–Winkler_distance)
|
||||
Computes the bag distance between two strings.
|
||||
|
||||
Returns a float value between 0 and 1 representing the bag
|
||||
distance between `string1` and `string2`.
|
||||
|
||||
The Jaro distance metric is designed and best suited for short strings such as person names.
|
||||
The bag distance is meant to be an efficient approximation
|
||||
of the distance between two strings to quickly rule out strings
|
||||
that are largely different.
|
||||
|
||||
The algorithm is outlined in the "String Matching with Metric
|
||||
Trees Using an Approximate Distance" paper by Ilaria Bartolini,
|
||||
Paolo Ciaccia, and Marco Patella.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> String.jaro_distance("dwayne", "duane")
|
||||
iex> String.bag_distance("abc", "")
|
||||
0.0
|
||||
iex> String.bag_distance("abcd", "a")
|
||||
0.25
|
||||
iex> String.bag_distance("abcd", "ab")
|
||||
0.5
|
||||
iex> String.bag_distance("abcd", "abc")
|
||||
0.75
|
||||
iex> String.bag_distance("abcd", "abcd")
|
||||
1.0
|
||||
|
||||
"""
|
||||
@spec bag_distance(t, t) :: float
|
||||
@doc since: "1.8.0"
|
||||
def bag_distance(_string, ""), do: 0.0
|
||||
def bag_distance("", _string), do: 0.0
|
||||
|
||||
def bag_distance(string1, string2) do
|
||||
{bag1, length1} = string_to_bag(string1, %{}, 0)
|
||||
{bag2, length2} = string_to_bag(string2, %{}, 0)
|
||||
|
||||
diff1 = bag_difference(bag1, bag2)
|
||||
diff2 = bag_difference(bag2, bag1)
|
||||
|
||||
1 - max(diff1, diff2) / max(length1, length2)
|
||||
end
|
||||
|
||||
defp string_to_bag(string, bag, length) do
|
||||
case next_grapheme(string) do
|
||||
{char, rest} ->
|
||||
bag =
|
||||
case bag do
|
||||
%{^char => current} -> %{bag | char => current + 1}
|
||||
%{} -> Map.put(bag, char, 1)
|
||||
end
|
||||
|
||||
string_to_bag(rest, bag, length + 1)
|
||||
|
||||
nil ->
|
||||
{bag, length}
|
||||
end
|
||||
end
|
||||
|
||||
defp bag_difference(bag1, bag2) do
|
||||
Enum.reduce(bag1, 0, fn {char, count1}, sum ->
|
||||
case bag2 do
|
||||
%{^char => count2} -> sum + max(count1 - count2, 0)
|
||||
%{} -> sum + count1
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Computes the Jaro distance (similarity) between two strings.
|
||||
|
||||
Returns a float value between `0.0` (equates to no similarity) and `1.0`
|
||||
(is an exact match) representing [Jaro](https://en.wikipedia.org/wiki/Jaro-Winkler_distance)
|
||||
distance between `string1` and `string2`.
|
||||
|
||||
The Jaro distance metric is designed and best suited for short
|
||||
strings such as person names. Elixir itself uses this function
|
||||
to provide the "did you mean?" functionality. For instance, when you
|
||||
are calling a function in a module and you have a typo in the
|
||||
function name, we attempt to suggest the most similar function
|
||||
name available, if any, based on the `jaro_distance/2` score.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> String.jaro_distance("Dwayne", "Duane")
|
||||
0.8222222222222223
|
||||
iex> String.jaro_distance("even", "odd")
|
||||
0.0
|
||||
iex> String.jaro_distance("same", "same")
|
||||
1.0
|
||||
|
||||
"""
|
||||
@spec jaro_distance(t, t) :: float
|
||||
|
||||
+17
-14
@@ -31,21 +31,22 @@ defmodule StringIO do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> StringIO.open("foo", [], fn(pid) ->
|
||||
...> input = IO.gets(pid, ">")
|
||||
...> IO.write(pid, "The input was #{input}")
|
||||
...> StringIO.contents(pid)
|
||||
...> end)
|
||||
{:ok, {"", "The input was foo"}}
|
||||
iex> StringIO.open("foo", [], fn pid ->
|
||||
...> input = IO.gets(pid, ">")
|
||||
...> IO.write(pid, "The input was #{input}")
|
||||
...> StringIO.contents(pid)
|
||||
...> end)
|
||||
{:ok, {"", "The input was foo"}}
|
||||
|
||||
iex> StringIO.open("foo", [capture_prompt: true], fn(pid) ->
|
||||
...> input = IO.gets(pid, ">")
|
||||
...> IO.write(pid, "The input was #{input}")
|
||||
...> StringIO.contents(pid)
|
||||
...> end)
|
||||
{:ok, {"", ">The input was foo"}}
|
||||
iex> StringIO.open("foo", [capture_prompt: true], fn pid ->
|
||||
...> input = IO.gets(pid, ">")
|
||||
...> IO.write(pid, "The input was #{input}")
|
||||
...> StringIO.contents(pid)
|
||||
...> end)
|
||||
{:ok, {"", ">The input was foo"}}
|
||||
|
||||
"""
|
||||
@doc since: "1.7.0"
|
||||
@spec open(binary, keyword, (pid -> res)) :: {:ok, res} when res: var
|
||||
def open(string, options, function)
|
||||
when is_binary(string) and is_list(options) and is_function(function, 1) do
|
||||
@@ -90,7 +91,7 @@ defmodule StringIO do
|
||||
iex> StringIO.contents(pid)
|
||||
{"", ">"}
|
||||
|
||||
iex> StringIO.open("foo", fn(pid) ->
|
||||
iex> StringIO.open("foo", fn pid ->
|
||||
...> input = IO.gets(pid, ">")
|
||||
...> IO.write(pid, "The input was #{input}")
|
||||
...> StringIO.contents(pid)
|
||||
@@ -100,7 +101,7 @@ defmodule StringIO do
|
||||
"""
|
||||
@spec open(binary, keyword) :: {:ok, pid}
|
||||
@spec open(binary, (pid -> res)) :: {:ok, res} when res: var
|
||||
def open(path, options_or_function \\ [])
|
||||
def open(string, options_or_function \\ [])
|
||||
|
||||
def open(string, options_or_function) when is_binary(string) and is_list(options_or_function) do
|
||||
GenServer.start_link(__MODULE__, {string, options_or_function}, [])
|
||||
@@ -278,6 +279,8 @@ defmodule StringIO do
|
||||
{_, _, _} ->
|
||||
{{:error, req}, state}
|
||||
end
|
||||
rescue
|
||||
ArgumentError -> {{:error, req}, state}
|
||||
end
|
||||
|
||||
## get_chars
|
||||
|
||||
+139
-149
@@ -97,50 +97,11 @@ defmodule Supervisor do
|
||||
Supervisors support different strategies; in the example above, we
|
||||
have chosen `:one_for_one`. Furthermore, each supervisor can have many
|
||||
workers and/or supervisors as children, with each one having its own
|
||||
configuration (as outlined in the “Child specification” section).
|
||||
configuration (as outlined in the "Child specification" section).
|
||||
|
||||
The rest of this document will cover how child processes are started,
|
||||
how they can be specified, different supervision strategies and more.
|
||||
|
||||
## Start and shutdown
|
||||
|
||||
When the supervisor starts, it traverses all child specifications and
|
||||
then starts each child in the order they are defined. This is done by
|
||||
calling the function defined under the `:start` key in the child
|
||||
specification and typically defaults to `start_link/1`.
|
||||
|
||||
The `start_link/1` (or a custom) is then called for each child process.
|
||||
The `start_link/1` function must return `{:ok, pid}` where `pid` is the
|
||||
process identifier of a new process that is linked to the supervisor.
|
||||
The child process usually starts its work by executing the `init/1`
|
||||
callback. Generally speaking, the `init` callback is where we initialize
|
||||
and configure the child process.
|
||||
|
||||
The shutdown process happens in reverse order.
|
||||
|
||||
When a supervisor shuts down, it terminates all children in the opposite
|
||||
order they are listed. The termination happens by sending a shutdown exit
|
||||
signal, via `Process.exit(child_pid, :shutdown)`, to the child process and
|
||||
then awaiting for a time interval for the child process to terminate. This
|
||||
interval defaults to 5000 milliseconds. If the child process does not
|
||||
terminate in this interval, the supervisor abruptly terminates the child
|
||||
with reason `:kill`. The shutdown time can be configured in the child
|
||||
specification which is fully detailed in the next section.
|
||||
|
||||
If the child process is not trapping exits, it will shutdown immediately
|
||||
when it receives the first exit signal. If the child process is trapping
|
||||
exits, then the `terminate` callback is invoked, and the child process
|
||||
must terminate in a reasonable time interval before being abruptly
|
||||
terminated by the supervisor.
|
||||
|
||||
In other words, if it is important that a process cleans after itself
|
||||
when your application or the supervision tree is shutting down, then
|
||||
this process must trap exits and its child specification should specify
|
||||
the proper `:shutdown` value, ensuring it terminates within a reasonable
|
||||
interval.
|
||||
|
||||
Now that we understand the start and shutdown process, let's take a
|
||||
complete look at all of the options provided in the child specification.
|
||||
The rest of this document will cover how child processes are specified,
|
||||
how they can be started and stopped, different supervision strategies
|
||||
and more.
|
||||
|
||||
## Child specification
|
||||
|
||||
@@ -183,11 +144,11 @@ defmodule Supervisor do
|
||||
terminated using `Process.exit(child, :kill)`.
|
||||
|
||||
* any integer >= 0 - the amount of time in milliseconds that the
|
||||
supervisor will wait for children to terminate after emitting a
|
||||
supervisor will wait for its children to terminate after emitting a
|
||||
`Process.exit(child, :shutdown)` signal. If the child process is
|
||||
not trapping exits, the initial `:shutdown` signal will terminate
|
||||
the child process immediately. If the child process is trapping
|
||||
exits, it has the given amount of time in milliseconds to terminate.
|
||||
exits, it has the given amount of time to terminate.
|
||||
If it doesn't terminate within the specified time, the child process
|
||||
is unconditionally terminated by the supervisor via
|
||||
`Process.exit(child, :kill)`.
|
||||
@@ -195,7 +156,7 @@ defmodule Supervisor do
|
||||
* `:infinity` - works as an integer except the supervisor will wait
|
||||
indefinitely for the child to terminate. If the child process is a
|
||||
supervisor, the recommended value is `:infinity` to give the supervisor
|
||||
and its children enough time to shutdown. This option can be used with
|
||||
and its children enough time to shut down. This option can be used with
|
||||
regular workers but doing so is discouraged and requires extreme care.
|
||||
If not used carefully, the child process will never terminate,
|
||||
preventing your application from terminating as well.
|
||||
@@ -247,30 +208,31 @@ defmodule Supervisor do
|
||||
|
||||
The supervisor will then invoke `Stack.child_spec([:hello])` to retrieve a
|
||||
child specification. Now the `Stack` module is responsible for building its
|
||||
own specification. By default, `use GenServer` defines a `Stack.child_spec/1`
|
||||
function which returns the same child specification we had before:
|
||||
own specification, for example, we could write:
|
||||
|
||||
%{
|
||||
id: Stack,
|
||||
start: {Stack, :start_link, [[:hello]]}
|
||||
}
|
||||
def child_spec(arg) do
|
||||
%{
|
||||
id: Stack,
|
||||
start: {Stack, :start_link, [arg]}
|
||||
}
|
||||
end
|
||||
|
||||
It is also possible to simply pass the `Stack` module as a child:
|
||||
Luckily for us, `use GenServer` already defines a `Stack.child_spec/1`
|
||||
exactly like above. If you need to customize the `GenServer`, you can
|
||||
pass the options directly to `use GenServer`:
|
||||
|
||||
use GenServer, restart: :transient
|
||||
|
||||
Finally, note it is also possible to simply pass the `Stack` module as
|
||||
a child:
|
||||
|
||||
children = [
|
||||
Stack
|
||||
]
|
||||
|
||||
When only the module name is given, it is equivalent to `{Stack, []}`. In this
|
||||
case, we will end-up with a child specification that looks like this:
|
||||
|
||||
%{
|
||||
id: Stack,
|
||||
start: {Stack, :start_link, [[]]}
|
||||
}
|
||||
|
||||
When only the module name is given, it is equivalent to `{Stack, []}`.
|
||||
By replacing the map specification by `{Stack, [:hello]}` or `Stack`, we keep
|
||||
the child specification encapsulated in the Stack module, using the default
|
||||
the child specification encapsulated in the `Stack` module, using the default
|
||||
implementation defined by `use GenServer`. We can now share our `Stack` worker
|
||||
with other developers and they can add it directly to their supervision tree
|
||||
without worrying about the low-level details of the worker.
|
||||
@@ -285,7 +247,7 @@ defmodule Supervisor do
|
||||
* a module - such as `Stack`. In this case, `Stack.child_spec([])`
|
||||
is called to retrieve the child specification
|
||||
|
||||
If you need to convert how a tuple or module child specification to a map or
|
||||
If you need to convert a tuple or a module child specification to a map or
|
||||
modify a child specification, you can use the `Supervisor.child_spec/2` function.
|
||||
For example, to run the stack with a different `:id` and a `:shutdown` value of
|
||||
10 seconds (10_000 milliseconds):
|
||||
@@ -294,55 +256,6 @@ defmodule Supervisor do
|
||||
Supervisor.child_spec({Stack, [:hello]}, id: MyStack, shutdown: 10_000)
|
||||
]
|
||||
|
||||
The call to `Supervisor.child_spec/2` above will return the following specification:
|
||||
|
||||
%{
|
||||
id: MyStack,
|
||||
start: {Stack, :start_link, [[:hello]]},
|
||||
shutdown: 10_000
|
||||
}
|
||||
|
||||
You may also configure the child specification in the Stack module itself to
|
||||
use a different `:id` or `:shutdown` value by passing options to `use GenServer`:
|
||||
|
||||
defmodule Stack do
|
||||
use GenServer, id: MyStack, shutdown: 10_000
|
||||
|
||||
The options above will customize the `Stack.child_spec/1` function defined
|
||||
by `use GenServer`. It accepts the same options as the `Supervisor.child_spec/2`
|
||||
function.
|
||||
|
||||
You may also completely override the `child_spec/1` function in the Stack module
|
||||
and return your own child specification. Note there is no guarantee the `child_spec/1`
|
||||
function will be called by the Supervisor process, as other processes may invoke
|
||||
it to retrieve the child specification before reaching the supervisor.
|
||||
|
||||
## Exit reasons and restarts
|
||||
|
||||
A supervisor restarts a child process depending on its `:restart`
|
||||
configuration. For example, when `:restart` is set to `:transient`, the
|
||||
supervisor does not restart the child in case it exits with reason `:normal`,
|
||||
`:shutdown` or `{:shutdown, term}`.
|
||||
|
||||
So one may ask: which exit reason should I choose when exiting? There are
|
||||
three options:
|
||||
|
||||
* `:normal` - in such cases, the exit won't be logged, there is no restart
|
||||
in transient mode, and linked processes do not exit
|
||||
|
||||
* `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be
|
||||
logged, there is no restart in transient mode, and linked processes exit
|
||||
with the same reason unless they're trapping exits
|
||||
|
||||
* any other term - in such cases, the exit will be logged, there are
|
||||
restarts in transient mode, and linked processes exit with the same
|
||||
reason unless they're trapping exits
|
||||
|
||||
Notice that the supervisor that reaches maximum restart intensity will exit with
|
||||
`:shutdown` reason. In this case the supervisor will only be restarted if its
|
||||
child specification was defined with the `:restart` option set to `:permanent`
|
||||
(the default).
|
||||
|
||||
## Module-based supervisors
|
||||
|
||||
In the example above, a supervisor was started by passing the supervision
|
||||
@@ -353,12 +266,12 @@ defmodule Supervisor do
|
||||
# Automatically defines child_spec/1
|
||||
use Supervisor
|
||||
|
||||
def start_link(arg) do
|
||||
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
|
||||
def start_link(init_arg) do
|
||||
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
|
||||
end
|
||||
|
||||
@impl true
|
||||
def init(_arg) do
|
||||
def init(_init_arg) do
|
||||
children = [
|
||||
{Stack, [:hello]}
|
||||
]
|
||||
@@ -375,7 +288,8 @@ defmodule Supervisor do
|
||||
`c:init/1` callback.
|
||||
|
||||
`use Supervisor` also defines a `child_spec/1` function which allows
|
||||
us to run `MyApp.Supervisor` as a child of another supervisor:
|
||||
us to run `MyApp.Supervisor` as a child of another supervisor or
|
||||
at the top of your supervision tree as:
|
||||
|
||||
children = [
|
||||
MyApp.Supervisor
|
||||
@@ -387,27 +301,35 @@ defmodule Supervisor do
|
||||
module only at the top of your supervision tree, generally in the
|
||||
`c:Application.start/2` callback. We recommend using module-based
|
||||
supervisors for any other supervisor in your application, so they
|
||||
can run as a child of another supervision in the tree. The generated
|
||||
`child_spec/1` can be customized with the following options:
|
||||
can run as a child of another supervisor in the tree. The `child_spec/1`
|
||||
generated automatically by `Supervisor` can be customized with the
|
||||
following options:
|
||||
|
||||
* `:id` - the child specification identifier, defaults to the current module
|
||||
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
|
||||
* `:restart` - when the supervisor should be restarted, defaults to `:permanent`
|
||||
|
||||
The `@doc` annotation immediately preceding `use Supervisor` will be
|
||||
attached to the generated `child_spec/1` function.
|
||||
|
||||
## `start_link/2`, `init/2`, and strategies
|
||||
|
||||
So far we have started the supervisor passing a single child as a tuple
|
||||
as well as a strategy called `:one_for_one`:
|
||||
|
||||
Supervisor.start_link([
|
||||
children = [
|
||||
{Stack, [:hello]}
|
||||
], strategy: :one_for_one)
|
||||
]
|
||||
|
||||
Supervisor.start_link(children, strategy: :one_for_one)
|
||||
|
||||
or from inside the `c:init/1` callback:
|
||||
|
||||
Supervisor.init([
|
||||
children = [
|
||||
{Stack, [:hello]}
|
||||
], strategy: :one_for_one)
|
||||
]
|
||||
|
||||
Supervisor.init(children, strategy: :one_for_one)
|
||||
|
||||
The first argument given to `start_link/2` and `init/2` is a list of child
|
||||
specifications as defined in the "child_spec/1" section above.
|
||||
@@ -454,10 +376,73 @@ defmodule Supervisor do
|
||||
differently when this strategy was used. See the `DynamicSupervisor` module
|
||||
for more information and migration strategies.
|
||||
|
||||
## Name registration
|
||||
### Name registration
|
||||
|
||||
A supervisor is bound to the same name registration rules as a `GenServer`.
|
||||
Read more about these rules in the documentation for `GenServer`.
|
||||
|
||||
## Start and shutdown
|
||||
|
||||
When the supervisor starts, it traverses all child specifications and
|
||||
then starts each child in the order they are defined. This is done by
|
||||
calling the function defined under the `:start` key in the child
|
||||
specification and typically defaults to `start_link/1`.
|
||||
|
||||
The `start_link/1` (or a custom) is then called for each child process.
|
||||
The `start_link/1` function must return `{:ok, pid}` where `pid` is the
|
||||
process identifier of a new process that is linked to the supervisor.
|
||||
The child process usually starts its work by executing the `init/1`
|
||||
callback. Generally speaking, the `init` callback is where we initialize
|
||||
and configure the child process.
|
||||
|
||||
The shutdown process happens in reverse order.
|
||||
|
||||
When a supervisor shuts down, it terminates all children in the opposite
|
||||
order they are listed. The termination happens by sending a shutdown exit
|
||||
signal, via `Process.exit(child_pid, :shutdown)`, to the child process and
|
||||
then awaiting for a time interval for the child process to terminate. This
|
||||
interval defaults to 5000 milliseconds. If the child process does not
|
||||
terminate in this interval, the supervisor abruptly terminates the child
|
||||
with reason `:kill`. The shutdown time can be configured in the child
|
||||
specification which is fully detailed in the next section.
|
||||
|
||||
If the child process is not trapping exits, it will shutdown immediately
|
||||
when it receives the first exit signal. If the child process is trapping
|
||||
exits, then the `terminate` callback is invoked, and the child process
|
||||
must terminate in a reasonable time interval before being abruptly
|
||||
terminated by the supervisor.
|
||||
|
||||
In other words, if it is important that a process cleans after itself
|
||||
when your application or the supervision tree is shutting down, then
|
||||
this process must trap exits and its child specification should specify
|
||||
the proper `:shutdown` value, ensuring it terminates within a reasonable
|
||||
interval.
|
||||
|
||||
## Exit reasons and restarts
|
||||
|
||||
A supervisor restarts a child process depending on its `:restart` configuration.
|
||||
For example, when `:restart` is set to `:transient`, the supervisor does not
|
||||
restart the child in case it exits with reason `:normal`, `:shutdown` or
|
||||
`{:shutdown, term}`.
|
||||
|
||||
So one may ask: which exit reason should I choose when exiting? There are
|
||||
three options:
|
||||
|
||||
* `:normal` - in such cases, the exit won't be logged, there is no restart
|
||||
in transient mode, and linked processes do not exit
|
||||
|
||||
* `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be
|
||||
logged, there is no restart in transient mode, and linked processes exit
|
||||
with the same reason unless they're trapping exits
|
||||
|
||||
* any other term - in such cases, the exit will be logged, there are
|
||||
restarts in transient mode, and linked processes exit with the same
|
||||
reason unless they're trapping exits
|
||||
|
||||
Notice that the supervisor that reaches maximum restart intensity will exit with
|
||||
`:shutdown` reason. In this case the supervisor will only be restarted if its
|
||||
child specification was defined with the `:restart` option set to `:permanent`
|
||||
(the default).
|
||||
"""
|
||||
|
||||
@doc false
|
||||
@@ -466,15 +451,18 @@ defmodule Supervisor do
|
||||
import Supervisor.Spec
|
||||
@behaviour Supervisor
|
||||
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
See `Supervisor`.
|
||||
"""
|
||||
end
|
||||
|
||||
def child_spec(init_arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
start: {__MODULE__, :start_link, [arg]},
|
||||
start: {__MODULE__, :start_link, [init_arg]},
|
||||
type: :supervisor
|
||||
}
|
||||
|
||||
@@ -491,7 +479,7 @@ defmodule Supervisor do
|
||||
Developers typically invoke `Supervisor.init/2` at the end of their
|
||||
init callback to return the proper supervision flags.
|
||||
"""
|
||||
@callback init(args :: term) ::
|
||||
@callback init(init_arg :: term) ::
|
||||
{:ok, {:supervisor.sup_flags(), [:supervisor.child_spec()]}}
|
||||
| :ignore
|
||||
|
||||
@@ -544,10 +532,10 @@ defmodule Supervisor do
|
||||
@doc """
|
||||
Starts a supervisor with the given children.
|
||||
|
||||
The children is a list of modules, 2-element tuples with module and
|
||||
The children is a list of modules, two-element tuples with module and
|
||||
arguments or a map with the child specification. A strategy is required
|
||||
to be provided through the `:strategy` option. See
|
||||
"start_link/2, init/2 and strategies" for examples and other options.
|
||||
"start_link/2, init/2, and strategies" for examples and other options.
|
||||
|
||||
The options can also be used to register a supervisor name.
|
||||
The supported values are described under the "Name registration"
|
||||
@@ -577,11 +565,11 @@ defmodule Supervisor do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Receives a list of children to initialize and a set of options.
|
||||
Receives a list of `children` to initialize and a set of `options`.
|
||||
|
||||
This is typically invoked at the end of the `c:init/1` callback of
|
||||
module-based supervisors. See the sections "Module-based supervisors"
|
||||
and "start_link/2, init/2 and strategies" in the module
|
||||
and "start_link/2, init/2, and strategies" in the module
|
||||
documentation for more information.
|
||||
|
||||
This function returns a tuple containing the supervisor
|
||||
@@ -589,10 +577,12 @@ defmodule Supervisor do
|
||||
|
||||
## Examples
|
||||
|
||||
def init(_arg) do
|
||||
Supervisor.init([
|
||||
def init(_init_arg) do
|
||||
children = [
|
||||
{Stack, [:hello]}
|
||||
], strategy: :one_for_one)
|
||||
]
|
||||
|
||||
Supervisor.init(children, strategy: :one_for_one)
|
||||
end
|
||||
|
||||
## Options
|
||||
@@ -604,15 +594,15 @@ defmodule Supervisor do
|
||||
* `:max_restarts` - the maximum number of restarts allowed in
|
||||
a time frame. Defaults to `3`.
|
||||
|
||||
* `:max_seconds` - the time frame in which `:max_restarts` applies.
|
||||
Defaults to `5`.
|
||||
* `:max_seconds` - the time frame in seconds in which `:max_restarts`
|
||||
applies. Defaults to `5`.
|
||||
|
||||
The `:strategy` option is required and by default a maximum of 3 restarts
|
||||
is allowed within 5 seconds. Check the `Supervisor` module for a detailed
|
||||
description of the available strategies.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
# TODO: Warn if simple_one_for_one strategy is used on Elixir v1.8.
|
||||
# TODO: Warn if simple_one_for_one strategy is used on Elixir v1.9
|
||||
@spec init([:supervisor.child_spec() | {module, term} | module], [init_option]) :: {:ok, tuple}
|
||||
def init(children, options) when is_list(children) and is_list(options) do
|
||||
unless strategy = options[:strategy] do
|
||||
@@ -750,10 +740,10 @@ defmodule Supervisor do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts a module-based supervisor process with the given `module` and `arg`.
|
||||
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 `arg` as its argument. The `c:init/1` callback must return a
|
||||
`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/2`
|
||||
function.
|
||||
|
||||
@@ -772,19 +762,19 @@ defmodule Supervisor do
|
||||
# all to start_link(children, options).
|
||||
@spec start_link(module, term) :: on_start
|
||||
@spec start_link(module, term, GenServer.options()) :: on_start
|
||||
def start_link(module, arg, options \\ []) when is_list(options) do
|
||||
def start_link(module, init_arg, options \\ []) when is_list(options) do
|
||||
case Keyword.get(options, :name) do
|
||||
nil ->
|
||||
:supervisor.start_link(module, arg)
|
||||
:supervisor.start_link(module, init_arg)
|
||||
|
||||
atom when is_atom(atom) ->
|
||||
:supervisor.start_link({:local, atom}, module, arg)
|
||||
:supervisor.start_link({:local, atom}, module, init_arg)
|
||||
|
||||
{:global, _term} = tuple ->
|
||||
:supervisor.start_link(tuple, module, arg)
|
||||
:supervisor.start_link(tuple, module, init_arg)
|
||||
|
||||
{:via, via_module, _term} = tuple when is_atom(via_module) ->
|
||||
:supervisor.start_link(tuple, module, arg)
|
||||
:supervisor.start_link(tuple, module, init_arg)
|
||||
|
||||
other ->
|
||||
raise ArgumentError, """
|
||||
@@ -830,7 +820,7 @@ defmodule Supervisor do
|
||||
call(supervisor, {:start_child, child_spec})
|
||||
end
|
||||
|
||||
# TODO: Deprecate this on Elixir v1.8. Remove and update typespec on v2.0.
|
||||
# TODO: Deprecate this on Elixir v1.9. Remove and update typespec on v2.0.
|
||||
def start_child(supervisor, args) when is_list(args) do
|
||||
call(supervisor, {:start_child, args})
|
||||
end
|
||||
@@ -857,7 +847,7 @@ defmodule Supervisor do
|
||||
when error: :not_found | :simple_one_for_one
|
||||
def terminate_child(supervisor, child_id)
|
||||
|
||||
# TODO: Deprecate this clause on Elixir v1.8
|
||||
# TODO: Deprecate this clause on Elixir v1.9
|
||||
def terminate_child(supervisor, pid) when is_pid(pid) do
|
||||
call(supervisor, {:terminate_child, pid})
|
||||
end
|
||||
|
||||
@@ -86,7 +86,7 @@ defmodule Supervisor.Spec do
|
||||
In this case the supervisor will only be restarted if its child specification was defined with
|
||||
the `:restart` option is set to `:permanent` (the default).
|
||||
|
||||
### Shutdown values (:shutdown)
|
||||
### Shutdown values (`:shutdown`)
|
||||
|
||||
The following shutdown values are supported in the `:shutdown` option:
|
||||
|
||||
@@ -94,14 +94,14 @@ defmodule Supervisor.Spec do
|
||||
using `Process.exit(child, :kill)`
|
||||
|
||||
* `:infinity` - if the child process is a supervisor, this is a mechanism
|
||||
to give the subtree enough time to shutdown; it can also be used with
|
||||
to give the subtree enough time to shut down; it can also be used with
|
||||
workers with care
|
||||
|
||||
* any integer - the value of `:shutdown` can also be any integer meaning
|
||||
* a non-negative integer - the amount of time in milliseconds
|
||||
that the supervisor tells the child process to terminate by calling
|
||||
`Process.exit(child, :shutdown)` and then waits for an exit signal back.
|
||||
If no exit signal is received within the specified time (the value of this
|
||||
option, in milliseconds), the child process is unconditionally terminated
|
||||
If no exit signal is received within the specified time,
|
||||
the child process is unconditionally terminated
|
||||
using `Process.exit(child, :kill)`
|
||||
|
||||
"""
|
||||
@@ -109,7 +109,7 @@ defmodule Supervisor.Spec do
|
||||
@moduledoc deprecated:
|
||||
"Use the new child specifications outlined in the Supervisor module instead"
|
||||
|
||||
# TODO: Deprecate all functions in this module on Elixir v1.8.
|
||||
# TODO: Deprecate all functions in this module on Elixir v1.9.
|
||||
# Also deprecate entry in Supervisor.Default.
|
||||
|
||||
@typedoc "Supported strategies"
|
||||
@@ -135,8 +135,8 @@ defmodule Supervisor.Spec do
|
||||
{child_id, start_fun :: {module, atom, [term]}, restart, shutdown, worker, modules}
|
||||
|
||||
@doc """
|
||||
Receives a list of children (workers or supervisors) to
|
||||
supervise and a set of options.
|
||||
Receives a list of `children` (workers or supervisors) to
|
||||
supervise and a set of `options`.
|
||||
|
||||
Returns a tuple containing the supervisor specification. This tuple can be
|
||||
used as the return value of the `c:init/1` callback when implementing a
|
||||
@@ -216,14 +216,16 @@ defmodule Supervisor.Spec do
|
||||
By default, the function `start_link` is invoked on the given
|
||||
module. Overall, the default values for the options are:
|
||||
|
||||
[id: module,
|
||||
function: :start_link,
|
||||
restart: :permanent,
|
||||
shutdown: 5000,
|
||||
modules: [module]]
|
||||
[
|
||||
id: module,
|
||||
function: :start_link,
|
||||
restart: :permanent,
|
||||
shutdown: 5000,
|
||||
modules: [module]
|
||||
]
|
||||
|
||||
Check the documentation for the `Supervisor.Spec` module for more
|
||||
information on the options.
|
||||
See the "Supervisor and worker options" section in the `Supervisor.Spec` module for more
|
||||
information on the available options.
|
||||
"""
|
||||
@spec worker(
|
||||
module,
|
||||
@@ -242,19 +244,21 @@ defmodule Supervisor.Spec do
|
||||
Defines the given `module` as a supervisor which will be started
|
||||
with the given arguments.
|
||||
|
||||
supervisor(ExUnit.Runner, [], restart: :permanent)
|
||||
supervisor(module, [], restart: :permanent)
|
||||
|
||||
By default, the function `start_link` is invoked on the given
|
||||
module. Overall, the default values for the options are:
|
||||
|
||||
[id: module,
|
||||
function: :start_link,
|
||||
restart: :permanent,
|
||||
shutdown: :infinity,
|
||||
modules: [module]]
|
||||
[
|
||||
id: module,
|
||||
function: :start_link,
|
||||
restart: :permanent,
|
||||
shutdown: :infinity,
|
||||
modules: [module]
|
||||
]
|
||||
|
||||
Check the documentation for the `Supervisor.Spec` module for more
|
||||
information on the options.
|
||||
See the "Supervisor and worker options" section in the `Supervisor.Spec` module for more
|
||||
information on the available options.
|
||||
"""
|
||||
@spec supervisor(
|
||||
module,
|
||||
|
||||
+65
-50
@@ -73,22 +73,13 @@ defmodule System do
|
||||
parts_per_second` seconds. For example, using the `:millisecond` time unit
|
||||
is equivalent to using `1000` as the time unit (as the time will be returned
|
||||
in 1/1000 seconds - milliseconds).
|
||||
|
||||
Keep in mind the Erlang API prior to version 19.1 will use `:milli_seconds`,
|
||||
`:micro_seconds` and `:nano_seconds` as time units although Elixir normalizes
|
||||
their spelling to match the SI convention.
|
||||
"""
|
||||
# TODO: Warn all old mappings once Elixir requires Erlang/OTP 19.1+ (on v1.8)
|
||||
@type time_unit ::
|
||||
:second
|
||||
| :millisecond
|
||||
| :microsecond
|
||||
| :nanosecond
|
||||
| pos_integer
|
||||
| :seconds
|
||||
| :milliseconds
|
||||
| :microseconds
|
||||
| :nanoseconds
|
||||
|
||||
@base_dir :filename.join(__DIR__, "../../..")
|
||||
@version_file :filename.join(@base_dir, "VERSION")
|
||||
@@ -110,7 +101,7 @@ defmodule System do
|
||||
# Read and strip the version from the VERSION file.
|
||||
defmacrop get_version do
|
||||
case read_stripped(@version_file) do
|
||||
"" -> raise RuntimeError, message: "could not read the version number from VERSION"
|
||||
"" -> raise "could not read the version number from VERSION"
|
||||
data -> data
|
||||
end
|
||||
end
|
||||
@@ -149,6 +140,7 @@ defmodule System do
|
||||
@doc """
|
||||
Returns the endianness.
|
||||
"""
|
||||
@spec endianness() :: :little | :big
|
||||
def endianness do
|
||||
:erlang.system_info(:endian)
|
||||
end
|
||||
@@ -157,6 +149,7 @@ defmodule System do
|
||||
Returns the endianness the system was compiled with.
|
||||
"""
|
||||
@endianness :erlang.system_info(:endian)
|
||||
@spec compiled_endianness() :: :little | :big
|
||||
def compiled_endianness do
|
||||
@endianness
|
||||
end
|
||||
@@ -222,32 +215,32 @@ defmodule System do
|
||||
Returns the current working directory or `nil` if one
|
||||
is not available.
|
||||
"""
|
||||
# TODO: Remove by 2.0
|
||||
@deprecated "Use File.cwd/0 instead"
|
||||
@spec cwd() :: String.t() | nil
|
||||
def cwd do
|
||||
case :file.get_cwd() do
|
||||
{:ok, base} -> IO.chardata_to_string(fix_drive_letter(base))
|
||||
case File.cwd() do
|
||||
{:ok, cwd} -> cwd
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp fix_drive_letter([l, ?:, ?/ | rest] = original) when l in ?A..?Z do
|
||||
case :os.type() do
|
||||
{:win32, _} -> [l + ?a - ?A, ?:, ?/ | rest]
|
||||
_ -> original
|
||||
end
|
||||
end
|
||||
|
||||
defp fix_drive_letter(original), do: original
|
||||
|
||||
@doc """
|
||||
Current working directory, exception on error.
|
||||
|
||||
Returns the current working directory or raises `RuntimeError`.
|
||||
"""
|
||||
# TODO: Remove by 2.0
|
||||
@deprecated "Use File.cwd!/0 instead"
|
||||
@spec cwd!() :: String.t()
|
||||
def cwd! do
|
||||
cwd() ||
|
||||
raise RuntimeError,
|
||||
message:
|
||||
"could not get a current working directory, the current location is not accessible"
|
||||
case File.cwd() do
|
||||
{:ok, cwd} ->
|
||||
cwd
|
||||
|
||||
_ ->
|
||||
raise "could not get a current working directory, the current location is not accessible"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -255,6 +248,7 @@ defmodule System do
|
||||
|
||||
Returns the user home directory (platform independent).
|
||||
"""
|
||||
@spec user_home() :: String.t() | nil
|
||||
def user_home do
|
||||
:elixir_config.get(:home)
|
||||
end
|
||||
@@ -265,10 +259,9 @@ defmodule System do
|
||||
Same as `user_home/0` but raises `RuntimeError`
|
||||
instead of returning `nil` if no user home is set.
|
||||
"""
|
||||
@spec user_home!() :: String.t()
|
||||
def user_home! do
|
||||
user_home() ||
|
||||
raise RuntimeError,
|
||||
message: "could not find the user home, please set the HOME environment variable"
|
||||
user_home() || raise "could not find the user home, please set the HOME environment variable"
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
@@ -285,9 +278,17 @@ defmodule System do
|
||||
|
||||
Returns `nil` if none of the above are writable.
|
||||
"""
|
||||
@spec tmp_dir() :: String.t() | nil
|
||||
def tmp_dir do
|
||||
write_env_tmp_dir('TMPDIR') || write_env_tmp_dir('TEMP') || write_env_tmp_dir('TMP') ||
|
||||
write_tmp_dir('/tmp') || ((cwd = cwd()) && write_tmp_dir(cwd))
|
||||
write_tmp_dir('/tmp') || write_cwd_tmp_dir()
|
||||
end
|
||||
|
||||
defp write_cwd_tmp_dir do
|
||||
case File.cwd() do
|
||||
{:ok, cwd} -> write_tmp_dir(cwd)
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -296,12 +297,10 @@ defmodule System do
|
||||
Same as `tmp_dir/0` but raises `RuntimeError`
|
||||
instead of returning `nil` if no temp dir is set.
|
||||
"""
|
||||
@spec tmp_dir!() :: String.t()
|
||||
def tmp_dir! do
|
||||
tmp_dir() ||
|
||||
raise RuntimeError,
|
||||
message:
|
||||
"could not get a writable temporary directory, " <>
|
||||
"please set the TMPDIR environment variable"
|
||||
raise "could not get a writable temporary directory, please set the TMPDIR environment variable"
|
||||
end
|
||||
|
||||
defp write_env_tmp_dir(env) do
|
||||
@@ -340,8 +339,10 @@ defmodule System do
|
||||
|
||||
The function must receive the exit status code as an argument.
|
||||
"""
|
||||
@spec at_exit((non_neg_integer -> any)) :: :ok
|
||||
def at_exit(fun) when is_function(fun, 1) do
|
||||
:elixir_config.update(:at_exit, &[fun | &1])
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -454,12 +455,13 @@ defmodule System do
|
||||
|
||||
Note that the Erlang VM (and therefore this function) does not
|
||||
return the current stacktrace but rather the stacktrace of the
|
||||
latest exception.
|
||||
latest exception. To retrieve the stacktrace of the current process,
|
||||
use `Process.info(self(), :current_stacktrace)` instead.
|
||||
"""
|
||||
# TODO: Fully deprecate it on Elixir v1.9.
|
||||
# It is currently partially deprecated in elixir_dispatch.erl
|
||||
def stacktrace do
|
||||
:erlang.get_stacktrace()
|
||||
apply(:erlang, :get_stacktrace, [])
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -564,10 +566,10 @@ defmodule System do
|
||||
iex> System.cmd("echo", ["hello"])
|
||||
{"hello\n", 0}
|
||||
|
||||
iex> System.cmd("echo", ["hello"]), env: [{"MIX_ENV", "test"}]
|
||||
iex> System.cmd("echo", ["hello"], env: [{"MIX_ENV", "test"}])
|
||||
{"hello\n", 0}
|
||||
|
||||
iex> System.cmd("echo", ["hello"]), into: IO.stream(:stdio, :line)
|
||||
iex> System.cmd("echo", ["hello"], into: IO.stream(:stdio, :line))
|
||||
hello
|
||||
{%IO.Stream{}, 0}
|
||||
|
||||
@@ -881,26 +883,39 @@ defmodule System do
|
||||
|
||||
defp normalize_time_unit(:native), do: :native
|
||||
|
||||
defp normalize_time_unit(:second), do: :seconds
|
||||
defp normalize_time_unit(:millisecond), do: :milli_seconds
|
||||
defp normalize_time_unit(:microsecond), do: :micro_seconds
|
||||
defp normalize_time_unit(:nanosecond), do: :nano_seconds
|
||||
defp normalize_time_unit(:second), do: :second
|
||||
defp normalize_time_unit(:millisecond), do: :millisecond
|
||||
defp normalize_time_unit(:microsecond), do: :microsecond
|
||||
defp normalize_time_unit(:nanosecond), do: :nanosecond
|
||||
|
||||
defp normalize_time_unit(:seconds), do: :seconds
|
||||
defp normalize_time_unit(:milliseconds), do: :milli_seconds
|
||||
defp normalize_time_unit(:microseconds), do: :micro_seconds
|
||||
defp normalize_time_unit(:nanoseconds), do: :nano_seconds
|
||||
defp normalize_time_unit(:seconds), do: warn(:seconds, :second)
|
||||
defp normalize_time_unit(:milliseconds), do: warn(:milliseconds, :millisecond)
|
||||
defp normalize_time_unit(:microseconds), do: warn(:microseconds, :microsecond)
|
||||
defp normalize_time_unit(:nanoseconds), do: warn(:nanoseconds, :nanosecond)
|
||||
|
||||
defp normalize_time_unit(:milli_seconds), do: warn(:milli_seconds, :millisecond)
|
||||
defp normalize_time_unit(:micro_seconds), do: warn(:micro_seconds, :microsecond)
|
||||
defp normalize_time_unit(:nano_seconds), do: warn(:nano_seconds, :nanosecond)
|
||||
|
||||
defp normalize_time_unit(unit) when is_integer(unit) and unit > 0, do: unit
|
||||
|
||||
defp normalize_time_unit(erlang_unit)
|
||||
when erlang_unit in [:milli_seconds, :micro_seconds, :nano_seconds] do
|
||||
erlang_unit
|
||||
end
|
||||
|
||||
defp normalize_time_unit(other) do
|
||||
raise ArgumentError,
|
||||
"unsupported time unit. Expected :second, :millisecond, " <>
|
||||
":microsecond, :nanosecond, or a positive integer, " <> "got #{inspect(other)}"
|
||||
end
|
||||
|
||||
defp warn(unit, replacement_unit) do
|
||||
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
|
||||
stacktrace = Enum.drop(stacktrace, 3)
|
||||
|
||||
:elixir_config.warn({System, unit}, stacktrace) &&
|
||||
IO.warn(
|
||||
"deprecated time unit: #{inspect(unit)}. A time unit should be " <>
|
||||
":second, :millisecond, :microsecond, :nanosecond, or a positive integer",
|
||||
stacktrace
|
||||
)
|
||||
|
||||
replacement_unit
|
||||
end
|
||||
end
|
||||
|
||||
+160
-93
@@ -9,7 +9,7 @@ defmodule Task do
|
||||
by computing a value asynchronously:
|
||||
|
||||
task = Task.async(fn -> do_some_work() end)
|
||||
res = do_some_other_work()
|
||||
res = do_some_other_work()
|
||||
res + Task.await(task)
|
||||
|
||||
Tasks spawned with `async` can be awaited on by their caller
|
||||
@@ -62,8 +62,8 @@ defmodule Task do
|
||||
a function to run:
|
||||
|
||||
Supervisor.start_link([
|
||||
{Task, fn -> ... some function ... end}
|
||||
])
|
||||
{Task, fn -> :some_work end}
|
||||
], strategy: :one_for_one)
|
||||
|
||||
However, if you want to invoke a specific module, function and
|
||||
arguments, or give the task process a name, you need to define
|
||||
@@ -85,21 +85,21 @@ defmodule Task do
|
||||
|
||||
Supervisor.start_link([
|
||||
{MyTask, arg}
|
||||
])
|
||||
], strategy: :one_for_one)
|
||||
|
||||
Since these tasks are supervised and not directly linked to
|
||||
the caller, they cannot be awaited on. Note `start_link/1`,
|
||||
unlike `async/1`, returns `{:ok, pid}` (which is the result
|
||||
expected by supervisors).
|
||||
the caller, they cannot be awaited on. `start_link/1`, unlike
|
||||
`async/1`, returns `{:ok, pid}` (which is the result expecte
|
||||
by supervisors).
|
||||
|
||||
Note `use Task` defines a `child_spec/1` function, allowing the
|
||||
`use Task` defines a `child_spec/1` function, allowing the
|
||||
defined module to be put under a supervision tree. The generated
|
||||
`child_spec/1` can be customized with the following options:
|
||||
|
||||
* `:id` - the child specification identifier, defaults to the current module
|
||||
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
|
||||
* `:restart` - when the child should be restarted, defaults to `:temporary`
|
||||
* `:shutdown` - how to shut down the child
|
||||
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
|
||||
|
||||
Opposite to `GenServer`, `Agent` and `Supervisor`, a Task has
|
||||
a default `:restart` of `:temporary`. This means the task will
|
||||
@@ -112,7 +112,10 @@ defmodule Task do
|
||||
|
||||
use Task, restart: :permanent
|
||||
|
||||
See the `Supervisor` docs for more information.
|
||||
See the "Child specification" section in the `Supervisor` module
|
||||
for more detailed information. The `@doc` annotation immediately
|
||||
preceding `use Task` will be attached to the generated `child_spec/1`
|
||||
function.
|
||||
|
||||
## Dynamically supervised tasks
|
||||
|
||||
@@ -122,9 +125,12 @@ defmodule Task do
|
||||
A short example is:
|
||||
|
||||
{:ok, pid} = Task.Supervisor.start_link()
|
||||
task = Task.Supervisor.async(pid, fn ->
|
||||
# Do something
|
||||
end)
|
||||
|
||||
task =
|
||||
Task.Supervisor.async(pid, fn ->
|
||||
# Do something
|
||||
end)
|
||||
|
||||
Task.await(task)
|
||||
|
||||
However, in the majority of cases, you want to add the task supervisor
|
||||
@@ -132,7 +138,7 @@ defmodule Task do
|
||||
|
||||
Supervisor.start_link([
|
||||
{Task.Supervisor, name: MyApp.TaskSupervisor}
|
||||
])
|
||||
], strategy: :one_for_one)
|
||||
|
||||
Now you can dynamically start supervised tasks:
|
||||
|
||||
@@ -144,21 +150,22 @@ defmodule Task do
|
||||
|
||||
Task.Supervisor.async(MyApp.TaskSupervisor, fn ->
|
||||
# Do something
|
||||
end) |> Task.await()
|
||||
end)
|
||||
|> Task.await()
|
||||
|
||||
Finally, check `Task.Supervisor` for other supported operations.
|
||||
|
||||
## Distributed tasks
|
||||
|
||||
Since Elixir provides a Task supervisor, it is easy to use one
|
||||
Since Elixir provides a `Task.Supervisor`, it is easy to use one
|
||||
to dynamically spawn tasks across nodes:
|
||||
|
||||
# On the remote node
|
||||
Task.Supervisor.start_link(name: MyApp.DistSupervisor)
|
||||
|
||||
# On the client
|
||||
Task.Supervisor.async({MyApp.DistSupervisor, :remote@local},
|
||||
MyMod, :my_fun, [arg1, arg2, arg3])
|
||||
supervisor = {MyApp.DistSupervisor, :remote@local}
|
||||
Task.Supervisor.async(supervisor, MyMod, :my_fun, [arg1, arg2, arg3])
|
||||
|
||||
Note that, when working with distributed tasks, one should use the `Task.Supervisor.async/4` function
|
||||
that expects explicit module, function and arguments, instead of `Task.Supervisor.async/2` that
|
||||
@@ -181,16 +188,34 @@ defmodule Task do
|
||||
* `:owner` - the PID of the process that started the task
|
||||
|
||||
"""
|
||||
@enforce_keys [:pid, :ref, :owner]
|
||||
defstruct pid: nil, ref: nil, owner: nil
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
@typedoc """
|
||||
The Task type.
|
||||
|
||||
See `%Task{}` for information about each field of the structure.
|
||||
"""
|
||||
@type t :: %__MODULE__{
|
||||
pid: pid() | nil,
|
||||
ref: reference() | nil,
|
||||
owner: pid() | nil
|
||||
}
|
||||
|
||||
defguardp is_timeout(timeout)
|
||||
when timeout == :infinity or (is_integer(timeout) and timeout >= 0)
|
||||
|
||||
@doc """
|
||||
Returns a specification to start a task under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
`arg` is passed as the argument to `Task.start_link/1` in the `:start` field
|
||||
of the spec.
|
||||
|
||||
For more information, see the `Supervisor` module,
|
||||
the `Supervisor.child_spec/2` function and the `t:Supervisor.child_spec/0` type.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
@spec child_spec(term) :: Supervisor.child_spec()
|
||||
def child_spec(arg) do
|
||||
%{
|
||||
id: Task,
|
||||
@@ -202,12 +227,18 @@ defmodule Task do
|
||||
@doc false
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
if Module.get_attribute(__MODULE__, :doc) == nil do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
`arg` is passed as the argument to `Task.start_link/1` in the `:start` field
|
||||
of the spec.
|
||||
|
||||
For more information, see the `Supervisor` module,
|
||||
the `Supervisor.child_spec/2` function and the `t:Supervisor.child_spec/0` type.
|
||||
"""
|
||||
end
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
@doc since: "1.5.0"
|
||||
def child_spec(arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
@@ -225,10 +256,12 @@ defmodule Task do
|
||||
@doc """
|
||||
Starts a process linked to the current process.
|
||||
|
||||
`fun` must be a zero-arity anonymous function.
|
||||
|
||||
This is often used to start the process as part of a supervision tree.
|
||||
"""
|
||||
@spec start_link((() -> any)) :: {:ok, pid}
|
||||
def start_link(fun) do
|
||||
def start_link(fun) when is_function(fun, 0) do
|
||||
start_link(:erlang, :apply, [fun, []])
|
||||
end
|
||||
|
||||
@@ -236,19 +269,23 @@ defmodule Task do
|
||||
Starts a task as part of a supervision tree.
|
||||
"""
|
||||
@spec start_link(module, atom, [term]) :: {:ok, pid}
|
||||
def start_link(mod, fun, args) do
|
||||
Task.Supervised.start_link(get_info(self()), {mod, fun, args})
|
||||
def start_link(module, function_name, args)
|
||||
when is_atom(module) and is_atom(function_name) and is_list(args) do
|
||||
mfa = {module, function_name, args}
|
||||
Task.Supervised.start_link(get_owner(self()), get_callers(self()), mfa)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts a task.
|
||||
|
||||
`fun` must be a zero-arity anonymous function.
|
||||
|
||||
This is only used when the task is used for side-effects
|
||||
(i.e. no interest in the returned result) and it should not
|
||||
be linked to the current process.
|
||||
"""
|
||||
@spec start((() -> any)) :: {:ok, pid}
|
||||
def start(fun) do
|
||||
def start(fun) when is_function(fun, 0) do
|
||||
start(:erlang, :apply, [fun, []])
|
||||
end
|
||||
|
||||
@@ -260,24 +297,27 @@ defmodule Task do
|
||||
be linked to the current process.
|
||||
"""
|
||||
@spec start(module, atom, [term]) :: {:ok, pid}
|
||||
def start(mod, fun, args) do
|
||||
Task.Supervised.start(get_info(self()), {mod, fun, args})
|
||||
def start(module, function_name, args)
|
||||
when is_atom(module) and is_atom(function_name) and is_list(args) do
|
||||
mfa = {module, function_name, args}
|
||||
Task.Supervised.start(get_owner(self()), get_callers(self()), mfa)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts a task that must be awaited on.
|
||||
|
||||
`fun` must be a zero-arity anonymous function.
|
||||
This function spawns a process that is linked to and monitored
|
||||
by the caller process. A `Task` struct is returned containing
|
||||
the relevant information.
|
||||
|
||||
Read the `Task` module documentation for more info on general
|
||||
usage of `async/1` and `async/3`.
|
||||
Read the `Task` module documentation for more information about the
|
||||
general usage of `async/1` and `async/3`.
|
||||
|
||||
See also `async/3`.
|
||||
"""
|
||||
@spec async((() -> any)) :: t
|
||||
def async(fun) do
|
||||
def async(fun) when is_function(fun, 0) do
|
||||
async(:erlang, :apply, [fun, []])
|
||||
end
|
||||
|
||||
@@ -288,8 +328,8 @@ defmodule Task do
|
||||
Developers must eventually call `Task.await/2` or `Task.yield/2`
|
||||
followed by `Task.shutdown/2` on the returned task.
|
||||
|
||||
Read the `Task` module documentation for more info on general
|
||||
usage of `async/1` and `async/3`.
|
||||
Read the `Task` module documentation for more information about
|
||||
the general usage of `async/1` and `async/3`.
|
||||
|
||||
## Linking
|
||||
|
||||
@@ -345,49 +385,52 @@ defmodule Task do
|
||||
and `result` is the return value of the task function.
|
||||
"""
|
||||
@spec async(module, atom, [term]) :: t
|
||||
def async(mod, fun, args) do
|
||||
mfa = {mod, fun, args}
|
||||
def async(module, function_name, args)
|
||||
when is_atom(module) and is_atom(function_name) and is_list(args) do
|
||||
mfa = {module, function_name, args}
|
||||
owner = self()
|
||||
pid = Task.Supervised.spawn_link(owner, get_info(owner), mfa)
|
||||
{:ok, pid} = Task.Supervised.start_link(get_owner(owner), get_callers(owner), :nomonitor, mfa)
|
||||
ref = Process.monitor(pid)
|
||||
send(pid, {owner, ref})
|
||||
%Task{pid: pid, ref: ref, owner: owner}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a stream that runs the given `module`, `function`, and `args`
|
||||
concurrently on each item in `enumerable`.
|
||||
Returns a stream where the given function (`module` and `function_name`)
|
||||
is mapped concurrently on each item in `enumerable`.
|
||||
|
||||
Each item will be prepended to the given `args` and processed by its
|
||||
own task. The tasks will be linked to an intermediate process that is
|
||||
then linked to the current process. This means a failure in a task
|
||||
terminates the current process and a failure in the current process
|
||||
Each item of `enumerable` will be prepended to the given `args` and
|
||||
processed by its own task. The tasks will be linked to an intermediate
|
||||
process that is then linked to the current process. This means a failure
|
||||
in a task terminates the current process and a failure in the current process
|
||||
terminates all tasks.
|
||||
|
||||
When streamed, each task will emit `{:ok, value}` upon successful
|
||||
completion or `{:exit, reason}` if the caller is trapping exits.
|
||||
Results are emitted in the same order as the original `enumerable`.
|
||||
The order of results depends on the value of the `:ordered` option.
|
||||
|
||||
The level of concurrency can be controlled via the `:max_concurrency`
|
||||
option and defaults to `System.schedulers_online/0`. A timeout
|
||||
can also be given as an option representing the maximum amount of
|
||||
time to wait without a task reply.
|
||||
The level of concurrency and the time tasks are allowed to run can
|
||||
be controlled via options (see the "Options" section below).
|
||||
|
||||
Finally, consider using `Task.Supervisor.async_stream/6` to start tasks
|
||||
Consider using `Task.Supervisor.async_stream/6` to start tasks
|
||||
under a supervisor. If you find yourself trapping exits to handle exits
|
||||
inside the async stream, consider using `Task.Supervisor.async_stream_nolink/6`
|
||||
to start tasks that are not linked to the current process.
|
||||
to start tasks that are not linked to the calling process.
|
||||
|
||||
## Options
|
||||
|
||||
* `:max_concurrency` - sets the maximum number of tasks to run
|
||||
at the same time. Defaults to `System.schedulers_online/0`.
|
||||
|
||||
* `:ordered` - whether the results should be returned in the same order
|
||||
as the input stream. This option is useful when you have large
|
||||
streams and don't want to buffer results before they are delivered.
|
||||
This is also useful when you're using the tasks for side effects.
|
||||
Defaults to `true`.
|
||||
|
||||
* `:timeout` - the maximum amount of time (in milliseconds) each
|
||||
task is allowed to execute for. Defaults to `5000`.
|
||||
|
||||
* `:on_timeout` - what to do when a task times out. The possible
|
||||
values are:
|
||||
* `:exit` (default) - the process that spawned the tasks exits.
|
||||
@@ -404,22 +447,32 @@ defmodule Task do
|
||||
The concurrency can be increased or decreased using the `:max_concurrency`
|
||||
option. For example, if the tasks are IO heavy, the value can be increased:
|
||||
|
||||
max_concurrency = System.schedulers_online * 2
|
||||
max_concurrency = System.schedulers_online() * 2
|
||||
stream = Task.async_stream(collection, Mod, :expensive_fun, [], max_concurrency: max_concurrency)
|
||||
Enum.to_list(stream)
|
||||
|
||||
If you do not care about the results of the computation, you can run
|
||||
the stream with `Stream.run/1`. Also set `ordered: false`, as you don't
|
||||
care about the order of the results either:
|
||||
|
||||
stream = Task.async_stream(collection, Mod, :expensive_fun, [], ordered: false)
|
||||
Stream.run(stream)
|
||||
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec async_stream(Enumerable.t(), module, atom, [term], keyword) :: Enumerable.t()
|
||||
def async_stream(enumerable, module, function, args, options \\ [])
|
||||
when is_atom(module) and is_atom(function) and is_list(args) do
|
||||
build_stream(enumerable, {module, function, args}, options)
|
||||
def async_stream(enumerable, module, function_name, args, options \\ [])
|
||||
when is_atom(module) and is_atom(function_name) and is_list(args) do
|
||||
build_stream(enumerable, {module, function_name, args}, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a stream that runs the given function `fun` concurrently
|
||||
on each item in `enumerable`.
|
||||
|
||||
Works the same as `async_stream/5` but with an anonymous function instead of a
|
||||
module-function-arguments tuple. `fun` must be a one-arity anonymous function.
|
||||
|
||||
Each `enumerable` item is passed as argument to the given function `fun` and
|
||||
processed by its own task. The tasks will be linked to the current process,
|
||||
similarly to `async/1`.
|
||||
@@ -437,27 +490,36 @@ defmodule Task do
|
||||
"""
|
||||
@doc since: "1.4.0"
|
||||
@spec async_stream(Enumerable.t(), (term -> term), keyword) :: Enumerable.t()
|
||||
def async_stream(enumerable, fun, options \\ []) when is_function(fun, 1) do
|
||||
def async_stream(enumerable, fun, options \\ [])
|
||||
when is_function(fun, 1) and is_list(options) do
|
||||
build_stream(enumerable, fun, options)
|
||||
end
|
||||
|
||||
defp build_stream(enumerable, fun, options) do
|
||||
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn owner, mfa ->
|
||||
{:link, Task.Supervised.spawn_link(owner, get_info(owner), mfa)}
|
||||
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn [owner | _] = callers, mfa ->
|
||||
{:ok, pid} = Task.Supervised.start_link(get_owner(owner), callers, :nomonitor, mfa)
|
||||
{:ok, :link, pid}
|
||||
end)
|
||||
end
|
||||
|
||||
# Returns a tuple with the node where this is executed and either the
|
||||
# registered name of the given pid or the pid of where this is executed. Used
|
||||
# registered name of the given PID or the PID of where this is executed. Used
|
||||
# when exiting from tasks to print out from where the task was started.
|
||||
defp get_info(pid) do
|
||||
defp get_owner(pid) do
|
||||
self_or_name =
|
||||
case Process.info(pid, :registered_name) do
|
||||
{:registered_name, name} when is_atom(name) -> name
|
||||
_ -> pid
|
||||
end
|
||||
|
||||
{node(), self_or_name}
|
||||
{node(), self_or_name, pid}
|
||||
end
|
||||
|
||||
defp get_callers(owner) do
|
||||
case :erlang.get(:"$callers") do
|
||||
[_ | _] = list -> [owner | list]
|
||||
_ -> [owner]
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -466,7 +528,7 @@ defmodule Task do
|
||||
In case the task process dies, the current process will exit with the same
|
||||
reason as the task.
|
||||
|
||||
A timeout, in milliseconds, can be given with default value of `5000`. If the
|
||||
A timeout in milliseconds or `:infinity`, can be given with a default value of `5000`. If the
|
||||
timeout is exceeded, then the current process will exit. If the task process
|
||||
is linked to the current process which is the case when a task is started with
|
||||
`async`, then the task process will also exit. If the task process is trapping
|
||||
@@ -485,7 +547,9 @@ defmodule Task do
|
||||
|
||||
It is not recommended to `await` a long-running task inside an OTP
|
||||
behaviour such as `GenServer`. Instead, you should match on the message
|
||||
coming from a task inside your `GenServer.handle_info/2` callback.
|
||||
coming from a task inside your `c:GenServer.handle_info/2` callback. For
|
||||
more information on the format of the message, see the documentation for
|
||||
`async/1`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -494,14 +558,12 @@ defmodule Task do
|
||||
2
|
||||
|
||||
"""
|
||||
@spec await(t, timeout) :: term | no_return
|
||||
def await(task, timeout \\ 5000)
|
||||
@spec await(t, timeout) :: term
|
||||
def await(%Task{ref: ref, owner: owner} = task, timeout \\ 5000) when is_timeout(timeout) do
|
||||
if owner != self() do
|
||||
raise ArgumentError, invalid_owner_error(task)
|
||||
end
|
||||
|
||||
def await(%Task{owner: owner} = task, _) when owner != self() do
|
||||
raise ArgumentError, invalid_owner_error(task)
|
||||
end
|
||||
|
||||
def await(%Task{ref: ref} = task, timeout) do
|
||||
receive do
|
||||
{^ref, reply} ->
|
||||
Process.demonitor(ref, [:flush])
|
||||
@@ -518,7 +580,7 @@ defmodule Task do
|
||||
|
||||
@doc false
|
||||
# TODO: Remove on 2.0
|
||||
@deprecated "Pattern match on the message directly instead"
|
||||
@deprecated "Pattern match directly on the message instead"
|
||||
def find(tasks, {ref, reply}) when is_reference(ref) do
|
||||
Enum.find_value(tasks, fn
|
||||
%Task{ref: ^ref} = task ->
|
||||
@@ -555,7 +617,7 @@ defmodule Task do
|
||||
* it isn't linked to the caller
|
||||
* the caller is trapping exits
|
||||
|
||||
A timeout, in milliseconds, can be given with default value
|
||||
A timeout, in milliseconds or `:infinity`, can be given with a default value
|
||||
of `5000`. If the time runs out before a message from
|
||||
the task is received, this function will return `nil`
|
||||
and the monitor will remain active. Therefore `yield/2` can be
|
||||
@@ -572,8 +634,9 @@ defmodule Task do
|
||||
case Task.yield(task, timeout) || Task.shutdown(task) do
|
||||
{:ok, result} ->
|
||||
result
|
||||
|
||||
nil ->
|
||||
Logger.warn "Failed to get a result in #{timeout}ms"
|
||||
Logger.warn("Failed to get a result in #{timeout}ms")
|
||||
nil
|
||||
end
|
||||
|
||||
@@ -582,13 +645,11 @@ defmodule Task do
|
||||
handle this case and return the result.
|
||||
"""
|
||||
@spec yield(t, timeout) :: {:ok, term} | {:exit, term} | nil
|
||||
def yield(task, timeout \\ 5000)
|
||||
def yield(%Task{ref: ref, owner: owner} = task, timeout \\ 5000) when is_timeout(timeout) do
|
||||
if owner != self() do
|
||||
raise ArgumentError, invalid_owner_error(task)
|
||||
end
|
||||
|
||||
def yield(%Task{owner: owner} = task, _) when owner != self() do
|
||||
raise ArgumentError, invalid_owner_error(task)
|
||||
end
|
||||
|
||||
def yield(%Task{ref: ref} = task, timeout) do
|
||||
receive do
|
||||
{^ref, reply} ->
|
||||
Process.demonitor(ref, [:flush])
|
||||
@@ -610,8 +671,10 @@ defmodule Task do
|
||||
|
||||
This function receives a list of tasks and waits for their
|
||||
replies in the given time interval. It returns a list
|
||||
of tuples of two elements, with the task as the first element
|
||||
and the yielded result as the second.
|
||||
of two-element tuples, with the task as the first element
|
||||
and the yielded result as the second. The tasks in the returned
|
||||
list will be in the same order as the tasks supplied in the `tasks`
|
||||
input argument.
|
||||
|
||||
Similarly to `yield/2`, each task's result will be
|
||||
|
||||
@@ -620,6 +683,9 @@ defmodule Task do
|
||||
* `{:exit, reason}` if the task has died
|
||||
* `nil` if the task keeps running past the timeout
|
||||
|
||||
A timeout, in milliseconds or `:infinity`, can be given with a default value
|
||||
of `5000`.
|
||||
|
||||
Check `yield/2` for more information.
|
||||
|
||||
## Example
|
||||
@@ -641,26 +707,27 @@ defmodule Task do
|
||||
|
||||
tasks_with_results = Task.yield_many(tasks, 5000)
|
||||
|
||||
results = Enum.map(tasks_with_results, fn {task, res} ->
|
||||
# Shutdown the tasks that did not reply nor exit
|
||||
res || Task.shutdown(task, :brutal_kill)
|
||||
end)
|
||||
results =
|
||||
Enum.map(tasks_with_results, fn {task, res} ->
|
||||
# Shut down the tasks that did not reply nor exit
|
||||
res || Task.shutdown(task, :brutal_kill)
|
||||
end)
|
||||
|
||||
# Here we are matching only on {:ok, value} and
|
||||
# ignoring {:exit, _} (crashed tasks) and `nil` (no replies)
|
||||
for {:ok, value} <- results do
|
||||
IO.inspect value
|
||||
IO.inspect(value)
|
||||
end
|
||||
|
||||
In the example above, we create tasks that sleep from 1
|
||||
up to 10 seconds and return the number of seconds they slept.
|
||||
up to 10 seconds and return the number of seconds they slept for.
|
||||
If you execute the code all at once, you should see 1 up to 5
|
||||
printed, as those were the tasks that have replied in the
|
||||
given time. All other tasks will have been shut down using
|
||||
the `Task.shutdown/2` call.
|
||||
"""
|
||||
@spec yield_many([t], timeout) :: [{t, {:ok, term} | {:exit, term} | nil}]
|
||||
def yield_many(tasks, timeout \\ 5000) do
|
||||
def yield_many(tasks, timeout \\ 5000) when is_timeout(timeout) do
|
||||
timeout_ref = make_ref()
|
||||
|
||||
timer_ref =
|
||||
@@ -714,7 +781,7 @@ defmodule Task do
|
||||
`{:exit, reason}` if the task died, otherwise `nil`.
|
||||
|
||||
The second argument is either a timeout or `:brutal_kill`. In case
|
||||
of a `timeout`, a `:shutdown` exit signal is sent to the task process
|
||||
of a timeout, a `:shutdown` exit signal is sent to the task process
|
||||
and if it does not exit within the timeout, it is killed. With `:brutal_kill`
|
||||
the task is killed straight away. In case the task terminates abnormally
|
||||
(possibly killed by another process), this function will exit with the same reason.
|
||||
@@ -723,10 +790,10 @@ defmodule Task do
|
||||
exiting with reason `:normal` or if the task is trapping exits. If the caller is
|
||||
exiting with a reason other than `:normal` and the task is not trapping exits, the
|
||||
caller's exit signal will stop the task. The caller can exit with reason
|
||||
`:shutdown` to shutdown all of its linked processes, including tasks, that
|
||||
`:shutdown` to shut down all of its linked processes, including tasks, that
|
||||
are not trapping exits without generating any log messages.
|
||||
|
||||
If a task's monitor has already been demonitored or received and there is not
|
||||
If a task's monitor has already been demonitored or received and there is not
|
||||
a response waiting in the message queue this function will return
|
||||
`{:exit, :noproc}` as the result or exit reason can not be determined.
|
||||
"""
|
||||
@@ -757,7 +824,7 @@ defmodule Task do
|
||||
end
|
||||
end
|
||||
|
||||
def shutdown(%Task{pid: pid} = task, timeout) do
|
||||
def shutdown(%Task{pid: pid} = task, timeout) when is_timeout(timeout) do
|
||||
mon = Process.monitor(pid)
|
||||
exit(pid, :shutdown)
|
||||
|
||||
|
||||
@@ -2,40 +2,37 @@ defmodule Task.Supervised do
|
||||
@moduledoc false
|
||||
@ref_timeout 5000
|
||||
|
||||
def start(info, fun) do
|
||||
{:ok, :proc_lib.spawn(__MODULE__, :noreply, [info, fun])}
|
||||
def start(owner, callers, fun) do
|
||||
{:ok, :proc_lib.spawn(__MODULE__, :noreply, [owner, callers, fun])}
|
||||
end
|
||||
|
||||
def start_link(info, fun) do
|
||||
{:ok, :proc_lib.spawn_link(__MODULE__, :noreply, [info, fun])}
|
||||
def start_link(owner, callers, fun) do
|
||||
{:ok, :proc_lib.spawn_link(__MODULE__, :noreply, [owner, callers, fun])}
|
||||
end
|
||||
|
||||
def start_link(caller, monitor, info, fun) do
|
||||
{:ok, spawn_link(caller, monitor, info, fun)}
|
||||
def start_link(owner, callers, monitor, fun) do
|
||||
{:ok, :proc_lib.spawn_link(__MODULE__, :reply, [owner, callers, monitor, fun])}
|
||||
end
|
||||
|
||||
def spawn_link(caller, monitor \\ :nomonitor, info, fun) do
|
||||
:proc_lib.spawn_link(__MODULE__, :reply, [caller, monitor, info, fun])
|
||||
end
|
||||
|
||||
def reply(caller, monitor, info, mfa) do
|
||||
def reply({_, _, owner_pid} = owner, callers, monitor, mfa) do
|
||||
initial_call(mfa)
|
||||
put_callers(callers)
|
||||
|
||||
case monitor do
|
||||
:monitor ->
|
||||
mref = Process.monitor(caller)
|
||||
reply(caller, mref, @ref_timeout, info, mfa)
|
||||
mref = Process.monitor(owner_pid)
|
||||
reply(owner, owner_pid, mref, @ref_timeout, mfa)
|
||||
|
||||
:nomonitor ->
|
||||
reply(caller, nil, :infinity, info, mfa)
|
||||
reply(owner, owner_pid, nil, :infinity, mfa)
|
||||
end
|
||||
end
|
||||
|
||||
defp reply(caller, mref, timeout, info, mfa) do
|
||||
defp reply(owner, owner_pid, mref, timeout, mfa) do
|
||||
receive do
|
||||
{^caller, ref} ->
|
||||
{^owner_pid, ref} ->
|
||||
_ = if mref, do: Process.demonitor(mref, [:flush])
|
||||
send(caller, {ref, do_apply(info, mfa)})
|
||||
send(owner_pid, {ref, invoke_mfa(owner, mfa)})
|
||||
|
||||
{:DOWN, ^mref, _, _, reason} when is_reference(mref) ->
|
||||
exit({:shutdown, reason})
|
||||
@@ -64,9 +61,14 @@ defmodule Task.Supervised do
|
||||
end
|
||||
end
|
||||
|
||||
def noreply(info, mfa) do
|
||||
def noreply(owner, callers, mfa) do
|
||||
initial_call(mfa)
|
||||
do_apply(info, mfa)
|
||||
put_callers(callers)
|
||||
invoke_mfa(owner, mfa)
|
||||
end
|
||||
|
||||
defp put_callers(callers) do
|
||||
Process.put(:"$callers", callers)
|
||||
end
|
||||
|
||||
defp initial_call(mfa) do
|
||||
@@ -83,44 +85,26 @@ defmodule Task.Supervised do
|
||||
{mod, fun, length(args)}
|
||||
end
|
||||
|
||||
# TODO: Remove conditionals once we depend on Erlang/OTP 20+
|
||||
defp do_apply(info, {module, fun, args} = mfa) do
|
||||
defp invoke_mfa(owner, {module, fun, args} = mfa) do
|
||||
try do
|
||||
apply(module, fun, args)
|
||||
catch
|
||||
:error, value ->
|
||||
reason = {value, __STACKTRACE__}
|
||||
log(info, mfa, reason)
|
||||
|
||||
if :erlang.system_info(:otp_release) >= '20' do
|
||||
:erlang.raise(:error, value, __STACKTRACE__)
|
||||
else
|
||||
exit(reason)
|
||||
end
|
||||
|
||||
:throw, value ->
|
||||
reason = {{:nocatch, value}, __STACKTRACE__}
|
||||
log(info, mfa, reason)
|
||||
|
||||
if :erlang.system_info(:otp_release) >= '20' do
|
||||
:erlang.raise(:throw, value, __STACKTRACE__)
|
||||
else
|
||||
exit(reason)
|
||||
end
|
||||
|
||||
:exit, value
|
||||
when value == :normal
|
||||
when value == :shutdown
|
||||
when tuple_size(value) == 2 and elem(value, 0) == :shutdown ->
|
||||
:erlang.raise(:exit, value, __STACKTRACE__)
|
||||
|
||||
:exit, value ->
|
||||
log(info, mfa, {value, __STACKTRACE__})
|
||||
:erlang.raise(:exit, value, __STACKTRACE__)
|
||||
kind, value ->
|
||||
log(owner, mfa, {log_value(kind, value), __STACKTRACE__})
|
||||
:erlang.raise(kind, value, __STACKTRACE__)
|
||||
end
|
||||
end
|
||||
|
||||
defp log(info, mfa, reason) do
|
||||
defp log_value(:throw, value), do: {:nocatch, value}
|
||||
defp log_value(_, value), do: value
|
||||
|
||||
defp log(owner, mfa, reason) do
|
||||
{fun, args} = get_running(mfa)
|
||||
|
||||
message =
|
||||
@@ -129,11 +113,12 @@ defmodule Task.Supervised do
|
||||
'** When function == ~p~n' ++
|
||||
'** arguments == ~p~n' ++ '** Reason for termination == ~n' ++ '** ~p~n'
|
||||
|
||||
:error_logger.format(message, [self(), get_from(info), fun, args, get_reason(reason)])
|
||||
:error_logger.format(message, [self(), get_from(owner), fun, args, get_reason(reason)])
|
||||
end
|
||||
|
||||
defp get_from({node, pid_or_name}) when node == node(), do: pid_or_name
|
||||
defp get_from(other), do: other
|
||||
defp get_from({node, pid_or_name, _pid}) when node == node(), do: pid_or_name
|
||||
defp get_from({node, name, _pid}) when is_atom(name), do: {node, name}
|
||||
defp get_from({_node, _name, pid}), do: pid
|
||||
|
||||
defp get_running({:erlang, :apply, [fun, []]}) when is_function(fun, 0), do: {fun, []}
|
||||
defp get_running({mod, fun, args}), do: {Function.capture(mod, fun, length(args)), args}
|
||||
@@ -168,6 +153,7 @@ defmodule Task.Supervised do
|
||||
timeout = Keyword.get(options, :timeout, 5000)
|
||||
on_timeout = Keyword.get(options, :on_timeout, :exit)
|
||||
parent = self()
|
||||
callers = get_callers()
|
||||
|
||||
{:trap_exit, trap_exit?} = Process.info(self(), :trap_exit)
|
||||
|
||||
@@ -177,7 +163,10 @@ defmodule Task.Supervised do
|
||||
spawn_opts = [:link, :monitor]
|
||||
|
||||
{monitor_pid, monitor_ref} =
|
||||
Process.spawn(fn -> stream_monitor(parent, mfa, spawn, trap_exit?, timeout) end, spawn_opts)
|
||||
Process.spawn(
|
||||
fn -> stream_monitor(callers, mfa, spawn, trap_exit?, timeout) end,
|
||||
spawn_opts
|
||||
)
|
||||
|
||||
# Now that we have the pid of the "monitor" process and the reference of the
|
||||
# monitor we use to monitor such process, we can inform the monitor process
|
||||
@@ -204,6 +193,13 @@ defmodule Task.Supervised do
|
||||
)
|
||||
end
|
||||
|
||||
defp get_callers do
|
||||
case :erlang.get(:"$callers") do
|
||||
[_ | _] = list -> [self() | list]
|
||||
_ -> [self()]
|
||||
end
|
||||
end
|
||||
|
||||
defp stream_reduce({:halt, acc}, _max, _spawned, _delivered, _waiting, next, config) do
|
||||
%{monitor_pid: monitor_pid, monitor_ref: monitor_ref, timeout: timeout} = config
|
||||
stream_close(monitor_pid, monitor_ref, timeout)
|
||||
@@ -429,15 +425,26 @@ defmodule Task.Supervised do
|
||||
send(pid, {self(), {monitor_ref, spawned}})
|
||||
Map.put(waiting, spawned, {pid, :running})
|
||||
|
||||
{:max_children, ^monitor_ref} ->
|
||||
stream_close(monitor_pid, monitor_ref, timeout)
|
||||
|
||||
raise """
|
||||
reached the maximum number of tasks for this task supervisor. The maximum number \
|
||||
of tasks that are allowed to run at the same time under this supervisor can be \
|
||||
configured with the :max_children option passed to Task.Supervisor.start_link/1. When \
|
||||
using async_stream or async_stream_nolink, make sure to configure :max_concurrency to \
|
||||
be lower or equal to :max_children and pay attention to whether other tasks are also \
|
||||
spawned under the same task supervisor.\
|
||||
"""
|
||||
|
||||
{:DOWN, ^monitor_ref, _, ^monitor_pid, reason} ->
|
||||
stream_cleanup_inbox(monitor_pid, monitor_ref)
|
||||
exit({reason, {__MODULE__, :stream, [timeout]}})
|
||||
end
|
||||
end
|
||||
|
||||
defp stream_monitor(parent_pid, mfa, spawn, trap_exit?, timeout) do
|
||||
defp stream_monitor([parent_pid | _] = callers, mfa, spawn, trap_exit?, timeout) do
|
||||
Process.flag(:trap_exit, trap_exit?)
|
||||
|
||||
parent_ref = Process.monitor(parent_pid)
|
||||
|
||||
# Let's wait for the parent process to tell this process the monitor ref
|
||||
@@ -446,7 +453,7 @@ defmodule Task.Supervised do
|
||||
receive do
|
||||
{^parent_pid, monitor_ref} ->
|
||||
config = %{
|
||||
parent_pid: parent_pid,
|
||||
callers: callers,
|
||||
parent_ref: parent_ref,
|
||||
mfa: mfa,
|
||||
spawn: spawn,
|
||||
@@ -463,8 +470,7 @@ defmodule Task.Supervised do
|
||||
|
||||
defp stream_monitor_loop(running_tasks, config) do
|
||||
%{
|
||||
parent_pid: parent_pid,
|
||||
parent_ref: parent_ref,
|
||||
callers: [parent_pid | _] = callers,
|
||||
mfa: mfa,
|
||||
spawn: spawn,
|
||||
monitor_ref: monitor_ref,
|
||||
@@ -475,55 +481,35 @@ defmodule Task.Supervised do
|
||||
# The parent process is telling us to spawn a new task to process
|
||||
# "value". We spawn it and notify the parent about its pid.
|
||||
{:spawn, position, value} ->
|
||||
{type, pid} = spawn.(parent_pid, normalize_mfa_with_arg(mfa, value))
|
||||
ref = Process.monitor(pid)
|
||||
case spawn.(callers, normalize_mfa_with_arg(mfa, value)) do
|
||||
{:ok, type, pid} ->
|
||||
ref = Process.monitor(pid)
|
||||
|
||||
# Schedule a timeout message to ourselves, unless the timeout was set to :infinity
|
||||
timer_ref =
|
||||
case timeout do
|
||||
:infinity -> nil
|
||||
timeout -> Process.send_after(self(), {:timeout, {monitor_ref, ref}}, timeout)
|
||||
end
|
||||
# Schedule a timeout message to ourselves, unless the timeout was set to :infinity
|
||||
timer_ref =
|
||||
case timeout do
|
||||
:infinity -> nil
|
||||
timeout -> Process.send_after(self(), {:timeout, {monitor_ref, ref}}, timeout)
|
||||
end
|
||||
|
||||
send(parent_pid, {:spawned, {monitor_ref, position}, pid})
|
||||
send(parent_pid, {:spawned, {monitor_ref, position}, pid})
|
||||
|
||||
task_info = %{
|
||||
position: position,
|
||||
type: type,
|
||||
pid: pid,
|
||||
timer_ref: timer_ref,
|
||||
timed_out?: false
|
||||
}
|
||||
running_tasks =
|
||||
Map.put(running_tasks, ref, %{
|
||||
position: position,
|
||||
type: type,
|
||||
pid: pid,
|
||||
timer_ref: timer_ref,
|
||||
timed_out?: false
|
||||
})
|
||||
|
||||
running_tasks = Map.put(running_tasks, ref, task_info)
|
||||
stream_monitor_loop(running_tasks, config)
|
||||
stream_monitor_loop(running_tasks, config)
|
||||
|
||||
# The parent process is telling us to stop because the stream is being
|
||||
# closed. In this case, we forcibly kill all spawned processes and then
|
||||
# exit gracefully ourselves.
|
||||
{:stop, ^monitor_ref} ->
|
||||
Process.flag(:trap_exit, true)
|
||||
|
||||
for {ref, %{pid: pid}} <- running_tasks do
|
||||
Process.exit(pid, :kill)
|
||||
|
||||
receive do
|
||||
{:DOWN, ^ref, _, _, _} -> :ok
|
||||
end
|
||||
{:error, :max_children} ->
|
||||
send(parent_pid, {:max_children, monitor_ref})
|
||||
stream_waiting_for_stop_loop(running_tasks, config)
|
||||
end
|
||||
|
||||
exit(:normal)
|
||||
|
||||
# The parent process went down with a given reason. We kill all the
|
||||
# spawned processes (that are also linked) with the same reason, and then
|
||||
# exit ourselves with the same reason.
|
||||
{:DOWN, ^parent_ref, _, _, reason} ->
|
||||
for {_ref, %{type: :link, pid: pid}} <- running_tasks do
|
||||
Process.exit(pid, reason)
|
||||
end
|
||||
|
||||
exit(reason)
|
||||
|
||||
# One of the spawned processes went down. We inform the parent process of
|
||||
# this and keep going.
|
||||
{:DOWN, ref, _, _, reason} ->
|
||||
@@ -557,9 +543,62 @@ defmodule Task.Supervised do
|
||||
|
||||
{:EXIT, _, _} ->
|
||||
stream_monitor_loop(running_tasks, config)
|
||||
|
||||
other ->
|
||||
handle_stop_or_parent_down(other, running_tasks, config)
|
||||
stream_monitor_loop(running_tasks, config)
|
||||
end
|
||||
end
|
||||
|
||||
defp stream_waiting_for_stop_loop(running_tasks, config) do
|
||||
receive do
|
||||
message ->
|
||||
handle_stop_or_parent_down(message, running_tasks, config)
|
||||
stream_waiting_for_stop_loop(running_tasks, config)
|
||||
end
|
||||
end
|
||||
|
||||
# The parent process is telling us to stop because the stream is being
|
||||
# closed. In this case, we forcibly kill all spawned processes and then
|
||||
# exit gracefully ourselves.
|
||||
defp handle_stop_or_parent_down(
|
||||
{:stop, monitor_ref},
|
||||
running_tasks,
|
||||
%{monitor_ref: monitor_ref}
|
||||
) do
|
||||
Process.flag(:trap_exit, true)
|
||||
|
||||
for {_ref, %{pid: pid}} <- running_tasks, do: Process.exit(pid, :kill)
|
||||
|
||||
for {ref, _task} <- running_tasks do
|
||||
receive do
|
||||
{:DOWN, ^ref, _, _, _} -> :ok
|
||||
end
|
||||
end
|
||||
|
||||
exit(:normal)
|
||||
end
|
||||
|
||||
# The parent process went down with a given reason. We kill all the
|
||||
# spawned processes (that are also linked) with the same reason, and then
|
||||
# exit ourselves with the same reason.
|
||||
defp handle_stop_or_parent_down(
|
||||
{:DOWN, parent_ref, _, _, reason},
|
||||
running_tasks,
|
||||
%{parent_ref: parent_ref}
|
||||
) do
|
||||
for {_ref, %{type: :link, pid: pid}} <- running_tasks do
|
||||
Process.exit(pid, reason)
|
||||
end
|
||||
|
||||
exit(reason)
|
||||
end
|
||||
|
||||
# We ignore all other messages.
|
||||
defp handle_stop_or_parent_down(_other, _running_tasks, _config) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp unlink_and_kill(pid) do
|
||||
caller = self()
|
||||
ref = make_ref()
|
||||
|
||||
@@ -78,7 +78,7 @@ defmodule Task.Supervisor do
|
||||
give them directly to `start_child` and `async`.
|
||||
"""
|
||||
@spec start_link([option]) :: Supervisor.on_start()
|
||||
# TODO: Deprecate passing restart and shutdown here on Elixir v1.8.
|
||||
# TODO: Deprecate passing restart and shutdown here on Elixir v1.9.
|
||||
def start_link(options \\ []) do
|
||||
{restart, options} = Keyword.pop(options, :restart, :temporary)
|
||||
{shutdown, options} = Keyword.pop(options, :shutdown, 5000)
|
||||
@@ -97,10 +97,13 @@ defmodule Task.Supervisor do
|
||||
@doc """
|
||||
Starts a task that can be awaited on.
|
||||
|
||||
The `supervisor` must be a reference as defined in `Task.Supervisor`.
|
||||
The `supervisor` must be a reference as defined in `Supervisor`.
|
||||
The task will still be linked to the caller, see `Task.async/3` for
|
||||
more information and `async_nolink/2` for a non-linked variant.
|
||||
|
||||
Raises an error if `supervisor` has reached the maximum number of
|
||||
children.
|
||||
|
||||
## Options
|
||||
|
||||
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
|
||||
@@ -115,10 +118,13 @@ defmodule Task.Supervisor do
|
||||
@doc """
|
||||
Starts a task that can be awaited on.
|
||||
|
||||
The `supervisor` must be a reference as defined in `Task.Supervisor`.
|
||||
The `supervisor` must be a reference as defined in `Supervisor`.
|
||||
The task will still be linked to the caller, see `Task.async/3` for
|
||||
more information and `async_nolink/2` for a non-linked variant.
|
||||
|
||||
Raises an error if `supervisor` has reached the maximum number of
|
||||
children.
|
||||
|
||||
## Options
|
||||
|
||||
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
|
||||
@@ -133,10 +139,13 @@ defmodule Task.Supervisor do
|
||||
@doc """
|
||||
Starts a task that can be awaited on.
|
||||
|
||||
The `supervisor` must be a reference as defined in `Task.Supervisor`.
|
||||
The `supervisor` must be a reference as defined in `Supervisor`.
|
||||
The task won't be linked to the caller, see `Task.async/3` for
|
||||
more information.
|
||||
|
||||
Raises an error if `supervisor` has reached the maximum number of
|
||||
children.
|
||||
|
||||
## Options
|
||||
|
||||
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
|
||||
@@ -156,6 +165,53 @@ defmodule Task.Supervisor do
|
||||
terminates, the caller's process will always receive a `:DOWN` message
|
||||
with the same `ref` value that is held by the task struct. If the task
|
||||
terminates normally, the reason in the `:DOWN` message will be `:normal`.
|
||||
|
||||
## Examples
|
||||
|
||||
Typically, you use `async_nolink/3` when there is a reasonable expectation that
|
||||
the task may fail, and you don't want it to take down the caller. Let's see an
|
||||
example where a `GenServer` is meant to run a single task and track its status:
|
||||
|
||||
defmodule MyApp.Server do
|
||||
use GenServer
|
||||
|
||||
# ...
|
||||
|
||||
def start_task do
|
||||
GenServer.call(__MODULE__, :start_task)
|
||||
end
|
||||
|
||||
# In this case the task is already running, so we just return :ok.
|
||||
def handle_call(:start_task, %{ref: ref} = state) when is_reference(ref) do
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
# The task is not running yet, so let's start it.
|
||||
def handle_cast(:start_task, %{ref: nil} = state) do
|
||||
task =
|
||||
Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn ->
|
||||
...
|
||||
end)
|
||||
|
||||
# We return :ok and the server will continue running
|
||||
{:reply, :ok, %{state | ref: task.ref}}
|
||||
end
|
||||
|
||||
# The task completed successfully
|
||||
def handle_info({ref, answer}, %{ref: ref} = state) do
|
||||
# We don't care about the DOWN message now, so let's demonitor and flush it
|
||||
Process.demonitor(ref, [:flush])
|
||||
# Do something with the result and then return
|
||||
{:noreply, %{state | ref: nil}}
|
||||
end
|
||||
|
||||
# The task failed
|
||||
def handle_info({:DOWN, ref, :process, _pid, _reason}, %{ref: ref} = state) do
|
||||
# Log and possibly restart the task...
|
||||
{:noreply, %{state | ref: nil}}
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
@spec async_nolink(Supervisor.supervisor(), (() -> any), Keyword.t()) :: Task.t()
|
||||
def async_nolink(supervisor, fun, options \\ []) do
|
||||
@@ -165,10 +221,13 @@ defmodule Task.Supervisor do
|
||||
@doc """
|
||||
Starts a task that can be awaited on.
|
||||
|
||||
The `supervisor` must be a reference as defined in `Task.Supervisor`.
|
||||
The `supervisor` must be a reference as defined in `Supervisor`.
|
||||
The task won't be linked to the caller, see `Task.async/3` for
|
||||
more information.
|
||||
|
||||
Raises an error if `supervisor` has reached the maximum number of
|
||||
children.
|
||||
|
||||
Note this function requires the task supervisor to have `:temporary`
|
||||
as the `:restart` option (the default), as `async_nolink/4` keeps a
|
||||
direct reference to the task which is lost if the task is restarted.
|
||||
@@ -179,8 +238,8 @@ defmodule Task.Supervisor do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a stream that runs the given `module`, `function`, and `args`
|
||||
concurrently on each item in `enumerable`.
|
||||
Returns a stream where the given function (`module` and `function`)
|
||||
is mapped concurrently on each item in `enumerable`.
|
||||
|
||||
Each item will be prepended to the given `args` and processed by its
|
||||
own task. The tasks will be spawned under the given `supervisor` and
|
||||
@@ -188,35 +247,38 @@ defmodule Task.Supervisor do
|
||||
|
||||
When streamed, each task will emit `{:ok, value}` upon successful
|
||||
completion or `{:exit, reason}` if the caller is trapping exits.
|
||||
Results are emitted in the same order as the original `enumerable`.
|
||||
The order of results depends on the value of the `:ordered` option.
|
||||
|
||||
The level of concurrency can be controlled via the `:max_concurrency`
|
||||
option and defaults to `System.schedulers_online/0`. A timeout
|
||||
can also be given as an option representing the maximum amount of
|
||||
time to wait without a task reply.
|
||||
The level of concurrency and the time tasks are allowed to run can
|
||||
be controlled via options (see the "Options" section below).
|
||||
|
||||
Finally, if you find yourself trapping exits to handle exits inside
|
||||
If you find yourself trapping exits to handle exits inside
|
||||
the async stream, consider using `async_stream_nolink/6` to start tasks
|
||||
that are not linked to the current process.
|
||||
that are not linked to the calling process.
|
||||
|
||||
## Options
|
||||
|
||||
* `:max_concurrency` - sets the maximum number of tasks to run
|
||||
at the same time. Defaults to `System.schedulers_online/0`.
|
||||
|
||||
* `:ordered` - whether the results should be returned in the same order
|
||||
as the input stream. This option is useful when you have large
|
||||
streams and don't want to buffer results before they are delivered.
|
||||
This is also useful when you're using the tasks for side effects.
|
||||
Defaults to `true`.
|
||||
|
||||
* `:timeout` - the maximum amount of time to wait (in milliseconds)
|
||||
without receiving a task reply (across all running tasks).
|
||||
Defaults to `5000`.
|
||||
|
||||
* `:on_timeout` - what do to when a task times out. The possible
|
||||
values are:
|
||||
* `:exit` (default) - the process that spawned the tasks exits.
|
||||
* `:kill_task` - the task that timed out is killed. The value
|
||||
emitted for that task is `{:exit, :timeout}`.
|
||||
|
||||
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
|
||||
or an integer indicating the timeout value, defaults to 5000 milliseconds.
|
||||
or an integer indicating the timeout value. Defaults to `5000` milliseconds.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -252,8 +314,8 @@ defmodule Task.Supervisor do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a stream that runs the given `module`, `function`, and `args`
|
||||
concurrently on each item in `enumerable`.
|
||||
Returns a stream where the given function (`module` and `function`)
|
||||
is mapped concurrently on each item in `enumerable`.
|
||||
|
||||
Each item in `enumerable` will be prepended to the given `args` and processed
|
||||
by its own task. The tasks will be spawned under the given `supervisor` and
|
||||
@@ -333,7 +395,7 @@ defmodule Task.Supervisor do
|
||||
def start_child(supervisor, fun, options \\ []) do
|
||||
restart = options[:restart]
|
||||
shutdown = options[:shutdown]
|
||||
args = [get_info(self()), {:erlang, :apply, [fun, []]}]
|
||||
args = [get_owner(self()), get_callers(self()), {:erlang, :apply, [fun, []]}]
|
||||
start_child_with_spec(supervisor, args, restart, shutdown)
|
||||
end
|
||||
|
||||
@@ -349,7 +411,7 @@ defmodule Task.Supervisor do
|
||||
when is_atom(fun) and is_list(args) do
|
||||
restart = options[:restart]
|
||||
shutdown = options[:shutdown]
|
||||
args = [get_info(self()), {module, fun, args}]
|
||||
args = [get_owner(self()), get_callers(self()), {module, fun, args}]
|
||||
start_child_with_spec(supervisor, args, restart, shutdown)
|
||||
end
|
||||
|
||||
@@ -360,35 +422,58 @@ defmodule Task.Supervisor do
|
||||
GenServer.call(supervisor, {:start_task, args, restart, shutdown}, :infinity)
|
||||
end
|
||||
|
||||
defp get_info(self) do
|
||||
name =
|
||||
case Process.info(self, :registered_name) do
|
||||
defp get_owner(pid) do
|
||||
self_or_name =
|
||||
case Process.info(pid, :registered_name) do
|
||||
{:registered_name, name} when is_atom(name) -> name
|
||||
_ -> self
|
||||
_ -> pid
|
||||
end
|
||||
|
||||
{node(), name}
|
||||
{node(), self_or_name, pid}
|
||||
end
|
||||
|
||||
defp get_callers(owner) do
|
||||
case :erlang.get(:"$callers") do
|
||||
[_ | _] = list -> [owner | list]
|
||||
_ -> [owner]
|
||||
end
|
||||
end
|
||||
|
||||
defp async(supervisor, link_type, module, fun, args, options) do
|
||||
owner = self()
|
||||
args = [owner, :monitor, get_info(owner), {module, fun, args}]
|
||||
args = [get_owner(owner), get_callers(owner), :monitor, {module, fun, args}]
|
||||
shutdown = options[:shutdown]
|
||||
{:ok, pid} = start_child_with_spec(supervisor, args, :temporary, shutdown)
|
||||
if link_type == :link, do: Process.link(pid)
|
||||
ref = Process.monitor(pid)
|
||||
send(pid, {owner, ref})
|
||||
%Task{pid: pid, ref: ref, owner: owner}
|
||||
|
||||
case start_child_with_spec(supervisor, args, :temporary, shutdown) do
|
||||
{:ok, pid} ->
|
||||
if link_type == :link, do: Process.link(pid)
|
||||
ref = Process.monitor(pid)
|
||||
send(pid, {owner, ref})
|
||||
%Task{pid: pid, ref: ref, owner: owner}
|
||||
|
||||
{:error, :max_children} ->
|
||||
raise """
|
||||
reached the maximum number of tasks for this task supervisor. The maximum number \
|
||||
of tasks that are allowed to run at the same time under this supervisor can be \
|
||||
configured with the :max_children option passed to Task.Supervisor.start_link/1\
|
||||
"""
|
||||
end
|
||||
end
|
||||
|
||||
defp build_stream(supervisor, link_type, enumerable, fun, options) do
|
||||
shutdown = options[:shutdown]
|
||||
|
||||
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn owner, mfa ->
|
||||
args = [owner, :monitor, get_info(owner), mfa]
|
||||
{:ok, pid} = start_child_with_spec(supervisor, args, :temporary, shutdown)
|
||||
if link_type == :link, do: Process.link(pid)
|
||||
{link_type, pid}
|
||||
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn [owner | _] = callers, mfa ->
|
||||
args = [get_owner(owner), callers, :monitor, mfa]
|
||||
|
||||
case start_child_with_spec(supervisor, args, :temporary, shutdown) do
|
||||
{:ok, pid} ->
|
||||
if link_type == :link, do: Process.link(pid)
|
||||
{:ok, link_type, pid}
|
||||
|
||||
{:error, :max_children} ->
|
||||
{:error, :max_children}
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,8 +6,8 @@ defmodule Tuple do
|
||||
|
||||
* `elem/2` - access a tuple by index
|
||||
* `put_elem/3` - insert a value into a tuple by index
|
||||
* `tuple_size/3` - get the number of elements in a tuple
|
||||
|
||||
* `tuple_size/1` - get the number of elements in a tuple
|
||||
|
||||
Tuples are intended as fixed-size containers for multiple elements.
|
||||
To manipulate a collection of elements, use a list instead. `Enum`
|
||||
functions do not work on tuples.
|
||||
@@ -20,23 +20,23 @@ defmodule Tuple do
|
||||
{1, :two, "three"}
|
||||
|
||||
A tuple may contain elements of different types, which are stored
|
||||
contiguously in memory. Accessing any element takes constant time,
|
||||
but modifying a tuple, which produces a shallow copy, takes linear time.
|
||||
contiguously in memory. Accessing any element takes constant time,
|
||||
but modifying a tuple, which produces a shallow copy, takes linear time.
|
||||
Tuples are good for reading data while lists are better for traversals.
|
||||
|
||||
Tuples are typically used either when a function has multiple return values
|
||||
or for error handling. `File.read/1` returns `{:ok, contents}` if reading
|
||||
the given file is successful, or else `{:error, reason}` such as when
|
||||
or for error handling. `File.read/1` returns `{:ok, contents}` if reading
|
||||
the given file is successful, or else `{:error, reason}` such as when
|
||||
the file does not exist.
|
||||
|
||||
The functions in this module that add and remove elements from tuples are
|
||||
rarely used in practice, as they typically imply tuples are being used as
|
||||
collections. To append to a tuple, it is preferrable to use pattern matching:
|
||||
collections. To append to a tuple, it is preferable to use pattern matching:
|
||||
|
||||
tuple = {:ok, :example}
|
||||
|
||||
# Avoid
|
||||
Tuple.insert_at(tuple, 2, %{}}
|
||||
Tuple.insert_at(tuple, 2, %{})
|
||||
|
||||
# Prefer
|
||||
{:ok, atom} = tuple
|
||||
|
||||
+53
-20
@@ -47,7 +47,7 @@ defmodule URI do
|
||||
"""
|
||||
@spec default_port(binary) :: nil | non_neg_integer
|
||||
def default_port(scheme) when is_binary(scheme) do
|
||||
:elixir_config.safe_get({:uri, scheme}, nil)
|
||||
:elixir_config.get({:uri, scheme}, nil)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -322,8 +322,8 @@ defmodule URI do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> URI.decode("http%3A%2F%2Felixir-lang.org")
|
||||
"http://elixir-lang.org"
|
||||
iex> URI.decode("https%3A%2F%2Felixir-lang.org")
|
||||
"https://elixir-lang.org"
|
||||
|
||||
"""
|
||||
@spec decode(binary) :: binary
|
||||
@@ -390,22 +390,53 @@ defmodule URI do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> URI.parse("http://elixir-lang.org/")
|
||||
%URI{scheme: "http", path: "/", query: nil, fragment: nil,
|
||||
authority: "elixir-lang.org", userinfo: nil,
|
||||
host: "elixir-lang.org", port: 80}
|
||||
iex> URI.parse("https://elixir-lang.org/")
|
||||
%URI{
|
||||
authority: "elixir-lang.org",
|
||||
fragment: nil,
|
||||
host: "elixir-lang.org",
|
||||
path: "/",
|
||||
port: 443,
|
||||
query: nil,
|
||||
scheme: "https",
|
||||
userinfo: nil
|
||||
}
|
||||
|
||||
iex> URI.parse("//elixir-lang.org/")
|
||||
%URI{authority: "elixir-lang.org", fragment: nil, host: "elixir-lang.org",
|
||||
path: "/", port: nil, query: nil, scheme: nil, userinfo: nil}
|
||||
%URI{
|
||||
authority: "elixir-lang.org",
|
||||
fragment: nil,
|
||||
host: "elixir-lang.org",
|
||||
path: "/",
|
||||
port: nil,
|
||||
query: nil,
|
||||
scheme: nil,
|
||||
userinfo: nil
|
||||
}
|
||||
|
||||
iex> URI.parse("/foo/bar")
|
||||
%URI{authority: nil, fragment: nil, host: nil, path: "/foo/bar",
|
||||
port: nil, query: nil, scheme: nil, userinfo: nil}
|
||||
%URI{
|
||||
authority: nil,
|
||||
fragment: nil,
|
||||
host: nil,
|
||||
path: "/foo/bar",
|
||||
port: nil,
|
||||
query: nil,
|
||||
scheme: nil,
|
||||
userinfo: nil
|
||||
}
|
||||
|
||||
iex> URI.parse("foo/bar")
|
||||
%URI{authority: nil, fragment: nil, host: nil, path: "foo/bar",
|
||||
port: nil, query: nil, scheme: nil, userinfo: nil}
|
||||
%URI{
|
||||
authority: nil,
|
||||
fragment: nil,
|
||||
host: nil,
|
||||
path: "foo/bar",
|
||||
port: nil,
|
||||
query: nil,
|
||||
scheme: nil,
|
||||
userinfo: nil
|
||||
}
|
||||
|
||||
"""
|
||||
@spec parse(t | binary) :: t
|
||||
@@ -416,9 +447,7 @@ defmodule URI do
|
||||
def parse(string) when is_binary(string) do
|
||||
# From https://tools.ietf.org/html/rfc3986#appendix-B
|
||||
regex =
|
||||
Regex.recompile!(
|
||||
~r/^(([a-z][a-z0-9\+\-\.]*):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/i
|
||||
)
|
||||
Regex.recompile!(~r{^(([a-z][a-z0-9\+\-\.]*):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?}i)
|
||||
|
||||
parts = Regex.run(regex, string)
|
||||
|
||||
@@ -488,8 +517,12 @@ defmodule URI do
|
||||
iex> URI.to_string(%URI{userinfo: "bar", host: "example.org", port: 81})
|
||||
"//bar@example.org:81"
|
||||
|
||||
iex> URI.to_string(%URI{authority: "foo@example.com:80",
|
||||
...> userinfo: "bar", host: "example.org", port: 81})
|
||||
iex> URI.to_string(%URI{
|
||||
...> authority: "foo@example.com:80",
|
||||
...> userinfo: "bar",
|
||||
...> host: "example.org",
|
||||
...> port: 81
|
||||
...> })
|
||||
"//bar@example.org:81"
|
||||
|
||||
"""
|
||||
@@ -504,10 +537,10 @@ defmodule URI do
|
||||
|
||||
## Examples
|
||||
|
||||
iex> URI.merge(URI.parse("http://google.com"), "/query") |> to_string
|
||||
iex> URI.merge(URI.parse("http://google.com"), "/query") |> to_string()
|
||||
"http://google.com/query"
|
||||
|
||||
iex> URI.merge("http://example.com", "http://google.com") |> to_string
|
||||
iex> URI.merge("http://example.com", "http://google.com") |> to_string()
|
||||
"http://google.com"
|
||||
|
||||
"""
|
||||
|
||||
+74
-40
@@ -14,13 +14,17 @@ defmodule Version do
|
||||
|
||||
MAJOR.MINOR.PATCH
|
||||
|
||||
Pre-releases are supported by appending `-[0-9A-Za-z-\.]`:
|
||||
Pre-releases are supported by optionally appending a hyphen and a series of
|
||||
period-separated identifiers immediately following the patch version.
|
||||
Identifiers consist of only ASCII alphanumeric characters and hyphens (`[0-9A-Za-z-]`):
|
||||
|
||||
"1.0.0-alpha.3"
|
||||
|
||||
Build information can be added by appending `+[0-9A-Za-z-\.]`:
|
||||
Build information can be added by appending a plus sign and a series of
|
||||
dot-separated identifiers immediately following the patch or pre-release version.
|
||||
Identifiers consist of only ASCII alphanumeric characters and hyphens (`[0-9A-Za-z-]`):
|
||||
|
||||
"1.0.0-alpha.3+20130417140000"
|
||||
"1.0.0-alpha.3+20130417140000.amd64"
|
||||
|
||||
## Struct
|
||||
|
||||
@@ -31,9 +35,9 @@ defmodule Version do
|
||||
## Requirements
|
||||
|
||||
Requirements allow you to specify which versions of a given
|
||||
dependency you are willing to work against. Requirements support common
|
||||
operators like `>=`, `<=`, `>`, `==`, and friends that
|
||||
work as one would expect:
|
||||
dependency you are willing to work against. Requirements support the common
|
||||
comparison operators such as `>`, `>=`, `<`, `<=`, `==`, `!=` that work as one would expect,
|
||||
and additionally the special operator `~>` described in detail further below.
|
||||
|
||||
# Only version 2.0.0
|
||||
"== 2.0.0"
|
||||
@@ -51,10 +55,11 @@ defmodule Version do
|
||||
|
||||
"~> 2.0.0"
|
||||
|
||||
`~>` will never include pre-release versions of its upper bound.
|
||||
It can also be used to set an upper bound on only the major
|
||||
`~>` will never include pre-release versions of its upper bound,
|
||||
regardless of the usage of the `:allow_pre` option, or whether the operand
|
||||
is a pre-release version. It can also be used to set an upper bound on only the major
|
||||
version part. See the table below for `~>` requirements and
|
||||
their corresponding translation.
|
||||
their corresponding translations.
|
||||
|
||||
`~>` | Translation
|
||||
:------------- | :---------------------
|
||||
@@ -64,23 +69,28 @@ defmodule Version do
|
||||
`~> 2.0` | `>= 2.0.0 and < 3.0.0`
|
||||
`~> 2.1` | `>= 2.1.0 and < 3.0.0`
|
||||
|
||||
When `allow_pre: false` is set, the requirement will not match a
|
||||
pre-release version unless the operand is a pre-release version.
|
||||
The requirement operand after the `~>` is allowed to omit the patch version,
|
||||
allowing us to express `~> 2.1` or `~> 2.1-dev`, something that wouldn't be allowed
|
||||
when using the common comparison operators.
|
||||
|
||||
When the `:allow_pre` option is set `false` in `Version.match?/3`, the requirement
|
||||
will not match a pre-release version unless the operand is a pre-release version.
|
||||
The default is to always allow pre-releases but note that in
|
||||
Hex `:allow_pre` is set to `false`. See the table below for examples.
|
||||
|
||||
Requirement | Version | `:allow_pre` | Matches
|
||||
:------------- | :---------- | :----------- | :------
|
||||
`~> 2.0` | `2.1.0` | - | `true`
|
||||
`~> 2.0` | `3.0.0` | - | `false`
|
||||
`~> 2.0.0` | `2.0.1` | - | `true`
|
||||
`~> 2.0.0` | `2.1.0` | - | `false`
|
||||
`~> 2.1.2` | `2.1.3-dev` | `true` | `true`
|
||||
`~> 2.1.2` | `2.1.3-dev` | `false` | `false`
|
||||
`~> 2.1-dev` | `2.2.0-dev` | `false` | `true`
|
||||
`~> 2.1.2-dev` | `2.1.3-dev` | `false` | `true`
|
||||
`>= 2.1.0` | `2.2.0-dev` | `false` | `false`
|
||||
`>= 2.1.0-dev` | `2.2.3-dev` | `true` | `true`
|
||||
Requirement | Version | `:allow_pre` | Matches
|
||||
:------------- | :---------- | :---------------- | :------
|
||||
`~> 2.0` | `2.1.0` | `true` or `false` | `true`
|
||||
`~> 2.0` | `3.0.0` | `true` or `false` | `false`
|
||||
`~> 2.0.0` | `2.0.5` | `true` or `false` | `true`
|
||||
`~> 2.0.0` | `2.1.0` | `true` or `false` | `false`
|
||||
`~> 2.1.2` | `2.1.6-dev` | `true` | `true`
|
||||
`~> 2.1.2` | `2.1.6-dev` | `false` | `false`
|
||||
`~> 2.1-dev` | `2.2.0-dev` | `true` or `false` | `true`
|
||||
`~> 2.1.2-dev` | `2.1.6-dev` | `true` or `false` | `true`
|
||||
`>= 2.1.0` | `2.2.0-dev` | `true` | `true`
|
||||
`>= 2.1.0` | `2.2.0-dev` | `false` | `false`
|
||||
`>= 2.1.0-dev` | `2.2.6-dev` | `true` or `false` | `true`
|
||||
|
||||
"""
|
||||
|
||||
@@ -89,18 +99,17 @@ defmodule Version do
|
||||
|
||||
@type version :: String.t() | t
|
||||
@type requirement :: String.t() | Version.Requirement.t()
|
||||
@type major :: String.t() | non_neg_integer
|
||||
@type minor :: non_neg_integer | nil
|
||||
@type patch :: non_neg_integer | nil
|
||||
@type major :: non_neg_integer
|
||||
@type minor :: non_neg_integer
|
||||
@type patch :: non_neg_integer
|
||||
@type pre :: [String.t() | non_neg_integer]
|
||||
@type build :: String.t() | nil
|
||||
@type matchable :: {major :: major, minor :: minor, patch :: patch, pre :: pre}
|
||||
@type t :: %__MODULE__{major: major, minor: minor, patch: patch, pre: pre, build: build}
|
||||
|
||||
defmodule Requirement do
|
||||
@moduledoc false
|
||||
defstruct [:source, :matchspec, :compiled]
|
||||
@type t :: %__MODULE__{}
|
||||
@type t :: %__MODULE__{source: String.t(), matchspec: :ets.match_spec(), compiled: boolean}
|
||||
end
|
||||
|
||||
defmodule InvalidRequirementError do
|
||||
@@ -143,8 +152,8 @@ defmodule Version do
|
||||
## Options
|
||||
|
||||
* `:allow_pre` (boolean) - when `false`, pre-release versions will not match
|
||||
unless the operand is a pre-release version. See the table above
|
||||
for examples. Defaults to `true`.
|
||||
unless the operand is a pre-release version. Defaults to `true`.
|
||||
For examples, please refer to the table above under the "Requirements" section.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -154,6 +163,12 @@ defmodule Version do
|
||||
iex> Version.match?("2.0.0", "== 1.0.0")
|
||||
false
|
||||
|
||||
iex> Version.match?("2.1.6-dev", "~> 2.1.2")
|
||||
true
|
||||
|
||||
iex> Version.match?("2.1.6-dev", "~> 2.1.2", allow_pre: false)
|
||||
false
|
||||
|
||||
iex> Version.match?("foo", "== 1.0.0")
|
||||
** (Version.InvalidVersionError) invalid version: "foo"
|
||||
|
||||
@@ -165,13 +180,7 @@ defmodule Version do
|
||||
def match?(version, requirement, opts \\ [])
|
||||
|
||||
def match?(version, requirement, opts) when is_binary(requirement) do
|
||||
case parse_requirement(requirement) do
|
||||
{:ok, requirement} ->
|
||||
match?(version, requirement, opts)
|
||||
|
||||
:error ->
|
||||
raise InvalidRequirementError, requirement
|
||||
end
|
||||
match?(version, parse_requirement!(requirement), opts)
|
||||
end
|
||||
|
||||
def match?(version, %Requirement{matchspec: spec, compiled: false}, opts) do
|
||||
@@ -267,7 +276,7 @@ defmodule Version do
|
||||
@doc """
|
||||
Parses a version string into a `Version`.
|
||||
|
||||
If `string` is an invalid version, an `InvalidVersionError` is raised.
|
||||
If `string` is an invalid version, a `Version.InvalidVersionError` is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -278,7 +287,7 @@ defmodule Version do
|
||||
** (Version.InvalidVersionError) invalid version: "2.0-alpha1"
|
||||
|
||||
"""
|
||||
@spec parse!(String.t()) :: t | no_return
|
||||
@spec parse!(String.t()) :: t
|
||||
def parse!(string) when is_binary(string) do
|
||||
case parse(string) do
|
||||
{:ok, version} -> version
|
||||
@@ -310,6 +319,32 @@ defmodule Version do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses a version requirement string into a `Version.Requirement` struct.
|
||||
|
||||
If `string` is an invalid requirement, a `Version.InvalidRequirementError` is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Version.parse_requirement!("== 2.0.1")
|
||||
#Version.Requirement<== 2.0.1>
|
||||
|
||||
iex> Version.parse_requirement!("== == 2.0.1")
|
||||
** (Version.InvalidRequirementError) invalid requirement: "== == 2.0.1"
|
||||
|
||||
"""
|
||||
@doc since: "1.8.0"
|
||||
@spec parse_requirement!(String.t()) :: Requirement.t()
|
||||
def parse_requirement!(string) when is_binary(string) do
|
||||
case Version.Parser.parse_requirement(string) do
|
||||
{:ok, spec} ->
|
||||
%Requirement{source: string, matchspec: spec, compiled: false}
|
||||
|
||||
:error ->
|
||||
raise InvalidRequirementError, string
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles a requirement to its internal representation with
|
||||
`:ets.match_spec_compile/1` for faster matching.
|
||||
@@ -394,7 +429,6 @@ defmodule Version do
|
||||
to_matchspec(lexed)
|
||||
end
|
||||
|
||||
@spec parse_version(String.t()) :: {:ok, Version.matchable()} | :error
|
||||
def parse_version(string, approximate? \\ false) when is_binary(string) do
|
||||
destructure [version_with_pre, build], String.split(string, "+", parts: 2)
|
||||
destructure [version, pre], String.split(version_with_pre, "-", parts: 2)
|
||||
|
||||
@@ -8,13 +8,15 @@ Elixir applies bug fixes only to the latest minor branch. Security patches are a
|
||||
|
||||
Elixir version | Support
|
||||
:------------- | :-----------------------------
|
||||
1.7 | Bug fixes and security patches
|
||||
1.8 | Bug fixes and security patches
|
||||
1.7 | Security patches only
|
||||
1.6 | Security patches only
|
||||
1.5 | Security patches only
|
||||
1.4 | Security patches only
|
||||
1.3 | Security patches only
|
||||
|
||||
Major Elixir releases may contain breaking changes and those will be explicitly outlined in the CHANGELOG. There are currently no plans for a major v2 release.
|
||||
New releases are announced in the read-only [announcements mailing list](https://groups.google.com/group/elixir-lang-ann). All security releases [will be tagged with `[security]`](https://groups.google.com/forum/#!searchin/elixir-lang-ann/%5Bsecurity%5D%7Csort:date).
|
||||
|
||||
There are currently no plans for a major v2 release.
|
||||
|
||||
## Compatibility between non-major Elixir versions
|
||||
|
||||
@@ -48,6 +50,7 @@ Elixir version | Supported Erlang/OTP versions
|
||||
1.5 | 18 - 20
|
||||
1.6 | 19 - 20 (and Erlang/OTP 21 from v1.6.6)
|
||||
1.7 | 19 - 21
|
||||
1.8 | 20 - 21
|
||||
|
||||
While Elixir often adds compatibility to new Erlang/OTP versions on released branches, such as support for Erlang/OTP 20 in v1.4.5, those releases usually contain the minimum changes for Elixir to run without errors. Only the next minor release, in this case v1.5.0, does effectively leverage the new features provided by the latest Erlang/OTP release.
|
||||
|
||||
@@ -67,12 +70,22 @@ Elixir deprecations happen in 3 steps:
|
||||
|
||||
Deprecated feature | Hard-deprecated in | Replaced by (available since)
|
||||
:----------------------------------------------- | :----------------- | :----------------------------
|
||||
Passing a non-empty list to `Enum.into/2` | [v1.8] | `Kernel.++/2` or `Keyword.merge/2` (v1.0)
|
||||
Passing a non-empty list to `:into` in `for` | [v1.8] | `Kernel.++/2` or `Keyword.merge/2` (v1.0)
|
||||
`:seconds`, `:milliseconds`, etc. as time units | [v1.8] | `:second`, `:millisecond`, etc. (v1.4)
|
||||
`Inspect.Algebra.surround/3` | [v1.8] | `Inspect.Algebra.concat/2` and `Inspect.Algebra.nest/2` (v1.0)
|
||||
`Inspect.Algebra.surround_many/6` | [v1.8] | `Inspect.Algebra.container_doc/6` (v1.6)
|
||||
`Kernel.ParallelCompiler.files/2` | [v1.8] | `Kernel.ParallelCompiler.compile/2` (v1.6)
|
||||
`Kernel.ParallelCompiler.files_to_path/2` | [v1.8] | `Kernel.ParallelCompiler.compile_to_path/2` (v1.6)
|
||||
`Kernel.ParallelRequire.files/2` | [v1.8] | `Kernel.ParallelCompiler.require/2` (v1.6)
|
||||
`System.cwd/0` and `System.cwd!/0` | [v1.8] | `File.cwd/0` and `File.cwd!/0` (v1.0)
|
||||
`mix compile.erlang` returning `{:ok, contents}` or `:error` as the callback in `Mix.Compilers.Erlang.compile/6`| [v1.8] | Return `{:ok, contents, warnings}` or `{:error, errors, warnings}`
|
||||
`Code.get_docs/2` | [v1.7] | `Code.fetch_docs/1` (v1.7)
|
||||
Calling `super` on GenServer callbacks | [v1.7] | Not calling super (v1.0)
|
||||
`Enum.chunk/2`[`/3/4`](Enum.chunk/4) | [v1.7] | `Enum.chunk_every/2`[`/3/4`](`Enum.chunk_every/4`) (v1.5)
|
||||
Calling `super/1` on GenServer callbacks | [v1.7] | Not calling `super/1` (v1.0)
|
||||
`Enum.chunk/2`[`/3/4`](`Enum.chunk/4`) | [v1.7] | `Enum.chunk_every/2`[`/3/4`](`Enum.chunk_every/4`) (v1.5)
|
||||
`not left in right` | [v1.7] | [`left not in right`](`Kernel.SpecialForms.in/2`) (v1.5)
|
||||
`Registry.start_link/3` | [v1.7] | `Registry.start_link/1` (v1.5)
|
||||
`Stream.chunk/2`[`/3/4`](Stream.chunk/4) | [v1.7] | `Stream.chunk_every/2`[`/3/4`](`Stream.chunk_every/4`) (v1.5)
|
||||
`Stream.chunk/2`[`/3/4`](`Stream.chunk/4`) | [v1.7] | `Stream.chunk_every/2`[`/3/4`](`Stream.chunk_every/4`) (v1.5)
|
||||
`Enum.partition/2` | [v1.6] | `Enum.split_with/2` (v1.4)
|
||||
`Keyword.replace/3` | [v1.6] | `Keyword.fetch/2` + `Keyword.put/3` (v1.0)
|
||||
`Macro.unescape_tokens/1` and `Macro.unescape_tokens/2` | [v1.6] | Use `Enum.map/2` to traverse over the arguments (v1.0)
|
||||
@@ -136,4 +149,5 @@ Non-map as second argument in `URI.decode_query/2` | [v1.3] | Use a map (v1
|
||||
[v1.4]: https://github.com/elixir-lang/elixir/blob/v1.4/CHANGELOG.md#4-deprecations
|
||||
[v1.5]: https://github.com/elixir-lang/elixir/blob/v1.5/CHANGELOG.md#4-deprecations
|
||||
[v1.6]: https://github.com/elixir-lang/elixir/blob/v1.6/CHANGELOG.md#4-deprecations
|
||||
[v1.7]: https://github.com/elixir-lang/elixir/blob/master/CHANGELOG.md#4-hard-deprecations
|
||||
[v1.7]: https://github.com/elixir-lang/elixir/blob/v1.7/CHANGELOG.md#4-hard-deprecations
|
||||
[v1.8]: https://github.com/elixir-lang/elixir/blob/v1.8/CHANGELOG.md#4-hard-deprecations
|
||||
|
||||
+40
-80
@@ -6,61 +6,19 @@ Not all expressions are allowed in guard clauses, but only a handful of them. Th
|
||||
|
||||
## List of allowed expressions
|
||||
|
||||
For reference, the following is a comprehensive list of all expressions allowed in guards:
|
||||
You can find the built-in list of guards [in the `Kernel` module](Kernel.html#guards). Here is an overview:
|
||||
|
||||
* comparison operators ([`==`](`Kernel.==/2`), [`!=`](`Kernel.!=/2`), [`===`](`Kernel.===/2`), [`!==`](`Kernel.!==/2`),
|
||||
[`>`](`Kernel.>/2`), [`>=`](`Kernel.>=/2`), [`<`](`Kernel.</2`), [`<=`](`Kernel.<=/2`))
|
||||
* strictly boolean operators ([`and`](`Kernel.and/2`), [`or`](`Kernel.or/2`), [`not`](`Kernel.not/1`))
|
||||
- __NOTE__: [`&&`](`Kernel.&&/2`), [`||`](`Kernel.||/2`), and [`!`](`Kernel.!/1`) sibling operators are not allowed as they're not
|
||||
*strictly* boolean - meaning they don't require both sides to be booleans
|
||||
* arithmetic binary operators ([`+`](`Kernel.+/2`), [`-`](`Kernel.-/2`), [`*`](`Kernel.*/2`), [`/`](`Kernel.//2`))
|
||||
* arithmetic unary operators ([`+`](`Kernel.+/1`), [`-`](`Kernel.-/1`))
|
||||
* binary concatenation operator ([`<>`](`Kernel.<>/2`))
|
||||
* [`in`](`Kernel.in/2`) and [`not in`](`Kernel.in/2`) operators (as long as the right-hand side is a list or a range)
|
||||
* the following "type-check" functions (all documented in the `Kernel` module):
|
||||
* `is_atom/1`
|
||||
* `is_binary/1`
|
||||
* `is_bitstring/1`
|
||||
* `is_boolean/1`
|
||||
* `is_float/1`
|
||||
* `is_function/1`
|
||||
* `is_function/2`
|
||||
* `is_integer/1`
|
||||
* `is_list/1`
|
||||
* `is_map/1`
|
||||
* `is_nil/1`
|
||||
* `is_number/1`
|
||||
* `is_pid/1`
|
||||
* `is_port/1`
|
||||
* `is_reference/1`
|
||||
* `is_tuple/1`
|
||||
* the following guard-friendly functions (all documented in the `Kernel` module):
|
||||
* `abs/1`
|
||||
* `binary_part/3`
|
||||
* `bit_size/1`
|
||||
* `byte_size/1`
|
||||
* `div/2`
|
||||
* `elem/2`
|
||||
* `hd/1`
|
||||
* `length/1`
|
||||
* `map_size/1`
|
||||
* `node/0`
|
||||
* `node/1`
|
||||
* `rem/2`
|
||||
* `round/1`
|
||||
* `self/0`
|
||||
* `tl/1`
|
||||
* `trunc/1`
|
||||
* `tuple_size/1`
|
||||
* the following handful of Erlang bitwise operations, if imported from the `Bitwise` module:
|
||||
* [`band/2`](`Bitwise.band/2`) or the [`&&&`](`Bitwise.&&&/2`) operator
|
||||
* [`bor/2`](`Bitwise.bor/2`) or the [`|||`](`Bitwise.|||/2`) operator
|
||||
* [`bnot/1`](`Bitwise.bnot/1`) or the [`~~~`](`Bitwise.~~~/1`) operator
|
||||
* [`bsl/2`](`Bitwise.bsl/2`) or the [`<<<`](`Bitwise.<<</2`) operator
|
||||
* [`bsr/2`](`Bitwise.bsr/2`) or the [`>>>`](`Bitwise.>>>/2`) operator
|
||||
* [`bxor/2`](`Bitwise.bxor/2`) or the [`^^^`](`Bitwise.^^^/2`) operator
|
||||
* comparison operators ([`==`](`==/2`), [`!=`](`!=/2`), [`===`](`===/2`), [`!==`](`!==/2`),
|
||||
[`>`](`>/2`), [`>=`](`>=/2`), [`<`](`</2`), [`<=`](`<=/2`))
|
||||
* strictly boolean operators ([`and`](`and/2`), [`or`](`or/2`), [`not`](`not/1`)). Note [`&&`](`&&/2`), [`||`](`||/2`), and [`!`](`!/1`) sibling operators are **not allowed** as they're not *strictly* boolean - meaning they don't require arguments to be booleans
|
||||
* arithmetic unary and binary operators ([`+`](`+/1`), [`-`](`-/1`), [`+`](`+/2`), [`-`](`-/2`), [`*`](`*/2`), [`/`](`//2`))
|
||||
* [`in`](`in/2`) and [`not in`](`in/2`) operators (as long as the right-hand side is a list or a range)
|
||||
* "type-check" functions ([`is_list/1`](`is_list/1`), [`is_number/1`](`is_number/1`), etc.)
|
||||
* functions that work on built-in datatypes ([`abs/1`](`abs/1`), [`map_size/1`](`map_size/1`), etc.)
|
||||
|
||||
Macros constructed out of any combination of the above guards are also valid guards - for example, `Integer.is_even/1`. See the section "Defining custom guard expressions" below.
|
||||
The module `Bitwise` also includes a handful of [Erlang bitwise operations as guards](Bitwise.html#guards).
|
||||
|
||||
Macros constructed out of any combination of the above guards are also valid guards - for example, `Integer.is_even/1`. For more information, see the "Defining custom guard expressions" section shown below.
|
||||
|
||||
## Why guards
|
||||
|
||||
@@ -86,7 +44,7 @@ In the example above, we show how guards can be used in function clauses. There
|
||||
def foo(term) when is_float(term), do: round(term)
|
||||
```
|
||||
|
||||
* [`case`](`Kernel.SpecialForms.case/2`) expressions:
|
||||
* [`case`](`case/2`) expressions:
|
||||
|
||||
```elixir
|
||||
case x do
|
||||
@@ -96,7 +54,7 @@ In the example above, we show how guards can be used in function clauses. There
|
||||
end
|
||||
```
|
||||
|
||||
* anonymous functions ([`fn`](`Kernel.SpecialForms.fn/1`)s):
|
||||
* anonymous functions ([`fn`](`fn/1`)s):
|
||||
|
||||
```elixir
|
||||
larger_than_two? = fn
|
||||
@@ -105,10 +63,10 @@ In the example above, we show how guards can be used in function clauses. There
|
||||
end
|
||||
```
|
||||
|
||||
* custom guards can also be defined with `Kernel.defguard/1` and `Kernel.defguardp/1`.
|
||||
* custom guards can also be defined with `defguard/1` and `defguardp/1`.
|
||||
A custom guard is always defined based on existing guards.
|
||||
|
||||
Other constructs are [`for`](`Kernel.SpecialForms.for/1`), [`with`](`Kernel.SpecialForms.with/1`), [`try/rescue/catch/else`](`Kernel.SpecialForms.try/1`), and the `Kernel.match?/2`.
|
||||
Other constructs are [`for`](`for/1`), [`with`](`with/1`), [`try/rescue/catch/else`](`try/1`), and the `match?/2`.
|
||||
|
||||
## Failing guards
|
||||
|
||||
@@ -204,32 +162,34 @@ def foo(_other) do
|
||||
end
|
||||
```
|
||||
|
||||
For most cases, the two forms are exactly the same. However, there exists a subtle difference in the case of failing guards, as discussed in the section above.
|
||||
In case of a boolean expression guard, a failed element means the whole guard fails. In case of multiple guards it means the next one will be evaluated.
|
||||
The difference can be highlighted with an example:
|
||||
If each guard expression always returns a boolean, the two forms are equivalent. However, recall that if any function call in a guard raises an exception, the entire guard fails. So this function will not detect empty tuples:
|
||||
|
||||
```elixir
|
||||
def multiguard(value)
|
||||
when map_size(value) < 1
|
||||
when tuple_size(value) < 1 do
|
||||
:guard_passed
|
||||
end
|
||||
def multiguard(_value) do
|
||||
:guard_failed
|
||||
defmodule Check do
|
||||
# If given a tuple, map_size/1 will raise, and tuple_size/1 will not be evaluated
|
||||
def empty?(val) when map_size(val) == 0 or tuple_size(val) == 0, do: true
|
||||
def empty?(_val), do: false
|
||||
end
|
||||
|
||||
def boolean(value) when map_size(value) < 1 or tuple_size(value) < 1 do
|
||||
:guard_passed
|
||||
end
|
||||
def boolean(value) do
|
||||
:guard_failed
|
||||
end
|
||||
|
||||
multiguard(%{}) #=> :guard_passed
|
||||
multiguard({}) #=> :guard_passed
|
||||
|
||||
boolean(%{}) #=> :guard_passed
|
||||
boolean({}) #=> :guard_failed
|
||||
Check.empty?(%{}) #=> true
|
||||
Check.empty?({}) #=> false # true was expected!
|
||||
```
|
||||
|
||||
For cases where guards do not rely on the failing guard behavior the two forms are exactly the same semantically but there are cases where multiple guard clauses may be more aesthetically pleasing.
|
||||
This could be corrected by ensuring that no exception is raised, either via type checks like `is_map(val) and map_size(val) == 0`, or by checking equality instead, like `val == %{}`.
|
||||
|
||||
It could also be corrected by using multiple guards, so that if an exception causes one guard to fail, the next one is evaluated.
|
||||
|
||||
```elixir
|
||||
defmodule Check do
|
||||
# If given a tuple, map_size/1 will raise, and the second guard will be evaluated
|
||||
def empty?(val)
|
||||
when map_size(val) == 0
|
||||
when tuple_size(val) == 0,
|
||||
do: true
|
||||
|
||||
def empty?(_val), do: false
|
||||
end
|
||||
|
||||
Check.empty?(%{}) #=> true
|
||||
Check.empty?({}) #=> true
|
||||
```
|
||||
|
||||
@@ -16,7 +16,7 @@ For more information on running your project, see the official [Mix & OTP guide]
|
||||
|
||||
### Applications with supervision tree
|
||||
|
||||
The `mix new` command also allows the `--sup` flag to scaffold an application with a supervision tree out of the box. We talk about supervision trees later on when discussing one of the common anti-patterns when writing libraries.
|
||||
The `mix new` command also allows the `--sup` option to scaffold an application with a supervision tree out of the box. We talk about supervision trees later on when discussing one of the common anti-patterns when writing libraries.
|
||||
|
||||
## Publishing
|
||||
|
||||
@@ -70,7 +70,7 @@ iex> File.read(1)
|
||||
** (FunctionClauseError) no function clause matching in IO.chardata_to_string/1
|
||||
```
|
||||
|
||||
The usage of `:ok`/`:error` tuples is about the domain that the function works on, in this case, filesystem access. Bad arguments, logical errors, invalid options should raise regardless of the function name. If in doubt, prefer to return tuples instead of raising, as users of your library can always match on the results and raise if necessary.
|
||||
The usage of `:ok`/`:error` tuples is about the domain that the function works on, in this case, file system access. Bad arguments, logical errors, invalid options should raise regardless of the function name. If in doubt, prefer to return tuples instead of raising, as users of your library can always match on the results and raise if necessary.
|
||||
|
||||
### Avoid working with invalid data
|
||||
|
||||
@@ -100,7 +100,7 @@ This advice does not only apply to libraries but to any Elixir code. Every time
|
||||
|
||||
### Avoid application configuration
|
||||
|
||||
You should avoid using [the application environment](https://hexdocs.pm/elixir/Application.html#get_env/2) as the configuration mechanism for libraries. The application environment is **global** which means it becomes impossible for two dependencies to use your library in two different ways.
|
||||
You should avoid using the application environment (see `Application.get_env/2`) as the configuration mechanism for libraries. The application environment is **global** which means it becomes impossible for two dependencies to use your library in two different ways.
|
||||
|
||||
Let's see a simple example. Imagine that you implement a library that breaks a string in two parts based on the first occurrence of the dash `-` character:
|
||||
|
||||
@@ -192,7 +192,7 @@ Although the previous section could be summarized as "avoid macros", both topics
|
||||
|
||||
To quote [the official guide on Macros](https://elixir-lang.org/getting-started/meta/macros.html):
|
||||
|
||||
> Even though Elixir attempts its best to provide a safe environment for macros, the major responsibility of writing clean code with macros falls on developers. Macros are harder to write than ordinary Elixir functions and it’s considered to be bad style to use them when they’re not necessary. So write macros responsibly.
|
||||
> Even though Elixir attempts its best to provide a safe environment for macros, the major responsibility of writing clean code with macros falls on developers. Macros are harder to write than ordinary Elixir functions and it's considered to be bad style to use them when they're not necessary. So write macros responsibly.
|
||||
>
|
||||
> Elixir already provides mechanisms to write your everyday code in a simple and readable fashion by using its data structures and functions. Macros should only be used as a last resort. Remember that **explicit is better than implicit**. **Clear code is better than concise code**.
|
||||
|
||||
@@ -202,7 +202,7 @@ When you absolutely have to use a macro, make sure that a macro is not the only
|
||||
|
||||
A developer must never use a process for code organization purposes. A process must be used to model runtime properties such as:
|
||||
|
||||
* Mutable state and access to shared resources (such as ets, files, etc)
|
||||
* Mutable state and access to shared resources (such as ETS, files, etc.)
|
||||
* Concurrency and distribution
|
||||
* Initialization, shutdown and restart logic (as seen in supervisors)
|
||||
* System messages such as timer messages and monitoring events
|
||||
|
||||
@@ -4,7 +4,7 @@ This document covers some naming conventions in Elixir code, from casing to punc
|
||||
|
||||
## Casing
|
||||
|
||||
Elixir developers must use `snake_case` when defining variables, function names, module attributes, etc:
|
||||
Elixir developers must use `snake_case` when defining variables, function names, module attributes, etc.:
|
||||
|
||||
some_map = %{this_is_a_key: "and a value"}
|
||||
is_map(some_map)
|
||||
@@ -71,7 +71,7 @@ More examples of paired functions: `Base.decode16/2` and `Base.decode16!/2`, `Fi
|
||||
|
||||
There are also some non-paired functions, with no non-bang variant. The bang still signifies that it will raise an exception on failure. Examples: `Mix.Config.validate!/1`, `Protocol.assert_protocol!/1`
|
||||
|
||||
In macro code, the bang on `Kernel.alias!/1` and `Kernel.var!/2` signifies that [macro hygiene](http://elixir-lang.org/getting-started/meta/macros.html#macros-hygiene) is set aside.
|
||||
In macro code, the bang on `Kernel.alias!/1` and `Kernel.var!/2` signifies that [macro hygiene](https://elixir-lang.org/getting-started/meta/macros.html#macros-hygiene) is set aside.
|
||||
|
||||
## Trailing question mark (`foo?`)
|
||||
|
||||
|
||||
@@ -14,15 +14,16 @@ Operator
|
||||
`*` `/` | Left to right
|
||||
`+` `-` | Left to right
|
||||
`++` `--` `..` `<>` | Right to left
|
||||
`^^^` | Left to right
|
||||
`in` `not in` | Left to right
|
||||
`\|>` `<<<` `>>>` `~>>` `<<~` `~>` `<~` `<~>` `<\|>` | Left to right
|
||||
`\|>` `<<<` `>>>` `<<~` `~>>` `<~` `~>` `<~>` `<\|>` | Left to right
|
||||
`<` `>` `<=` `>=` | Left to right
|
||||
`==` `!=` `=~` `===` `!==` | Left to right
|
||||
`&&` `&&&` `and` | Left to right
|
||||
`\|\|` `\|\|\|` `or` | Left to right
|
||||
`&` | Unary
|
||||
`=` | Right to left
|
||||
`=>` | Right to left
|
||||
`&` | Unary
|
||||
`=>` (valid syntax only inside `%{}`) | Right to left
|
||||
`\|` | Right to left
|
||||
`::` | Right to left
|
||||
`when` | Right to left
|
||||
@@ -32,16 +33,16 @@ Operator
|
||||
|
||||
Elixir provides the following built-in comparison operators:
|
||||
|
||||
* [`==`](`Kernel.==/2`) - equality
|
||||
* [`===`](`Kernel.===/2`) - strict equality
|
||||
* [`!=`](`Kernel.!=/2`) - inequality
|
||||
* [`!==`](`Kernel.!==/2`) - strict inequality
|
||||
* [`>`](`Kernel.>/2`) - greater than
|
||||
* [`<`](`Kernel.</2`) - less than
|
||||
* [`>=`](`Kernel.>=/2`) - greater than or equal
|
||||
* [`<=`](`Kernel.<=/2`) - less than or equal
|
||||
* [`==`](`==/2`) - equality
|
||||
* [`===`](`===/2`) - strict equality
|
||||
* [`!=`](`!=/2`) - inequality
|
||||
* [`!==`](`!==/2`) - strict inequality
|
||||
* [`<`](`</2`) - less than
|
||||
* [`>`](`>/2`) - greater than
|
||||
* [`<=`](`<=/2`) - less than or equal
|
||||
* [`>=`](`>=/2`) - greater than or equal
|
||||
|
||||
The only difference between [`==`](`Kernel.==/2`) and [`===`](`Kernel.===/2`) is that [`===`](`Kernel.===/2`) is stricter when it comes to comparing integers and floats:
|
||||
The only difference between [`==`](`==/2`) and [`===`](`===/2`) is that [`===`](`===/2`) is strict when it comes to comparing integers and floats:
|
||||
|
||||
```elixir
|
||||
iex> 1 == 1.0
|
||||
@@ -50,7 +51,7 @@ iex> 1 === 1.0
|
||||
false
|
||||
```
|
||||
|
||||
[`!=`](`Kernel.!=/2`) and [`!==`](`Kernel.!==/2`) act as the negation of [`==`](`Kernel.==/2`) and [`===`](`Kernel.===/2`), respectively.
|
||||
[`!=`](`!=/2`) and [`!==`](`!==/2`) act as the negation of [`==`](`==/2`) and [`===`](`===/2`), respectively.
|
||||
|
||||
### Term ordering
|
||||
|
||||
@@ -61,18 +62,18 @@ iex> 1 < :an_atom
|
||||
true
|
||||
```
|
||||
|
||||
The reason we can compare different data types is pragmatism. Sorting algorithms don’t need to worry about different data types in order to sort. For reference, the overall sorting order is defined below:
|
||||
The reason we can compare different data types is pragmatism. Sorting algorithms don't need to worry about different data types in order to sort. For reference, the overall sorting order is defined below:
|
||||
|
||||
```
|
||||
number < atom < reference < function < port < pid < tuple < map < list < bitstring
|
||||
```
|
||||
|
||||
When comparing two numbers of different types (a number is either an integer or a float), a conversion to the type with greater precision will always occur, unless the comparison operator used is either `===` or `!==`. A float will be considered more precise than an integer, unless the float is greater/less than +/-9007199254740992.0, at which point all the significant figures of the float are to the left of the decimal point. This behavior exists so that the comparison of large numbers remains transitive.
|
||||
When comparing two numbers of different types (a number being either an integer or a float), a conversion to the type with greater precision will always occur, unless the comparison operator used is either [`===`](`===/2`) or [`!==`](`!==/2`). A float will be considered more precise than an integer, unless the float is greater/less than +/-9007199254740992.0 respectively, at which point all the significant figures of the float are to the left of the decimal point. This behavior exists so that the comparison of large numbers remains transitive.
|
||||
|
||||
The collection types are compared using the following rules:
|
||||
|
||||
* Tuples are compared by size then element by element.
|
||||
* Maps are compared by size then by keys in ascending term order then by values in key order. In the specific case of maps' key ordering, integers are always considered to be less than floats.
|
||||
* Tuples are compared by size, then element by element.
|
||||
* Maps are compared by size, then by keys in ascending term order, then by values in key order. In the specific case of maps' key ordering, integers are always considered to be less than floats.
|
||||
* Lists are compared element by element.
|
||||
* Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
|
||||
|
||||
@@ -111,10 +112,10 @@ The following is a table of all the operators that Elixir is capable of parsing,
|
||||
* `&&&`
|
||||
* `<<<`
|
||||
* `>>>`
|
||||
* `~>>`
|
||||
* `<<~`
|
||||
* `~>`
|
||||
* `~>>`
|
||||
* `<~`
|
||||
* `~>`
|
||||
* `<~>`
|
||||
* `<|>`
|
||||
* `^^^`
|
||||
|
||||
@@ -17,15 +17,17 @@ These are the reserved words in the Elixir language. They are detailed throughou
|
||||
|
||||
### Numbers
|
||||
|
||||
Integers (`1234`) and floats (`123.4`) in Elixir are represented as a sequence of digits that may be separated by underscore for readability purposes, such as `1_000_000`. Integers never contain a dot (`.`) in their representation. Floats contain a dot and at least one other digit after the dot. Floats also support the scientific format, such as `123.4e10` or `123.4E10`.
|
||||
Integers (`1234`) and floats (`123.4`) in Elixir are represented as a sequence of digits that may be separated by underscore for readability purposes, such as `1_000_000`. Integers never contain a dot (`.`) in their representation. Floats contain a dot and at least one other digit after the dot. Floats also support the scientific notation, such as `123.4e10` or `123.4E10`.
|
||||
|
||||
### Atoms
|
||||
|
||||
Atoms in Elixir start with a colon (`:`) which must be followed by non-combining Unicode characters and underscore. The atom may continue using a sequence of Unicode characters, including numbers, underscore and `@`. Atoms may end in `!` or `?`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
|
||||
Unquoted atoms start with a colon (`:`) which must be inmediately followed by an underscore or a Unicode letter. The atom may continue using a sequence of Unicode letters, numbers, underscores, and `@`. Atoms may end in `!` or `?`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Valid unquoted atoms are: `:ok`, `:ISO8601`, and `:integer?`.
|
||||
|
||||
All operators in Elixir are also valid atoms. Valid examples are `:foo`, `:FOO`, `:foo_42`, `:foo@bar` and `:++`. Invalid examples are `:@foo` (`@` is not allowed at start), `:123` (numbers are not allowed at start) and `:(*)` (not a valid operator).
|
||||
If the colon is immediately followed by a pair of double- or single-quotes surrounding the atom name, the atom is considered quoted. In contrast with an unquoted atom, this one can be made of any Unicode character (not only letters), such as `:'🌢 Elixir'`, `:"++olá++"`, and `:"123"`.
|
||||
|
||||
If the colon is followed by a double- or single-quote, the atom can be made of any character, such as `:"++olá++"`.
|
||||
Quoted and unquoted atoms with the same name are considered equivalent, so `:atom`, `:"atom"`, and `:'atom'` represent the same atom. The only catch is that the compiler will warn when quotes are used in atoms that do not need to be quoted.
|
||||
|
||||
All operators in Elixir are also valid atoms. Valid examples are `:foo`, `:FOO`, `:foo_42`, `:foo@bar`, and `:++`. Invalid examples are `:@foo` (`@` is not allowed at start), `:123` (numbers are not allowed at start), and `:(*)` (not a valid operator).
|
||||
|
||||
`true`, `false`, and `nil` are reserved words that are represented by the atoms `:true`, `:false` and `:nil` respectively.
|
||||
|
||||
@@ -80,13 +82,13 @@ Structs built on the map syntax by passing the struct name between `%` and `{`.
|
||||
|
||||
### Variables
|
||||
|
||||
Variables in Elixir must start with underscore or a non-combining Unicode character that is not in uppercase or titlecase. The variable may continue using a sequence of Unicode characters, including numbers and underscore. Variables may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
|
||||
Variables in Elixir must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The variable may continue using a sequence of Unicode letters, numbers, and underscores. Variables may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification.
|
||||
|
||||
[Elixir's naming conventions](naming-conventions.html) recommend variables to be in `snake_case` format.
|
||||
|
||||
### Non-qualified calls (local calls)
|
||||
|
||||
Non-qualified calls, such as `add(1, 2)`, must start with underscore or a non-combining Unicode character that is not in uppercase or titlecase. The call may continue using a sequence of Unicode characters, including numbers and underscore. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
|
||||
Non-qualified calls, such as `add(1, 2)`, must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The call may continue using a sequence of Unicode letters, numbers, and underscore. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification.
|
||||
|
||||
Parentheses for non-qualified calls are optional, except for zero-arity calls, which would then be ambiguous with variables. If parentheses are used, they must immediately follow the function name *without spaces*. For example, `add (1, 2)` is a syntax error, since `(1, 2)` is treated as an invalid block which is attempted to be given as a single argument to `add`.
|
||||
|
||||
@@ -98,7 +100,7 @@ As many programming languages, Elixir also support operators as non-qualified ca
|
||||
|
||||
### Qualified calls (remote calls)
|
||||
|
||||
Qualified calls, such as `Math.add(1, 2)`, must start with underscore or a non-combining Unicode character that is not in uppercase or titlecase. The call may continue using a sequence of Unicode characters, including numbers and underscore. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
|
||||
Qualified calls, such as `Math.add(1, 2)`, must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The call may continue using a sequence of Unicode letters, numbers, and underscores. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification.
|
||||
|
||||
[Elixir's naming conventions](naming-conventions.html) recommend calls to be in `snake_case` format.
|
||||
|
||||
@@ -118,7 +120,7 @@ Blocks are multiple Elixir expressions separated by newlines or semi-colons. A n
|
||||
|
||||
### Left to right arrow
|
||||
|
||||
The left to right arrow (`->`) is used to establish a relationship between left and right. The left side may have zero, one or more arguments, the right side is zero, one or more expressions separated by new line. The `->` is always between one of the following terminators: `do`/`end`, `fn`/`end` or `(`/`)`.
|
||||
The left to right arrow (`->`) is used to establish a relationship between left and right, commonly referred as clauses. The left side may have zero, one, or more arguments; the right side is zero, one, or more expressions separated by new line. The `->` may appear one or more times between one of the following terminators: `do`/`end`, `fn`/`end` or `(`/`)`. When `->` is used, only other clauses are allowed between those terminators. Mixing clauses and regular expressions is invalid syntax.
|
||||
|
||||
It is seen on `case` and `cond` constructs between `do`/`end`:
|
||||
|
||||
@@ -437,7 +439,7 @@ However Elixir introduces a syntax sugar where the keywords above may be written
|
||||
[foo: 1, bar: 2]
|
||||
```
|
||||
|
||||
Atoms with foreign characters in their name, such as whitespace, must be wrapped in quotes. This rule applies to keywords as well:
|
||||
Atoms with foreign characters, such as whitespace, must be wrapped in quotes. This rule applies to keywords as well:
|
||||
|
||||
```elixir
|
||||
[{:"foo bar", 1}, {:"bar baz", 2}] == ["foo bar": 1, "bar baz": 2]
|
||||
|
||||
@@ -68,7 +68,7 @@ The notation to represent the union of types is the pipe `|`. For example, the t
|
||||
| nonempty_maybe_improper_list(type1, type2) # non-empty proper or improper list
|
||||
|
||||
| Literals # Described in section "Literals"
|
||||
| Builtin # Described in section "Built-in types"
|
||||
| BuiltIn # Described in section "Built-in types"
|
||||
| Remotes # Described in section "Remote types"
|
||||
| UserDefined # Described in section "User-defined types"
|
||||
|
||||
@@ -191,7 +191,7 @@ If you want to specify more than one variable, you separate them by a comma.
|
||||
|
||||
@spec function(arg1, arg2) :: {arg1, arg2} when arg1: atom, arg2: integer
|
||||
|
||||
Type variables with no restriction can also be defined.
|
||||
Type variables with no restriction can also be defined using `var`.
|
||||
|
||||
@spec function(arg) :: [arg] when arg: var
|
||||
|
||||
@@ -260,4 +260,4 @@ Elixir's standard library contains a few frequently used behaviours such as `Gen
|
||||
|
||||
Elixir discourages the use of the `string()` type. The `string()` type refers to Erlang strings, which are known as "charlists" in Elixir. They do not refer to Elixir strings, which are UTF-8 encoded binaries. To avoid confusion, if you attempt to use the type `string()`, Elixir will emit a warning. You should use `charlist()`, `binary()` or `String.t()` accordingly.
|
||||
|
||||
Note `String.t()` and `binary()` are equivalent to analysis tools. Although, for those reading the documentation, `String.t()` implies it is a UTF-8 encoded binary.
|
||||
Note that `String.t()` and `binary()` are equivalent to analysis tools. Although, for those reading the documentation, `String.t()` implies it is a UTF-8 encoded binary.
|
||||
|
||||
@@ -17,6 +17,7 @@ Documentation in Elixir is usually attached to module attributes. Let's see an e
|
||||
@moduledoc """
|
||||
This is the Hello module.
|
||||
"""
|
||||
@moduledoc since: "1.0.0"
|
||||
|
||||
@doc """
|
||||
Says hello to the given `name`.
|
||||
@@ -29,12 +30,13 @@ Documentation in Elixir is usually attached to module attributes. Let's see an e
|
||||
:ok
|
||||
|
||||
"""
|
||||
@doc since: "1.3.0"
|
||||
def world(name) do
|
||||
IO.puts "hello #{name}"
|
||||
end
|
||||
end
|
||||
|
||||
The `@moduledoc` attribute is used to add documentation to the module. `@doc` is used before a function to provide documentation for it. Besides the attributes above, `@typedoc` can also be used to attach documentation to types defined as part of typespecs.
|
||||
The `@moduledoc` attribute is used to add documentation to the module. `@doc` is used before a function to provide documentation for it. Besides the attributes above, `@typedoc` can also be used to attach documentation to types defined as part of typespecs. Elixir also allows metadata to be attached to documentation, by passing a keyword list to `@doc` and friends.
|
||||
|
||||
## Function Arguments
|
||||
|
||||
@@ -51,6 +53,20 @@ The compiler will infer this argument as `map`. Sometimes the inference will be
|
||||
size
|
||||
end
|
||||
|
||||
## Documentation metadata
|
||||
|
||||
Elixir allows developers to attach arbitrary metadata to the documentation. This is done by passing a keyword list to the relevant attribute (such as `@moduledoc`, `@typedoc`, and `@doc`). A commonly used metadata is `:since`, which annotates in which version that particular module, function, type, or callback was added, as shown in the example above.
|
||||
|
||||
Another common metadata is `:deprecated`, which emits a warning in the documentation, explaining that its usage is discouraged:
|
||||
|
||||
@doc deprecated: "Use Foo.bar/2 instead"
|
||||
|
||||
Note the `:deprecated` key does not warn when a developer invokes the functions. If you want the code to also emit a warning, you can use the `@deprecated` attribute:
|
||||
|
||||
@deprecated "Use Foo.bar/2 instead"
|
||||
|
||||
Metadata can have any key. Documentation tools often use metadata to provide more data to readers and to enrich the user experience.
|
||||
|
||||
## Recommendations
|
||||
|
||||
When writing documentation:
|
||||
@@ -59,7 +75,7 @@ When writing documentation:
|
||||
|
||||
* Reference modules by their full name.
|
||||
|
||||
Markdown uses backticks (`` ` ``) to quote code. Elixir builds on top of that to automatically generate links when module or function names are referenced. For this reason, always use full module names. If you have a module called `MyApp.Hello`, always reference it as `` `MyApp.Hello` `` and never as `` `Hello` ``.
|
||||
Markdown uses backticks (`` ` ``) to quote code. Elixir builds on top of that to automatically generate links when module or function names are referenced. For this reason, always use full module names. If you have a module called `MyApp.Hello`, always reference it as `` `MyApp.Hello` `` and never as `` `Hello` ``.
|
||||
|
||||
* Reference functions by name and arity if they are local, as in `` `world/1` ``, or by module, name and arity if pointing to an external module: `` `MyApp.Hello.world/1` ``.
|
||||
|
||||
@@ -70,6 +86,8 @@ When writing documentation:
|
||||
* Start new sections with second level Markdown headers `##`. First level headers are reserved for module and function names.
|
||||
|
||||
* Place documentation before the first clause of multi-clause functions. Documentation is always per function and arity and not per clause.
|
||||
|
||||
* Use the `:since` key in the documentation metadata to annotate whenever new functions or modules are added to your API.
|
||||
|
||||
## Doctests
|
||||
|
||||
@@ -77,19 +95,26 @@ We recommend that developers include examples in their documentation, often unde
|
||||
|
||||
Notice doctests have limitations. When you cannot doctest a function, because it relies on state or side-effects, we recommend developers include examples directly without the `iex>` prompt.
|
||||
|
||||
## Documentation != Comments
|
||||
## Documentation != Code comments
|
||||
|
||||
Elixir treats documentation and code comments as different concepts. Documentation is for users of your Application Programming Interface (API), be it your co-worker or your future self. Modules and functions must always be documented if they are part of your API.
|
||||
Elixir treats documentation and code comments as different concepts. Documentation is an explicit contract between you and users of your Application Programming Interface (API), be them third-party developers, co-workers, or your future self. Modules and functions must always be documented if they are part of your API.
|
||||
|
||||
Code comments are for developers reading the code. They are useful to mark improvements, leave notes for developers reading the code (for example, you decided not to call a function due to a bug in a library) and so forth.
|
||||
Code comments are aimed at developers reading the code. They are useful for marking improvements, leaving notes (for example, why you had to resort to a workaround due to a bug in a library), and so forth. They are tied to the source code: you can completely rewrite a function and remove all existing code comments, and it will continue to behave the same, with no change to either its behaviour or its documentation.
|
||||
|
||||
In other words: documentation is required, code comments are optional.
|
||||
Because private functions cannot be accessed externally, Elixir will warn if a private function has a `@doc` attribute and will discard its content. However, you can add code comments to private functions, as with any other piece of code, and we recommend developers to do so whenever they believe it will add relevant information to the readers and maintainers of such code.
|
||||
|
||||
Finally, beware of redundant code comments, such as the ones describing the exact same that the code does:
|
||||
|
||||
# Total is the sum of the batch and individual entries
|
||||
total = batch_sum + individual_sum
|
||||
|
||||
In summary, documentation is a contract with users of your API, who may not necessarily have access to the source code; whereas code comments are for those who interact directly with the source. You can learn and express different guarantees about your software by separating those two concepts.
|
||||
|
||||
## Hiding Internal Modules and Functions
|
||||
|
||||
Besides the modules and functions libraries provide as part of their public interface, libraries may also implement important functionality that is not part of their API. While these modules and functions can be accessed, they are meant to be internal to the library and thus should not have documentation for end users.
|
||||
|
||||
Luckily, Elixir allows developers to hide modules and functions from the documentation. For example, one common practice for documenting internal behaviour is to set the `@moduledoc` attribute to `false` while documenting each function:
|
||||
Conveniently, Elixir allows developers to hide modules and functions from the documentation, by setting `@doc false` to hide a particular function, or `@moduledoc false` to hide the whole module. If a module is hidden, you may even document the functions in the module, but the module itself won't be listed in the documentation:
|
||||
|
||||
defmodule MyApp.Hidden do
|
||||
@moduledoc false
|
||||
@@ -102,25 +127,12 @@ Luckily, Elixir allows developers to hide modules and functions from the documen
|
||||
end
|
||||
end
|
||||
|
||||
Similarly, developers can add `@doc false` to functions they do not want to be publicly exposed:
|
||||
|
||||
defmodule MyApp.Sample do
|
||||
@doc false
|
||||
def add(a, b), do: a + b
|
||||
end
|
||||
|
||||
However, keep in mind that adding `@doc false` does not make the function private. The function above can still be invoked as `MyApp.Sample.add(1, 2)`. Not only that, if `MyApp.Sample` is imported, the `add/2` function will also be imported into the caller. For those reasons, be cautious when adding `@doc false` to functions, instead use one of these two options:
|
||||
|
||||
* Move the undocumented function to a module with `@moduledoc false`, like `MyApp.Hidden`, ensuring the function won't be accidentally exposed or imported. Remember you can use `@moduledoc false` to hide a whole module and still document each function with `@doc`. Tools will still ignore the module.
|
||||
|
||||
* Start the function name with one or two underscores, for example, `__add__/2`, and add `@doc false`. The compiler does not import functions with leading underscores and they hint to anyone reading the code of their intended private usage.
|
||||
|
||||
## Documenting Private Functions
|
||||
|
||||
Elixir warns if a private function has a `@doc` attribute and discards its content, because `@doc` is intended to be used only for your public interface.
|
||||
|
||||
Private functions may still need internal documentation for maintainers, though. That can be accomplished with code comments.
|
||||
|
||||
## Code.fetch_docs/1
|
||||
|
||||
Elixir stores documentation inside pre-defined chunks in the bytecode. It can be accessed from Elixir by using the `Code.fetch_docs/1` function. This also means documentation is only accessed when required and not when modules are loaded by the Virtual Machine. The only downside is that modules defined in-memory, like the ones defined in IEx, cannot have their documentation accessed as they do not have their bytecode written to disk.
|
||||
|
||||
@@ -5,5 +5,5 @@
|
||||
{registered, [elixir_config, elixir_code_server]},
|
||||
{applications, [kernel,stdlib,compiler]},
|
||||
{mod, {elixir,[]}},
|
||||
{env, [{ansi_enabled, false}]}
|
||||
{env, [{ansi_enabled, false}, {time_zone_database, 'Elixir.Calendar.UTCOnlyTimeZoneDatabase'}]}
|
||||
]}.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
-behaviour(application).
|
||||
-export([start_cli/0,
|
||||
string_to_tokens/4, tokens_to_quoted/3, 'string_to_quoted!'/4,
|
||||
env_for_eval/1, env_for_eval/2, quoted_to_erl/2, quoted_to_erl/3,
|
||||
env_for_eval/1, env_for_eval/2, quoted_to_erl/2,
|
||||
eval/2, eval/3, eval_forms/3, eval_forms/4, eval_quoted/3]).
|
||||
-include("elixir.hrl").
|
||||
-define(system, 'Elixir.System').
|
||||
@@ -25,7 +25,7 @@
|
||||
-export([start/2, stop/1, config_change/3]).
|
||||
|
||||
start(_Type, _Args) ->
|
||||
OTPRelease = parse_otp_release(),
|
||||
_ = parse_otp_release(),
|
||||
Encoding = file:native_name_encoding(),
|
||||
|
||||
preload_common_modules(),
|
||||
@@ -33,9 +33,8 @@ start(_Type, _Args) ->
|
||||
check_file_encoding(Encoding),
|
||||
check_endianness(),
|
||||
|
||||
%% TODO: Remove OTPRelease check once we support OTP 20+.
|
||||
Tokenizer = case code:ensure_loaded('Elixir.String.Tokenizer') of
|
||||
{module, Mod} when OTPRelease >= 20 -> Mod;
|
||||
{module, Mod} -> Mod;
|
||||
_ -> elixir_tokenizer
|
||||
end,
|
||||
|
||||
@@ -103,21 +102,15 @@ preload_common_modules() ->
|
||||
%% the codebase we can avoid code:ensure_loaded/1 checks.
|
||||
_ = code:ensure_loaded('Elixir.Kernel'),
|
||||
_ = code:ensure_loaded('Elixir.Macro.Env'),
|
||||
|
||||
%% We need to make sure the re module is preloaded to make
|
||||
%% function_exported checks inside Regex.version is fast.
|
||||
%% TODO: Remove this once we support OTP 20+.
|
||||
_ = code:ensure_loaded(re),
|
||||
|
||||
ok.
|
||||
|
||||
parse_otp_release() ->
|
||||
%% Whenever we change this check, we should also change escript.build and Makefile.
|
||||
case string:to_integer(erlang:system_info(otp_release)) of
|
||||
{Num, _} when Num >= 19 ->
|
||||
{Num, _} when Num >= 20 ->
|
||||
Num;
|
||||
_ ->
|
||||
io:format(standard_error, "unsupported Erlang/OTP version, expected Erlang/OTP 19+~n", []),
|
||||
io:format(standard_error, "unsupported Erlang/OTP version, expected Erlang/OTP 20+~n", []),
|
||||
erlang:halt(1)
|
||||
end.
|
||||
|
||||
@@ -240,7 +233,7 @@ eval(String, Binding, #{line := Line, file := File} = E) when
|
||||
eval_quoted(Tree, Binding, Opts) when is_list(Opts) ->
|
||||
eval_quoted(Tree, Binding, env_for_eval(Opts));
|
||||
eval_quoted(Tree, Binding, #{line := Line} = E) ->
|
||||
eval_forms(elixir_quote:linify(Line, Tree), Binding, E).
|
||||
eval_forms(elixir_quote:linify(Line, line, Tree), Binding, E).
|
||||
|
||||
%% Handle forms evaluation. The main difference to
|
||||
%% eval_quoted is that it does not linify the given
|
||||
@@ -262,7 +255,7 @@ eval_forms(Tree, Binding, Env, Scope) ->
|
||||
% Below must be all one line for locations to be the same
|
||||
% when the stacktrace is extended to the full stacktrace.
|
||||
{value, Value, NewBinding} =
|
||||
try erl_eval:expr(Erl, ParsedBinding, none, none, none) catch Class:Exception -> erlang:raise(Class, Exception, get_stacktrace(erlang:get_stacktrace())) end,
|
||||
try erl_eval:expr(Erl, ParsedBinding, none, none, none) catch ?WITH_STACKTRACE(Class, Exception, Stacktrace) erlang:raise(Class, Exception, get_stacktrace(Stacktrace)) end,
|
||||
{Value, elixir_erl_var:dump_binding(NewBinding, NewScope), NewEnv, NewScope}
|
||||
end.
|
||||
|
||||
@@ -273,10 +266,9 @@ get_stacktrace(Stacktrace) ->
|
||||
try
|
||||
throw(stack)
|
||||
catch
|
||||
throw:stack ->
|
||||
?WITH_STACKTRACE(throw, stack, CurrentStack)
|
||||
% Ignore stack item for current function.
|
||||
[_ | CurrentStack] = erlang:get_stacktrace(),
|
||||
merge_stacktrace(Stacktrace, CurrentStack)
|
||||
merge_stacktrace(Stacktrace, tl(CurrentStack))
|
||||
end.
|
||||
|
||||
% The stacktrace did not include the current stack, re-add it.
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
-define(line(Opts), elixir_utils:get_line(Opts)).
|
||||
-define(generated(Meta), [{generated, true} | Meta]).
|
||||
-define(var_context, ?MODULE).
|
||||
-define(remote(Ann, Module, Function, Args), {call, Ann, {remote, Ann, {atom, Ann, Module}, {atom, Ann, Function}}, Args}).
|
||||
|
||||
-record(elixir_erl, {
|
||||
context=nil, %% can be match, guards or nil
|
||||
@@ -23,8 +24,6 @@
|
||||
aliases_hygiene=true,
|
||||
imports_hygiene=true,
|
||||
unquote=true,
|
||||
unquoted=false,
|
||||
escape=false,
|
||||
generated=false
|
||||
}).
|
||||
|
||||
@@ -40,3 +39,22 @@
|
||||
mismatch_hints=[],
|
||||
warn_on_unnecessary_quotes=true
|
||||
}).
|
||||
|
||||
%% TODO: Remove this once we support Erlang/OTP 21+ exclusively.
|
||||
-ifdef(OTP_RELEASE). %% defined on OTP 21+
|
||||
-define(WITH_STACKTRACE(K, R, S), K:R:S ->).
|
||||
-else.
|
||||
-define(WITH_STACKTRACE(K, R, S), K:R -> S = erlang:get_stacktrace(),).
|
||||
-endif.
|
||||
|
||||
%% TODO: Remove this once we support Erlang/OTP 22+ exclusively.
|
||||
%% See https://github.com/erlang/otp/pull/1972
|
||||
-ifdef(OTP_RELEASE).
|
||||
-if(?OTP_RELEASE >= 22).
|
||||
-define(NO_SPAWN_COMPILER_PROCESS, no_spawn_compiler_process).
|
||||
-elif(?OTP_RELEASE >= 21).
|
||||
-define(NO_SPAWN_COMPILER_PROCESS, dialyzer, no_spawn_compiler_process).
|
||||
-endif.
|
||||
-else.
|
||||
-define(NO_SPAWN_COMPILER_PROCESS, dialyzer, no_spawn_compiler_process).
|
||||
-endif.
|
||||
@@ -22,7 +22,7 @@ store_alias(New, Old, Aliases) ->
|
||||
|
||||
store_macro_alias(Meta, New, Old, Aliases) ->
|
||||
case lists:keyfind(counter, 1, Meta) of
|
||||
{counter, Counter} when is_integer(Counter) ->
|
||||
{counter, Counter} ->
|
||||
lists:keystore(New, 1, Aliases, {New, {Counter, Old}});
|
||||
false ->
|
||||
Aliases
|
||||
@@ -33,7 +33,7 @@ remove_alias(Atom, Aliases) ->
|
||||
|
||||
remove_macro_alias(Meta, Atom, Aliases) ->
|
||||
case lists:keyfind(counter, 1, Meta) of
|
||||
{counter, Counter} when is_integer(Counter) ->
|
||||
{counter, _Counter} ->
|
||||
lists:keydelete(Atom, 1, Aliases);
|
||||
false ->
|
||||
Aliases
|
||||
|
||||
@@ -7,7 +7,7 @@ expand(Meta, Args, E, RequireSize) ->
|
||||
case ?key(E, context) of
|
||||
match ->
|
||||
{EArgs, Alignment, EE} =
|
||||
expand(Meta, fun elixir_expand:expand/2, Args, [], E, 0, RequireSize),
|
||||
expand(Meta, fun elixir_expand:expand/2, Args, [], E, E, 0, RequireSize),
|
||||
|
||||
case find_match(EArgs) of
|
||||
false ->
|
||||
@@ -16,14 +16,14 @@ expand(Meta, Args, E, RequireSize) ->
|
||||
form_error(Meta, ?key(EE, file), ?MODULE, {nested_match, Match})
|
||||
end;
|
||||
_ ->
|
||||
{EArgs, Alignment, {EC, EV}} =
|
||||
expand(Meta, fun elixir_expand:expand_arg/2, Args, [], {E, E}, 0, RequireSize),
|
||||
{{'<<>>', [{alignment, Alignment} | Meta], EArgs}, elixir_env:mergea(EV, EC)}
|
||||
{EArgs, Alignment, {_EC, EV}} =
|
||||
expand(Meta, fun elixir_expand:expand_arg/2, Args, [], {E, E}, E, 0, RequireSize),
|
||||
{{'<<>>', [{alignment, Alignment} | Meta], EArgs}, EV}
|
||||
end.
|
||||
|
||||
expand(_BitstrMeta, _Fun, [], Acc, E, Alignment, _RequireSize) ->
|
||||
expand(_BitstrMeta, _Fun, [], Acc, E, _OriginalE, Alignment, _RequireSize) ->
|
||||
{lists:reverse(Acc), Alignment, E};
|
||||
expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, Alignment, RequireSize) ->
|
||||
expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, OriginalE, Alignment, RequireSize) ->
|
||||
{ELeft, EL} = expand_expr(Meta, Left, Fun, E),
|
||||
|
||||
%% Variables defined outside the binary can be accounted
|
||||
@@ -38,7 +38,7 @@ expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, Alignment, Re
|
||||
end,
|
||||
|
||||
EType = expr_type(ELeft),
|
||||
{ERight, EAlignment, ES} = expand_specs(EType, Meta, Right, EM, RequireSize or MatchSize),
|
||||
{ERight, EAlignment, ES} = expand_specs(EType, Meta, Right, EM, OriginalE, RequireSize or MatchSize),
|
||||
|
||||
EE =
|
||||
case EL of
|
||||
@@ -65,15 +65,15 @@ expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, Alignment, Re
|
||||
prepend_unless_bitstring_in_match(EType, Meta, ELeft, ERight, Acc, E)
|
||||
end,
|
||||
|
||||
expand(BitstrMeta, Fun, T, EAcc, EE, alignment(Alignment, EAlignment), RequireSize);
|
||||
expand(BitstrMeta, Fun, [{_, Meta, _} = H | T], Acc, E, Alignment, RequireSize) ->
|
||||
expand(BitstrMeta, Fun, T, EAcc, EE, OriginalE, alignment(Alignment, EAlignment), RequireSize);
|
||||
expand(BitstrMeta, Fun, [{_, Meta, _} = H | T], Acc, E, OriginalE, Alignment, RequireSize) ->
|
||||
{Expr, ES} = expand_expr(Meta, H, Fun, E),
|
||||
{EAcc, EAlignment} = wrap_expr(Expr, Acc),
|
||||
expand(BitstrMeta, Fun, T, EAcc, ES, alignment(Alignment, EAlignment), RequireSize);
|
||||
expand(Meta, Fun, [H | T], Acc, E, Alignment, RequireSize) ->
|
||||
expand(BitstrMeta, Fun, T, EAcc, ES, OriginalE, alignment(Alignment, EAlignment), RequireSize);
|
||||
expand(Meta, Fun, [H | T], Acc, E, OriginalE, Alignment, RequireSize) ->
|
||||
{Expr, ES} = expand_expr(Meta, H, Fun, E),
|
||||
{EAcc, EAlignment} = wrap_expr(Expr, Acc),
|
||||
expand(Meta, Fun, T, EAcc, ES, alignment(Alignment, EAlignment), RequireSize).
|
||||
expand(Meta, Fun, T, EAcc, ES, OriginalE, alignment(Alignment, EAlignment), RequireSize).
|
||||
|
||||
prepend_unless_bitstring_in_match(Type, Meta, Left, Right, Acc, E) ->
|
||||
Expr = {'::', Meta, [Left, Right]},
|
||||
@@ -137,7 +137,8 @@ compute_alignment(_, _, _) -> unknown.
|
||||
%% Expands the expression of a bitstring, that is, the LHS of :: or
|
||||
%% an argument of the bitstring (such as "foo" in "<<foo>>").
|
||||
|
||||
expand_expr(_, {{'.', M1, ['Elixir.Kernel', to_string]}, M2, [Arg]}, Fun, E) ->
|
||||
expand_expr(_, {{'.', M1, [Mod, to_string]}, M2, [Arg]}, Fun, E)
|
||||
when Mod == 'Elixir.Kernel'; Mod == 'Elixir.String.Chars' ->
|
||||
case Fun(Arg, E) of
|
||||
{EBin, EE} when is_binary(EBin) -> {EBin, EE};
|
||||
{EArg, EE} -> {{{'.', M1, ['Elixir.String.Chars', to_string]}, M2, [EArg]}, EE}
|
||||
@@ -156,7 +157,7 @@ env_for_error(E) -> E.
|
||||
|
||||
%% Expands and normalizes types of a bitstring.
|
||||
|
||||
expand_specs(ExprType, Meta, Info, E, RequireSize) ->
|
||||
expand_specs(ExprType, Meta, Info, E, OriginalE, RequireSize) ->
|
||||
Default =
|
||||
#{size => default,
|
||||
unit => default,
|
||||
@@ -164,7 +165,7 @@ expand_specs(ExprType, Meta, Info, E, RequireSize) ->
|
||||
type => default,
|
||||
endianness => default},
|
||||
{#{size := Size, unit := Unit, type := Type, endianness := Endianness, sign := Sign}, ES} =
|
||||
expand_each_spec(Meta, unpack_specs(Info, []), Default, E),
|
||||
expand_each_spec(Meta, unpack_specs(Info, []), Default, E, OriginalE),
|
||||
MergedType = type(Meta, ExprType, Type, E),
|
||||
validate_size_required(Meta, RequireSize, ExprType, MergedType, Size, ES),
|
||||
SizeAndUnit = size_and_unit(Meta, ExprType, Size, Unit, ES),
|
||||
@@ -189,11 +190,11 @@ type(_, default, Type, _) ->
|
||||
type(Meta, Other, Value, E) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {bittype_mismatch, Value, Other, type}).
|
||||
|
||||
expand_each_spec(Meta, [{Expr, _, Args} = H | T], Map, E) when is_atom(Expr) ->
|
||||
expand_each_spec(Meta, [{Expr, _, Args} = H | T], Map, E, OriginalE) when is_atom(Expr) ->
|
||||
case validate_spec(Expr, Args) of
|
||||
{Key, Arg} ->
|
||||
{Value, EE} = expand_spec_arg(Arg, E),
|
||||
validate_spec_arg(Meta, Key, Value, EE),
|
||||
validate_spec_arg(Meta, Key, Value, EE, OriginalE),
|
||||
|
||||
case maps:get(Key, Map) of
|
||||
default -> ok;
|
||||
@@ -201,25 +202,25 @@ expand_each_spec(Meta, [{Expr, _, Args} = H | T], Map, E) when is_atom(Expr) ->
|
||||
Other -> form_error(Meta, ?key(E, file), ?MODULE, {bittype_mismatch, Value, Other, Key})
|
||||
end,
|
||||
|
||||
expand_each_spec(Meta, T, maps:put(Key, Value, Map), EE);
|
||||
expand_each_spec(Meta, T, maps:put(Key, Value, Map), EE, OriginalE);
|
||||
none ->
|
||||
case 'Elixir.Macro':expand(H, elixir_env:linify({?line(Meta), E})) of
|
||||
H ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {undefined_bittype, H});
|
||||
NewTypes ->
|
||||
expand_each_spec(Meta, unpack_specs(NewTypes, []) ++ T, Map, E)
|
||||
expand_each_spec(Meta, unpack_specs(NewTypes, []) ++ T, Map, E, OriginalE)
|
||||
end
|
||||
end;
|
||||
expand_each_spec(Meta, [Expr | _], _Map, E) ->
|
||||
expand_each_spec(Meta, [Expr | _], _Map, E, _OriginalE) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {undefined_bittype, Expr});
|
||||
expand_each_spec(_Meta, [], Map, E) ->
|
||||
expand_each_spec(_Meta, [], Map, E, _OriginalE) ->
|
||||
{Map, E}.
|
||||
|
||||
unpack_specs({'-', _, [H, T]}, Acc) ->
|
||||
unpack_specs(H, unpack_specs(T, Acc));
|
||||
unpack_specs({'*', _, [{'_', _, Atom}, Unit]}, Acc) when is_atom(Atom) and is_integer(Unit) ->
|
||||
unpack_specs({'*', _, [{'_', _, Atom}, Unit]}, Acc) when is_atom(Atom) ->
|
||||
[{unit, [], [Unit]} | Acc];
|
||||
unpack_specs({'*', _, [Size, Unit]}, Acc) when is_integer(Size) and is_integer(Unit) ->
|
||||
unpack_specs({'*', _, [Size, Unit]}, Acc) ->
|
||||
[{size, [], [Size]}, {unit, [], [Unit]} | Acc];
|
||||
unpack_specs(Size, Acc) when is_integer(Size) ->
|
||||
[{size, [], [Size]} | Acc];
|
||||
@@ -250,17 +251,37 @@ validate_spec(_, _) -> none.
|
||||
expand_spec_arg(Expr, E) when is_atom(Expr); is_integer(Expr) -> {Expr, E};
|
||||
expand_spec_arg(Expr, E) -> elixir_expand:expand(Expr, E).
|
||||
|
||||
validate_spec_arg(Meta, size, Value, E) ->
|
||||
validate_spec_arg(Meta, size, Value, E, OriginalE) ->
|
||||
case Value of
|
||||
{Var, _, Context} when is_atom(Var) and is_atom(Context) -> ok;
|
||||
_ when is_integer(Value) -> ok;
|
||||
_ -> form_error(Meta, ?key(E, file), ?MODULE, {bad_size_argument, Value})
|
||||
{Var, VarMeta, Context} when is_atom(Var) and is_atom(Context) ->
|
||||
Tuple = {Var, elixir_utils:var_context(VarMeta, Context)},
|
||||
|
||||
case is_valid_spec_arg_var(Tuple, E, OriginalE) of
|
||||
true -> ok;
|
||||
false -> form_error(Meta, ?key(E, file), ?MODULE, {undefined_var_in_spec, Value})
|
||||
end;
|
||||
|
||||
_ when is_integer(Value) ->
|
||||
ok;
|
||||
|
||||
_ ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {bad_size_argument, Value})
|
||||
end;
|
||||
validate_spec_arg(Meta, unit, Value, E) when not is_integer(Value) ->
|
||||
validate_spec_arg(Meta, unit, Value, E, _OriginalE) when not is_integer(Value) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {bad_unit_argument, Value});
|
||||
validate_spec_arg(_Meta, _Key, _Value, _E) ->
|
||||
validate_spec_arg(_Meta, _Key, _Value, _E, _OriginalE) ->
|
||||
ok.
|
||||
|
||||
is_valid_spec_arg_var(Var, E, #{context := match} = OriginalE) ->
|
||||
case ?key(OriginalE, prematch_vars) of
|
||||
#{Var := _} ->
|
||||
true;
|
||||
_ ->
|
||||
maps:is_key(Var, ?key(E, current_vars)) andalso
|
||||
not maps:is_key(Var, ?key(OriginalE, current_vars))
|
||||
end;
|
||||
is_valid_spec_arg_var(_Var, _E, _OriginalE) -> true.
|
||||
|
||||
validate_size_required(Meta, true, default, Type, default, E) when Type == binary; Type == bitstring ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, unsized_binary);
|
||||
validate_size_required(_, _, _, _, _, _) ->
|
||||
@@ -331,7 +352,7 @@ format_error({unaligned_bitstring_in_match, Expr}) ->
|
||||
Message =
|
||||
"cannot verify size of binary expression in match. "
|
||||
"If you are concatenating two binaries or nesting a binary inside a bitstring, "
|
||||
"you need to make sure the size of all fieds in the binary expression are known. "
|
||||
"you need to make sure the size of all fields in the binary expression are known. "
|
||||
"The following examples are invalid:\n\n"
|
||||
" \"foo\" <> <<field, rest::bits>>\n"
|
||||
" <<\"foo\", <<field, rest::bitstring>>::binary>>\n\n"
|
||||
@@ -374,4 +395,10 @@ format_error({nested_match, Expr}) ->
|
||||
Message =
|
||||
"cannot pattern match inside a bitstring "
|
||||
"that is already in match, got: ~ts",
|
||||
io_lib:format(Message, ['Elixir.Macro':to_string(Expr)]).
|
||||
io_lib:format(Message, ['Elixir.Macro':to_string(Expr)]);
|
||||
format_error({undefined_var_in_spec, Var}) ->
|
||||
Message =
|
||||
"undefined variable \"~ts\" in bitstring segment. If the size of the binary is a "
|
||||
"variable, the variable must be defined prior to its use in the binary/bitstring match "
|
||||
"itself, or outside the pattern match",
|
||||
io_lib:format(Message, ['Elixir.Macro':to_string(Var)]).
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
'MACRO-defmacrop'(Caller, Call, Expr) -> define(Caller, defmacrop, Call, Expr).
|
||||
|
||||
'MACRO-defmodule'(_Caller, Alias, [{do, Block}]) ->
|
||||
{Escaped, _} = elixir_quote:escape(Block, false),
|
||||
Escaped = elixir_quote:escape(Block, default, false),
|
||||
Args = [Alias, Escaped, [], env()],
|
||||
{{'.', [], [elixir_module, compile]}, [], Args}.
|
||||
|
||||
@@ -36,8 +36,10 @@
|
||||
{defp, 2}].
|
||||
|
||||
define({Line, E}, Kind, Call, Expr) ->
|
||||
{EscapedCall, UC} = elixir_quote:escape(Call, true),
|
||||
{EscapedExpr, UE} = elixir_quote:escape(Expr, true),
|
||||
UC = elixir_quote:has_unquotes(Call),
|
||||
UE = elixir_quote:has_unquotes(Expr),
|
||||
EscapedCall = elixir_quote:escape(Call, default, true),
|
||||
EscapedExpr = elixir_quote:escape(Expr, default, true),
|
||||
Args = [Kind, not(UC or UE), EscapedCall, EscapedExpr, elixir_locals:cache_env(E#{line := Line})],
|
||||
{{'.', [], [elixir_def, store_definition]}, [], Args}.
|
||||
|
||||
|
||||
@@ -185,10 +185,17 @@ expand_with_else(Meta, Opts, E, HasMatch) ->
|
||||
'try'(Meta, [], E) ->
|
||||
form_error(Meta, ?key(E, file), elixir_expand, {missing_option, 'try', [do]});
|
||||
'try'(Meta, [{do, _}], E) ->
|
||||
form_error(Meta, ?key(E, file), elixir_expand, {missing_option, 'try', ['catch', 'rescue', 'after', 'else']});
|
||||
form_error(Meta, ?key(E, file), elixir_expand, {missing_option, 'try', ['catch', 'rescue', 'after']});
|
||||
'try'(Meta, Opts, E) when not is_list(Opts) ->
|
||||
form_error(Meta, ?key(E, file), elixir_expand, {invalid_args, 'try'});
|
||||
'try'(Meta, Opts, E) ->
|
||||
% TODO: Make this an error in Elixir 2.0
|
||||
case Opts of
|
||||
[{do, _}, {else, _}] ->
|
||||
form_warn(Meta, ?key(E, file), ?MODULE, {try_with_only_else_clause, origin(Meta, 'try')});
|
||||
_ ->
|
||||
ok
|
||||
end,
|
||||
RaiseError = fun(Key) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {duplicated_clauses, 'try', Key})
|
||||
end,
|
||||
@@ -227,7 +234,8 @@ expand_catch(_Meta, [_] = Args, E) ->
|
||||
expand_catch(_Meta, [_, _] = Args, E) ->
|
||||
head(Args, E);
|
||||
expand_catch(Meta, _, E) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {wrong_number_of_args_for_clause, "one or two args", 'try', 'catch'}).
|
||||
Error = {wrong_number_of_args_for_clause, "one or two args", origin(Meta, 'try'), 'catch'},
|
||||
form_error(Meta, ?key(E, file), ?MODULE, Error).
|
||||
|
||||
expand_rescue(Meta, [Arg], E) ->
|
||||
case expand_rescue(Arg, E) of
|
||||
@@ -237,7 +245,8 @@ expand_rescue(Meta, [Arg], E) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, invalid_rescue_clause)
|
||||
end;
|
||||
expand_rescue(Meta, _, E) ->
|
||||
form_error(Meta, ?key(E, file), ?MODULE, {wrong_number_of_args_for_clause, "one arg", 'try', 'rescue'}).
|
||||
Error = {wrong_number_of_args_for_clause, "one arg", origin(Meta, 'try'), 'rescue'},
|
||||
form_error(Meta, ?key(E, file), ?MODULE, Error).
|
||||
|
||||
%% rescue var
|
||||
expand_rescue({Name, _, Atom} = Var, E) when is_atom(Name), is_atom(Atom) ->
|
||||
@@ -286,11 +295,7 @@ expand_one(Meta, Kind, Key, Fun) ->
|
||||
|
||||
%% Expands all -> pairs in a given key but do not keep the overall vars.
|
||||
expand_clauses(Meta, Kind, Fun, Clauses, E) ->
|
||||
NewKind =
|
||||
case lists:keyfind(origin, 1, Meta) of
|
||||
{origin, Origin} -> Origin;
|
||||
_ -> Kind
|
||||
end,
|
||||
NewKind = origin(Meta, Kind),
|
||||
expand_clauses_origin(Meta, NewKind, Fun, Clauses, E).
|
||||
|
||||
expand_clauses_origin(Meta, Kind, Fun, {Key, Clauses}, E) when is_list(Clauses) ->
|
||||
@@ -314,12 +319,18 @@ assert_at_most_once(Kind, [_ | Rest], Count, Fun) ->
|
||||
warn_catch_before_rescue([], _, _, _) ->
|
||||
ok;
|
||||
warn_catch_before_rescue([{'rescue', _} | _], Meta, E, true) ->
|
||||
form_warn(Meta, ?key(E, file), ?MODULE, catch_before_rescue);
|
||||
form_warn(Meta, ?key(E, file), ?MODULE, {catch_before_rescue, origin(Meta, 'try')});
|
||||
warn_catch_before_rescue([{'catch', _} | Rest], Meta, E, _) ->
|
||||
warn_catch_before_rescue(Rest, Meta, E, true);
|
||||
warn_catch_before_rescue([_ | Rest], Meta, E, Found) ->
|
||||
warn_catch_before_rescue(Rest, Meta, E, Found).
|
||||
|
||||
origin(Meta, Default) ->
|
||||
case lists:keyfind(origin, 1, Meta) of
|
||||
{origin, Origin} -> Origin;
|
||||
false -> Default
|
||||
end.
|
||||
|
||||
format_error({bad_or_missing_clauses, {Kind, Key}}) ->
|
||||
io_lib:format("expected -> clauses for :~ts in \"~ts\"", [Key, Kind]);
|
||||
format_error({bad_or_missing_clauses, Kind}) ->
|
||||
@@ -341,8 +352,12 @@ format_error(invalid_rescue_clause) ->
|
||||
"invalid \"rescue\" clause. The clause should match on an alias, a variable "
|
||||
"or be in the \"var in [alias]\" format";
|
||||
|
||||
format_error(catch_before_rescue) ->
|
||||
"\"catch\" should always come after \"rescue\" in try";
|
||||
format_error({catch_before_rescue, Origin}) ->
|
||||
io_lib:format("\"catch\" should always come after \"rescue\" in ~ts", [Origin]);
|
||||
|
||||
format_error({try_with_only_else_clause, Origin}) ->
|
||||
io_lib:format("\"else\" shouldn't be used as the only clause in \"~ts\", use \"case\" instead",
|
||||
[Origin]);
|
||||
|
||||
format_error(unmatchable_else_in_with) ->
|
||||
"\"else\" clauses will never match because all patterns in \"with\" will always match";
|
||||
|
||||
@@ -52,20 +52,28 @@ eval_forms(Forms, Vars, E) ->
|
||||
compile(Forms, Vars, E)
|
||||
end.
|
||||
|
||||
compile(Forms, Vars, #{line := Line, file := File} = E) ->
|
||||
compile(Quoted, Vars, E) ->
|
||||
Args = list_to_tuple([V || {_, _, _, V} <- Vars]),
|
||||
{Expanded, EE} = elixir_expand:expand(Quoted, E),
|
||||
elixir_env:check_unused_vars(EE),
|
||||
|
||||
{Module, Fun, Purgeable} =
|
||||
elixir_erl_compiler:spawn(fun spawned_compile/3, [Expanded, Vars, E]),
|
||||
|
||||
{dispatch(Module, Fun, Args, Purgeable), EE}.
|
||||
|
||||
spawned_compile(ExExprs, Vars, #{line := Line, file := File} = E) ->
|
||||
Dict = [{{Name, Kind}, {0, Value}} || {Name, Kind, Value, _} <- Vars],
|
||||
S = elixir_env:env_to_scope_with_vars(E, Dict),
|
||||
{Expr, EE, _S} = elixir:quoted_to_erl(Forms, E, S),
|
||||
elixir_env:check_unused_vars(EE),
|
||||
{ErlExprs, _} = elixir_erl_pass:translate(ExExprs, S),
|
||||
|
||||
Module = retrieve_compiler_module(),
|
||||
Fun = code_fun(?key(E, module)),
|
||||
Form = code_mod(Fun, Expr, Line, File, Module, Vars),
|
||||
Args = list_to_tuple([V || {_, _, _, V} <- Vars]),
|
||||
Forms = code_mod(Fun, ErlExprs, Line, File, Module, Vars),
|
||||
|
||||
{Module, Binary} = elixir_erl_compiler:noenv_forms(Form, File, [nowarn_nomatch]),
|
||||
{Module, Binary} = elixir_erl_compiler:noenv_forms(Forms, File, [nowarn_nomatch]),
|
||||
code:load_binary(Module, "", Binary),
|
||||
{dispatch(Module, Fun, Args, is_purgeable(Module, Binary)), EE}.
|
||||
{Module, Fun, is_purgeable(Module, Binary)}.
|
||||
|
||||
dispatch(Module, Fun, Args, Purgeable) ->
|
||||
Res = Module:Fun(Args),
|
||||
@@ -123,8 +131,8 @@ bootstrap_file(File) ->
|
||||
_ = [binary_to_path(X, "lib/elixir/ebin") || X <- Lists],
|
||||
io:format("Compiled ~ts~n", [File])
|
||||
catch
|
||||
Kind:Reason ->
|
||||
io:format("~p: ~p~nstacktrace: ~p~n", [Kind, Reason, erlang:get_stacktrace()]),
|
||||
?WITH_STACKTRACE(Kind, Reason, Stacktrace)
|
||||
io:format("~p: ~p~nstacktrace: ~p~n", [Kind, Reason, Stacktrace]),
|
||||
erlang:halt(1)
|
||||
end.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
-module(elixir_config).
|
||||
-compile({no_auto_import, [get/1]}).
|
||||
-export([new/1, delete/1, put/2, get/1, safe_get/2, update/2, get_and_put/2]).
|
||||
-export([new/1, delete/1, put/2, get/1, get/2, update/2, get_and_put/2, warn/2]).
|
||||
-export([start_link/0, init/1, handle_call/3, handle_cast/2,
|
||||
handle_info/2, code_change/3, terminate/2]).
|
||||
-behaviour(gen_server).
|
||||
@@ -22,7 +22,7 @@ get(Key) ->
|
||||
[{_, Value}] = ets:lookup(?MODULE, Key),
|
||||
Value.
|
||||
|
||||
safe_get(Key, Default) ->
|
||||
get(Key, Default) ->
|
||||
try ets:lookup(?MODULE, Key) of
|
||||
[{_, Value}] -> Value;
|
||||
[] -> Default
|
||||
@@ -39,6 +39,17 @@ get_and_put(Key, Value) ->
|
||||
start_link() ->
|
||||
gen_server:start_link({local, ?MODULE}, ?MODULE, ?MODULE, []).
|
||||
|
||||
%% Used to guarantee warnings are emitted only once per caller.
|
||||
warn(Key, [{Mod, Fun, ArgsOrArity, _} | _]) ->
|
||||
EtsKey = {warn, Key, Mod, Fun, to_arity(ArgsOrArity)},
|
||||
ets:update_counter(?MODULE, EtsKey, {2, 1, 1, 1}, {EtsKey, -1}) =:= 0;
|
||||
|
||||
warn(_, _) ->
|
||||
true.
|
||||
|
||||
to_arity(Args) when is_list(Args) -> length(Args);
|
||||
to_arity(Arity) -> Arity.
|
||||
|
||||
%% gen_server api
|
||||
|
||||
init(Tab) ->
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user