Compare commits
703 Commits
mark-swift
...
main
Author | SHA1 | Date |
---|---|---|
![]() |
3ec9bc85bc | |
![]() |
f5ea2492dc | |
![]() |
b89e43a799 | |
![]() |
c8cd311615 | |
![]() |
ba42a6aa36 | |
![]() |
83ab977a1b | |
![]() |
f12b8d66d3 | |
![]() |
e29de7a99f | |
![]() |
d32bf2b879 | |
![]() |
e5cf99088b | |
![]() |
7462187191 | |
![]() |
23326fc433 | |
![]() |
156f6aabc8 | |
![]() |
43190834c5 | |
![]() |
f1d5a55658 | |
![]() |
c735e6320f | |
![]() |
2f9997e2cc | |
![]() |
8f3eea06d3 | |
![]() |
a53a1f052b | |
![]() |
704c9ae116 | |
![]() |
521df18fdb | |
![]() |
a2ba0a0626 | |
![]() |
1094a3b70e | |
![]() |
754127924f | |
![]() |
3f039f26d5 | |
![]() |
671589b1d4 | |
![]() |
d938b2d3c3 | |
![]() |
7fd22e0d6e | |
![]() |
07740506b5 | |
![]() |
26d06bcebb | |
![]() |
fe312a06fe | |
![]() |
d73970e9d7 | |
![]() |
c0ea9d1925 | |
![]() |
405113f793 | |
![]() |
f4987071f0 | |
![]() |
306dec0fcc | |
![]() |
4d4a330d46 | |
![]() |
1e73835e83 | |
![]() |
866001db2f | |
![]() |
34f5ffa7f7 | |
![]() |
1b1b19a902 | |
![]() |
15a18fd4e8 | |
![]() |
5802fd99b1 | |
![]() |
e7bf813f15 | |
![]() |
3cf9585b2e | |
![]() |
8827fca693 | |
![]() |
9f7c57b719 | |
![]() |
73acbaf6d5 | |
![]() |
5616d858bc | |
![]() |
6cdb0aa689 | |
![]() |
7483e61615 | |
![]() |
87e230ce87 | |
![]() |
7f3b93147a | |
![]() |
7501d44b69 | |
![]() |
0ffe0c5911 | |
![]() |
c99a4286b8 | |
![]() |
8d5700afca | |
![]() |
1fa8e484c4 | |
![]() |
9e15e37255 | |
![]() |
97259e24d0 | |
![]() |
eb6d50a04c | |
![]() |
9c1678968f | |
![]() |
fa32fbc4f0 | |
![]() |
8822d40687 | |
![]() |
c0cf1bf5c9 | |
![]() |
444653bfd5 | |
![]() |
9138213121 | |
![]() |
6fd5f98d38 | |
![]() |
bc18ff14e3 | |
![]() |
5e15039554 | |
![]() |
7756793356 | |
![]() |
f0138ea1df | |
![]() |
6a2e973de3 | |
![]() |
e86c06c390 | |
![]() |
6b094dd711 | |
![]() |
9054ec0658 | |
![]() |
71b89e66de | |
![]() |
a7bc9e20c7 | |
![]() |
eaf34d7204 | |
![]() |
86d60400c1 | |
![]() |
740572f049 | |
![]() |
3541ef4d02 | |
![]() |
39a05f2c35 | |
![]() |
711d92e26f | |
![]() |
d8dfc3c937 | |
![]() |
3a2bb15ca3 | |
![]() |
a7e3909c6a | |
![]() |
72c2a5488d | |
![]() |
ea56405983 | |
![]() |
9c414932d8 | |
![]() |
8a21549ca9 | |
![]() |
4abcf5f0dd | |
![]() |
b2a4c9fcb9 | |
![]() |
603fff9a82 | |
![]() |
2544dc79d3 | |
![]() |
ea6b3b4d64 | |
![]() |
172b8b8a94 | |
![]() |
4c04cdafa7 | |
![]() |
165172e0fa | |
![]() |
3f52acd0a2 | |
![]() |
e14a73438f | |
![]() |
817de197d5 | |
![]() |
214a749ace | |
![]() |
fd4f9afb08 | |
![]() |
c241935635 | |
![]() |
46ff727a13 | |
![]() |
dc89109622 | |
![]() |
9c2525139a | |
![]() |
d601917e40 | |
![]() |
498b4c8fbe | |
![]() |
69fadb6918 | |
![]() |
f866ec32b1 | |
![]() |
6d51459323 | |
![]() |
21dc766c93 | |
![]() |
0f802f766a | |
![]() |
fbbccf9db8 | |
![]() |
8b72eb0406 | |
![]() |
c22d60fac0 | |
![]() |
1892c846b0 | |
![]() |
41290a23d3 | |
![]() |
5814ec1a1a | |
![]() |
f9b0e9f0af | |
![]() |
3ef44cf742 | |
![]() |
5aed7ce95c | |
![]() |
97fd216455 | |
![]() |
f127ba14dd | |
![]() |
74b82daba0 | |
![]() |
8c617d7412 | |
![]() |
a4f4680442 | |
![]() |
62b2914271 | |
![]() |
1b0f37c6f6 | |
![]() |
5226725689 | |
![]() |
e361e14c90 | |
![]() |
70a56a1420 | |
![]() |
409f117da9 | |
![]() |
7fe7bb28d9 | |
![]() |
bb11e6a0a7 | |
![]() |
eee97a7b2b | |
![]() |
cf1e2e27dc | |
![]() |
a2facce70c | |
![]() |
bd444fcd77 | |
![]() |
ee849bcb10 | |
![]() |
6d4bc78cb4 | |
![]() |
16e2bb0f18 | |
![]() |
b0cbb440c3 | |
![]() |
58a07eb452 | |
![]() |
82491e6f84 | |
![]() |
3d15419adb | |
![]() |
6a09af169e | |
![]() |
7dad240ea7 | |
![]() |
ca43d2359b | |
![]() |
da27f1c7fd | |
![]() |
eb85125a5f | |
![]() |
62b9c2de7a | |
![]() |
aeee6325af | |
![]() |
5a91b1e392 | |
![]() |
efc5afd5d5 | |
![]() |
f2d15355be | |
![]() |
a840058cf5 | |
![]() |
358bdc89a5 | |
![]() |
a81a532091 | |
![]() |
6983c813c8 | |
![]() |
fb89ab2fb5 | |
![]() |
7ac128c83d | |
![]() |
06578e5d91 | |
![]() |
1940e0e2d2 | |
![]() |
bd77cbcf6e | |
![]() |
1bf2f25e40 | |
![]() |
7d7bee5eee | |
![]() |
31510b662e | |
![]() |
0bd8a7aba6 | |
![]() |
084ad9dfd4 | |
![]() |
228d53787b | |
![]() |
4fee8e6a0c | |
![]() |
4f9a608cf4 | |
![]() |
1c3c62e422 | |
![]() |
d6e3bbb64d | |
![]() |
128f37a6b8 | |
![]() |
cfd9a26e33 | |
![]() |
a71f588637 | |
![]() |
d73d87ac97 | |
![]() |
04791929a7 | |
![]() |
c9b1b961f5 | |
![]() |
613e916c39 | |
![]() |
e2f3f3ad45 | |
![]() |
5c94a43352 | |
![]() |
183c0aa784 | |
![]() |
ed6793f8f1 | |
![]() |
1790ad56dd | |
![]() |
2f0e537f9b | |
![]() |
393318d903 | |
![]() |
f3e5557de9 | |
![]() |
352ffdfc57 | |
![]() |
6a9e6776a9 | |
![]() |
ec38c244fd | |
![]() |
ad29864d7f | |
![]() |
b9e5cfb202 | |
![]() |
9c216baf20 | |
![]() |
7eb479d546 | |
![]() |
aafc574e90 | |
![]() |
5af4291b53 | |
![]() |
d3ebfc5567 | |
![]() |
60d0dd8a05 | |
![]() |
0163ffd328 | |
![]() |
eb5712582f | |
![]() |
6ea0397620 | |
![]() |
aba0f63704 | |
![]() |
993f34a96c | |
![]() |
eaacd9873e | |
![]() |
843198d241 | |
![]() |
325d0ee1e4 | |
![]() |
5eed8fe91b | |
![]() |
60610cef84 | |
![]() |
ca09bc5a22 | |
![]() |
0796236031 | |
![]() |
651b00eb70 | |
![]() |
500f143c7d | |
![]() |
81f1dbfd1b | |
![]() |
0750d5d465 | |
![]() |
84c6d200b6 | |
![]() |
9ac13f078a | |
![]() |
c84124d8bc | |
![]() |
3907772163 | |
![]() |
d98fd5386a | |
![]() |
36c24c822c | |
![]() |
e1fdf17d1b | |
![]() |
23e4db3e5f | |
![]() |
b4641e7e60 | |
![]() |
341db66f3c | |
![]() |
c9791783ba | |
![]() |
dc228d57ac | |
![]() |
fbd9f16955 | |
![]() |
d120f41181 | |
![]() |
db6aea5d07 | |
![]() |
876d8fc872 | |
![]() |
45c5f06754 | |
![]() |
040096a641 | |
![]() |
f91a2d5310 | |
![]() |
f8f2317bdb | |
![]() |
82249f5ed4 | |
![]() |
78c9ad6f33 | |
![]() |
693e504258 | |
![]() |
b66dd13e2f | |
![]() |
5ec6112ba1 | |
![]() |
74dbd52add | |
![]() |
cc44c989b7 | |
![]() |
e64e82d80d | |
![]() |
ea8b17dd9c | |
![]() |
672e19651f | |
![]() |
67eb330f1c | |
![]() |
e6d4ad653c | |
![]() |
100b3eec2a | |
![]() |
bcfc2c4b6c | |
![]() |
68dc0f58d2 | |
![]() |
d6ff2a7f37 | |
![]() |
64d9619a8a | |
![]() |
470d471e51 | |
![]() |
5ff40867b3 | |
![]() |
58611e6718 | |
![]() |
c740da48d5 | |
![]() |
eda0d92f44 | |
![]() |
d76daf5f62 | |
![]() |
1a39194f65 | |
![]() |
0e53e19cb1 | |
![]() |
3cba460f9a | |
![]() |
d3928cb8e8 | |
![]() |
a6c3cec8c9 | |
![]() |
7bd8362dae | |
![]() |
e1cddb710d | |
![]() |
4a6387da67 | |
![]() |
83ee9a89dd | |
![]() |
540003e2a1 | |
![]() |
3745704c03 | |
![]() |
33fa42becb | |
![]() |
25c3fb161d | |
![]() |
53ee4a955d | |
![]() |
40fb3796cb | |
![]() |
a876e860ee | |
![]() |
4c406459bd | |
![]() |
4ddeb22b6d | |
![]() |
ff06e0ed00 | |
![]() |
6734a64554 | |
![]() |
73a64d674c | |
![]() |
7f8eb9de77 | |
![]() |
609418f702 | |
![]() |
4adabd8e4b | |
![]() |
93d0d8fa7f | |
![]() |
4dfef014ab | |
![]() |
95d56e4130 | |
![]() |
7f9dd69c62 | |
![]() |
ac44fe23b6 | |
![]() |
60128ab196 | |
![]() |
7a8b2d1dab | |
![]() |
92304cdd98 | |
![]() |
ab143685a4 | |
![]() |
9cb1069090 | |
![]() |
e405d3d583 | |
![]() |
97ba82d740 | |
![]() |
d8d5e5bb43 | |
![]() |
28a4aa2195 | |
![]() |
28e2a1b022 | |
![]() |
c1c5e5f722 | |
![]() |
60ad710b7f | |
![]() |
5a7d3ade02 | |
![]() |
12c8bb369e | |
![]() |
f088bbde15 | |
![]() |
e9c1128b86 | |
![]() |
4ccf9eebb4 | |
![]() |
f6de471b5f | |
![]() |
0f68a0a0cb | |
![]() |
ac21584224 | |
![]() |
907c80f84c | |
![]() |
fd502b4526 | |
![]() |
a6c4ea9614 | |
![]() |
571ad33ceb | |
![]() |
6af9175386 | |
![]() |
fe4ec3521e | |
![]() |
1dbde3d9c3 | |
![]() |
cc49e82348 | |
![]() |
4408250920 | |
![]() |
85e59c706a | |
![]() |
cdd891a4a2 | |
![]() |
e5b1944ae6 | |
![]() |
cd291b043a | |
![]() |
8cdbb50cbf | |
![]() |
ba8899714d | |
![]() |
4f652a68e7 | |
![]() |
953ee620f7 | |
![]() |
18f9a0e3a6 | |
![]() |
0362cd07b8 | |
![]() |
9d2ec3dc8d | |
![]() |
04d1184904 | |
![]() |
4bd7da32ea | |
![]() |
901f05cd4f | |
![]() |
ca0813c605 | |
![]() |
ac7833aaf4 | |
![]() |
5fceb213d9 | |
![]() |
2928dab4ec | |
![]() |
0c828e35fb | |
![]() |
3864ecc12f | |
![]() |
fe141cd3b6 | |
![]() |
eaf7db1250 | |
![]() |
6c7e2107ae | |
![]() |
1edef5ebdc | |
![]() |
7e8a3ae2ac | |
![]() |
45ac3dcdff | |
![]() |
1c675bc993 | |
![]() |
fc0c0c7f5b | |
![]() |
22522254df | |
![]() |
9a706ba371 | |
![]() |
d4ea19e434 | |
![]() |
eb3d502ad7 | |
![]() |
65874dc40f | |
![]() |
759408fdb5 | |
![]() |
ec5124d939 | |
![]() |
05e06d1945 | |
![]() |
6fcdd8077f | |
![]() |
32152646f3 | |
![]() |
e97119efec | |
![]() |
fce8283843 | |
![]() |
f1f6a3c4a0 | |
![]() |
c56e19a0c2 | |
![]() |
3800ad32bf | |
![]() |
79e3c8bd4a | |
![]() |
6ad4a704f5 | |
![]() |
20bfe264f5 | |
![]() |
697eaa73dd | |
![]() |
5144cccb57 | |
![]() |
98e9c2f1f4 | |
![]() |
63c043664d | |
![]() |
a18436d4d6 | |
![]() |
a5c44605af | |
![]() |
b7f621c239 | |
![]() |
d551cb8c16 | |
![]() |
1b59a3f168 | |
![]() |
6b5352feac | |
![]() |
9a305dd2e6 | |
![]() |
7738f0c0a5 | |
![]() |
374130bb56 | |
![]() |
d37465ad37 | |
![]() |
50c85ef5c1 | |
![]() |
fa6db3cca7 | |
![]() |
96925d480e | |
![]() |
31ea58381c | |
![]() |
95838aa230 | |
![]() |
f8d505a225 | |
![]() |
7a8de1c966 | |
![]() |
7a3d0d55a0 | |
![]() |
1c6b6c67e0 | |
![]() |
87bebb6744 | |
![]() |
7f5b189c1f | |
![]() |
c1f2b615e2 | |
![]() |
5d1906456b | |
![]() |
53752f58ad | |
![]() |
c98ffcc940 | |
![]() |
351c8be2e0 | |
![]() |
cb79584c7d | |
![]() |
def404259f | |
![]() |
de7996f5c7 | |
![]() |
b4f45aa55e | |
![]() |
f0f46a45eb | |
![]() |
1ee5154687 | |
![]() |
401d0f7929 | |
![]() |
25a04e8eeb | |
![]() |
0bd9e4e65f | |
![]() |
60054da0f7 | |
![]() |
35fcf55198 | |
![]() |
cee4af098f | |
![]() |
9c8708bc01 | |
![]() |
7b1099a33d | |
![]() |
359699cea7 | |
![]() |
4589161742 | |
![]() |
5af8e3dd68 | |
![]() |
1fb04902c0 | |
![]() |
0dfc7a85b5 | |
![]() |
a4fbec355c | |
![]() |
8f3a23e1a9 | |
![]() |
ead4ca9b56 | |
![]() |
9f4b2c37ba | |
![]() |
f509998ec1 | |
![]() |
2d76e43068 | |
![]() |
e84430f222 | |
![]() |
469a3aa87a | |
![]() |
59ad84f6e9 | |
![]() |
fd722892e5 | |
![]() |
c46fd55711 | |
![]() |
2929e35183 | |
![]() |
533917dced | |
![]() |
25c9d34f5a | |
![]() |
d11dc2b321 | |
![]() |
62c8985a3e | |
![]() |
230688848e | |
![]() |
eb8971a933 | |
![]() |
016831d471 | |
![]() |
93b016bca3 | |
![]() |
bf716d7089 | |
![]() |
d3274565a1 | |
![]() |
04d7ce05ca | |
![]() |
bda8487ed2 | |
![]() |
a8bc9e9b42 | |
![]() |
286e59a0e6 | |
![]() |
db910946dc | |
![]() |
1837ae59cb | |
![]() |
03848ce583 | |
![]() |
e9f2248072 | |
![]() |
9a9629c1e8 | |
![]() |
1b86aa7eeb | |
![]() |
8ec6e0eefc | |
![]() |
937228d1ba | |
![]() |
0504d2c3f9 | |
![]() |
07be57027a | |
![]() |
844b7c02dd | |
![]() |
b4ec2d360d | |
![]() |
89c227ecaa | |
![]() |
6f4b75b0f6 | |
![]() |
4522005ab4 | |
![]() |
56a23448c3 | |
![]() |
bb1de21059 | |
![]() |
89c24cd52d | |
![]() |
0fbd03cf2b | |
![]() |
8b96aa0585 | |
![]() |
7ff3094821 | |
![]() |
f8e5339c69 | |
![]() |
9959f971f9 | |
![]() |
dcf03f5987 | |
![]() |
860b027005 | |
![]() |
4aa9588454 | |
![]() |
37bf2c9168 | |
![]() |
bd8c9e5bcb | |
![]() |
510cb39b11 | |
![]() |
c9ef157c29 | |
![]() |
e74e11533c | |
![]() |
a7ff8a8d76 | |
![]() |
7585aef910 | |
![]() |
f04e28cbf8 | |
![]() |
39bb05f7d1 | |
![]() |
7624059caa | |
![]() |
fa6bf50a22 | |
![]() |
5c3d4c1dab | |
![]() |
02b5a034d2 | |
![]() |
48fde2321f | |
![]() |
8d29b21ecb | |
![]() |
3bae16bee5 | |
![]() |
33f6ee1f36 | |
![]() |
de0b91cd5a | |
![]() |
4e3c750086 | |
![]() |
2f300502c0 | |
![]() |
9db88947b9 | |
![]() |
99436906cd | |
![]() |
7653b2d635 | |
![]() |
b4e01ba1b4 | |
![]() |
b9653e3e1b | |
![]() |
9aaeff67d0 | |
![]() |
1a7f03bbc5 | |
![]() |
b849234572 | |
![]() |
0282bf1923 | |
![]() |
4b04e528af | |
![]() |
602070164b | |
![]() |
87e9757af2 | |
![]() |
81ee297908 | |
![]() |
016c7b6abd | |
![]() |
6998d8af23 | |
![]() |
4da2ff1118 | |
![]() |
05d98b84cf | |
![]() |
ec05864880 | |
![]() |
b938a4e07d | |
![]() |
ca7510a394 | |
![]() |
04bd091810 | |
![]() |
82e916db15 | |
![]() |
957208c44b | |
![]() |
fe6a930bd4 | |
![]() |
8bcf8713e9 | |
![]() |
d913c8e63b | |
![]() |
b01e1504a1 | |
![]() |
3ac518ce69 | |
![]() |
0c06b7f65f | |
![]() |
1a76a882ca | |
![]() |
f34169575c | |
![]() |
9c53c94736 | |
![]() |
515587fb9f | |
![]() |
f174a55c94 | |
![]() |
c0a4dd1be7 | |
![]() |
1533e72fd4 | |
![]() |
549c71a27c | |
![]() |
367389a489 | |
![]() |
ef248f6529 | |
![]() |
a6c90dd942 | |
![]() |
2a95f1bde9 | |
![]() |
5ba9d60f8d | |
![]() |
8345545865 | |
![]() |
d6fd754679 | |
![]() |
a8d3813cc7 | |
![]() |
5ae1d98596 | |
![]() |
d3fd234883 | |
![]() |
503f8c506b | |
![]() |
8470b65ae9 | |
![]() |
4552facb7e | |
![]() |
c29e1673dd | |
![]() |
cfabd8ec99 | |
![]() |
91d4a42687 | |
![]() |
7af26f0f77 | |
![]() |
c087e79437 | |
![]() |
54ec0c9b28 | |
![]() |
3834e52ac4 | |
![]() |
5d9a72b2a5 | |
![]() |
af222a5754 | |
![]() |
54ccc39e72 | |
![]() |
8b578ebf36 | |
![]() |
2eb764d0c9 | |
![]() |
13c45a5c15 | |
![]() |
3fd1573c57 | |
![]() |
6d75645f67 | |
![]() |
8eec5e6997 | |
![]() |
44382ea397 | |
![]() |
41b8834a13 | |
![]() |
a40cc70478 | |
![]() |
1cbf3caae1 | |
![]() |
0f9705901b | |
![]() |
129a55fb74 | |
![]() |
c70510c3ea | |
![]() |
6bfecb8fcc | |
![]() |
db20dbb4a3 | |
![]() |
46649c8662 | |
![]() |
1662a38922 | |
![]() |
18ab68859c | |
![]() |
ab3f070222 | |
![]() |
e3f1b56129 | |
![]() |
26ca731cf0 | |
![]() |
8926596da0 | |
![]() |
647819eedc | |
![]() |
f37ea8acc4 | |
![]() |
ac91f7bfa0 | |
![]() |
462f741065 | |
![]() |
268415893d | |
![]() |
2388e49190 | |
![]() |
b2caef7202 | |
![]() |
2efd538d37 | |
![]() |
0fe3404494 | |
![]() |
da75cdca40 | |
![]() |
86f6023d13 | |
![]() |
afb46dc76d | |
![]() |
a40488feaf | |
![]() |
d2c638b5e4 | |
![]() |
86a176d4c6 | |
![]() |
73def99b49 | |
![]() |
fd7afedfcf | |
![]() |
c6eec8072c | |
![]() |
a4c46f624d | |
![]() |
734eceada0 | |
![]() |
4fb5ebe19b | |
![]() |
bb309de9df | |
![]() |
7be6f866fe | |
![]() |
0db26db975 | |
![]() |
f8a4276aba | |
![]() |
95ffaed655 | |
![]() |
7b1de2f9cd | |
![]() |
49665a9ec7 | |
![]() |
0ea26edd4f | |
![]() |
2efa085dd4 | |
![]() |
f3d367f667 | |
![]() |
345a904055 | |
![]() |
0808f2508b | |
![]() |
8d500d1a63 | |
![]() |
992cc9afe3 | |
![]() |
49ace1729f | |
![]() |
38e71f7a10 | |
![]() |
a9ec894caf | |
![]() |
9db303e3a3 | |
![]() |
4b1bb38fc3 | |
![]() |
623bc8ea73 | |
![]() |
baf5647e2b | |
![]() |
ea574bd640 | |
![]() |
837f46479f | |
![]() |
c6f3d0a6af | |
![]() |
8c5d3cbfc8 | |
![]() |
311a724c3c | |
![]() |
6b393b1b53 | |
![]() |
4234664671 | |
![]() |
8cd025112d | |
![]() |
efbe4d9f0f | |
![]() |
4a239a695e | |
![]() |
bc7792ecd6 | |
![]() |
958cc20a9f | |
![]() |
117ef7f0e2 | |
![]() |
0d03221281 | |
![]() |
80c8e5d37a | |
![]() |
9060d3f8e8 | |
![]() |
eb30be3826 | |
![]() |
2a8d536857 | |
![]() |
c34955ca64 | |
![]() |
e459c4ae9b | |
![]() |
75a6d14788 | |
![]() |
e2900c4a7e | |
![]() |
dd94d4ec53 | |
![]() |
1e7e0d6301 | |
![]() |
4b8a68072b | |
![]() |
26465f21ce | |
![]() |
b29c07e07e | |
![]() |
622d48bd0a | |
![]() |
b9e6a9aed8 | |
![]() |
6c0413077c | |
![]() |
772e5f5806 | |
![]() |
c7c4e0a1f3 | |
![]() |
ca2d3a874f | |
![]() |
79347a1728 | |
![]() |
c1650e6918 | |
![]() |
c26c40d31f | |
![]() |
93158a609e | |
![]() |
a3b70a0ffb | |
![]() |
e381a7d684 | |
![]() |
abad253310 | |
![]() |
57dc1c9532 | |
![]() |
d72877a34f | |
![]() |
ea41b9fd09 | |
![]() |
e0f23fa8e9 | |
![]() |
4bc6588f38 | |
![]() |
d14cf598fd | |
![]() |
9979c4fd27 | |
![]() |
f032c82b59 | |
![]() |
c8a66e7070 | |
![]() |
f32bc1f337 | |
![]() |
fc3b143973 | |
![]() |
4119c27857 | |
![]() |
a9e5a644bb | |
![]() |
501142d3e7 | |
![]() |
ea6ca3e8dd | |
![]() |
0fd9a112b4 | |
![]() |
eb14f5283c | |
![]() |
cd9bd5f9fd | |
![]() |
9875ab904b | |
![]() |
7412205b6c | |
![]() |
8dbc0e4cbf | |
![]() |
ccac242f3a | |
![]() |
dcb5bf438d | |
![]() |
fdcdcf76d1 | |
![]() |
05461c8525 | |
![]() |
848ec452c3 | |
![]() |
bf9bf83143 | |
![]() |
d9ec625601 | |
![]() |
ef36201e6b | |
![]() |
5a30991fa4 | |
![]() |
aebded15ba | |
![]() |
7dfadc205a | |
![]() |
9cfd3dc978 | |
![]() |
c73f68683a | |
![]() |
cf764e7b90 | |
![]() |
83bf37e642 | |
![]() |
7259c02ee5 | |
![]() |
68983d7da2 | |
![]() |
2960ae6a7a | |
![]() |
69f3a3b4b7 | |
![]() |
f3e2c0b7bb | |
![]() |
e8f738b39c | |
![]() |
6dc2ef937e | |
![]() |
0e3f3de17f | |
![]() |
dd55f59207 | |
![]() |
c1de2ef087 | |
![]() |
78949c1b99 | |
![]() |
1ef15f3bb7 | |
![]() |
3aa249b8a1 | |
![]() |
c2be5b18b4 | |
![]() |
f6fc4727b6 | |
![]() |
73c88c3af0 |
|
@ -0,0 +1 @@
|
|||
.build
|
14
.bazelrc
14
.bazelrc
|
@ -1 +1,15 @@
|
|||
common --enable_bzlmod
|
||||
|
||||
try-import %workspace%/ci.bazelrc
|
||||
try-import %workspace%/user.bazelrc
|
||||
|
||||
build --macos_minimum_os=12.0 --host_macos_minimum_os=12.0
|
||||
build --disk_cache=~/.bazel_cache
|
||||
build --experimental_remote_cache_compression
|
||||
build --experimental_remote_build_event_upload=minimal
|
||||
build --nolegacy_important_outputs
|
||||
build --swiftcopt=-warnings-as-errors
|
||||
|
||||
build:release \
|
||||
--compilation_mode=opt \
|
||||
--features=swift.opt_uses_wmo
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
6.2.0
|
|
@ -0,0 +1,3 @@
|
|||
fixedReleaser:
|
||||
login: jpsim
|
||||
email: jp@jpsim.com
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"homepage": "https://github.com/realm/SwiftLint",
|
||||
"maintainers": [
|
||||
{
|
||||
"email": "jp@jpsim.com",
|
||||
"github": "jpsim",
|
||||
"name": "JP Simard"
|
||||
}
|
||||
],
|
||||
"repository": [
|
||||
"github:realm/SwiftLint"
|
||||
],
|
||||
"versions": [],
|
||||
"yanked_versions": {}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
shell_commands: &shell_commands
|
||||
- "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME"
|
||||
- "mkdir $SWIFT_HOME"
|
||||
- "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME"
|
||||
|
||||
tasks:
|
||||
verify_targets_linux:
|
||||
name: Verify targets (Linux)
|
||||
platform: ubuntu2004
|
||||
environment:
|
||||
CC: "clang"
|
||||
SWIFT_VERSION: "5.7.2"
|
||||
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
|
||||
PATH: "$PATH:$SWIFT_HOME/usr/bin"
|
||||
shell_commands: *shell_commands
|
||||
build_flags:
|
||||
- "--action_env=PATH"
|
||||
build_targets:
|
||||
- '@SwiftLint//:swiftlint'
|
||||
verify_targets_macos:
|
||||
name: Verify targets (macOS)
|
||||
platform: macos
|
||||
build_targets:
|
||||
- '@SwiftLint//:swiftlint'
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"url": "https://github.com/realm/SwiftLint/releases/download/{TAG}/bazel.tar.gz",
|
||||
"integrity": "",
|
||||
"strip_prefix": ""
|
||||
}
|
|
@ -5,13 +5,25 @@ steps:
|
|||
- bazel build :swiftlint
|
||||
- echo "+++ Test"
|
||||
- bazel test --test_output=errors //Tests/...
|
||||
- label: "SwiftPM"
|
||||
commands:
|
||||
- echo "+++ Test"
|
||||
- swift test --parallel -Xswiftc -DDISABLE_FOCUSED_EXAMPLES
|
||||
- label: "Danger"
|
||||
commands:
|
||||
- echo "--- Install Bundler"
|
||||
- gem install bundler
|
||||
- echo "--- Bundle Install"
|
||||
- bundle install
|
||||
- echo "+++ Run Danger"
|
||||
- bundle exec danger --verbose
|
||||
- label: "Analyze"
|
||||
- label: "TSan Tests"
|
||||
commands:
|
||||
- echo "+++ Analyze"
|
||||
- make analyze
|
||||
- echo "+++ Test"
|
||||
- bazel test --test_output=errors --build_tests_only --features=tsan --test_timeout=1000 //Tests/...
|
||||
- label: "Sourcery"
|
||||
commands:
|
||||
- echo "+++ Run Sourcery"
|
||||
- make --always-make sourcery
|
||||
- echo "+++ Diff Files"
|
||||
- git diff --quiet HEAD
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
*
|
||||
!Plugins
|
||||
!Source
|
||||
!Tests
|
||||
!Package.*
|
||||
|
|
|
@ -3,16 +3,16 @@ name: docker
|
|||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- main
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Extract DOCKER_TAG using tag name
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## Build generated
|
||||
build/
|
||||
|
@ -22,6 +21,7 @@ xcuserdata
|
|||
*.moved-aside
|
||||
*.xcuserstate
|
||||
*.xcscmblueprint
|
||||
default.profraw
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
|
@ -44,6 +44,10 @@ benchmark_*
|
|||
osscheck/
|
||||
docs/
|
||||
rule_docs/
|
||||
bazel.tar.gz
|
||||
bazel.tar.gz.sha256
|
||||
ci.bazelrc
|
||||
user.bazelrc
|
||||
|
||||
# Swift Package Manager
|
||||
#
|
||||
|
|
11
.jazzy.yaml
11
.jazzy.yaml
|
@ -1,19 +1,20 @@
|
|||
module: SwiftLintFramework
|
||||
module: SwiftLintCore
|
||||
author: JP Simard, SwiftLint Contributors
|
||||
author_url: https://jpsim.com
|
||||
root_url: https://realm.github.io/SwiftLint/
|
||||
github_url: https://github.com/realm/SwiftLint
|
||||
github_file_prefix: https://github.com/realm/SwiftLint/tree/master
|
||||
github_file_prefix: https://github.com/realm/SwiftLint/tree/main
|
||||
swift_build_tool: spm
|
||||
theme: fullwidth
|
||||
clean: true
|
||||
copyright: '© 2020 [JP Simard](https://jpsim.com) under MIT.'
|
||||
copyright: '© 2023 [JP Simard](https://jpsim.com) under MIT.'
|
||||
|
||||
documentation: rule_docs/*.md
|
||||
hide_unlisted_documentation: true
|
||||
custom_categories_unlisted_prefix: ''
|
||||
exclude:
|
||||
- Source/SwiftLintFramework/Rules/**/*.swift
|
||||
# TODO: Document extensions
|
||||
- Source/SwiftLintCore/Extensions/*.swift
|
||||
custom_categories:
|
||||
- name: Rules
|
||||
children:
|
||||
|
@ -22,7 +23,7 @@ custom_categories:
|
|||
children:
|
||||
- CSVReporter
|
||||
- CheckstyleReporter
|
||||
- CodeclimateReporter
|
||||
- CodeClimateReporter
|
||||
- EmojiReporter
|
||||
- GitHubActionsLoggingReporter
|
||||
- HTMLReporter
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
|
||||
/// The rule list containing all available rules built into SwiftLint.
|
||||
public let primaryRuleList = RuleList(rules: [
|
||||
public let builtInRules: [Rule.Type] = [
|
||||
{% for rule in types.structs where rule.name|hasSuffix:"Rule" or rule.name|hasSuffix:"Rules" %} {{ rule.name }}.self{% if not forloop.last %},{% endif %}
|
||||
{% endfor %}] + extraRules())
|
||||
{% endfor %}]
|
|
@ -1,11 +1,14 @@
|
|||
import SwiftLintFramework
|
||||
import XCTest
|
||||
@testable import SwiftLintBuiltInRules
|
||||
@_spi(TestHelper)
|
||||
@testable import SwiftLintCore
|
||||
import SwiftLintTestHelpers
|
||||
|
||||
// swiftlint:disable:next blanket_disable_command
|
||||
// swiftlint:disable file_length single_test_class type_name
|
||||
|
||||
{% for rule in types.structs %}
|
||||
{% if rule.name|hasSuffix:"Rule" %}
|
||||
class {{ rule.name }}GeneratedTests: XCTestCase {
|
||||
class {{ rule.name }}GeneratedTests: SwiftLintTestCase {
|
||||
func testWithDefaultConfiguration() {
|
||||
verifyRule({{ rule.name }}.description)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
|
||||
/// The reporters list containing all the reporters built into SwiftLint.
|
||||
public let reportersList: [Reporter.Type] = [
|
||||
{% for reporter in types.structs where reporter.name|hasSuffix:"Reporter" %}
|
||||
{{ reporter.name }}.self{% if not forloop.last %},{% endif %}
|
||||
{% endfor %}
|
||||
]
|
135
.swiftlint.yml
135
.swiftlint.yml
|
@ -1,4 +1,5 @@
|
|||
included:
|
||||
- Plugins
|
||||
- Source
|
||||
- Tests
|
||||
excluded:
|
||||
|
@ -7,76 +8,55 @@ analyzer_rules:
|
|||
- unused_declaration
|
||||
- unused_import
|
||||
opt_in_rules:
|
||||
- all
|
||||
disabled_rules:
|
||||
- anonymous_argument_in_multiline_closure
|
||||
- anyobject_protocol
|
||||
- array_init
|
||||
- attributes
|
||||
- closure_end_indentation
|
||||
- closure_spacing
|
||||
- collection_alignment
|
||||
- contains_over_filter_count
|
||||
- contains_over_filter_is_empty
|
||||
- contains_over_first_not_nil
|
||||
- contains_over_range_nil_comparison
|
||||
- discouraged_none_name
|
||||
- discouraged_object_literal
|
||||
- empty_collection_literal
|
||||
- empty_count
|
||||
- empty_string
|
||||
- empty_xctest_method
|
||||
- enum_case_associated_values_count
|
||||
- explicit_init
|
||||
- extension_access_modifier
|
||||
- fallthrough
|
||||
- fatal_error_message
|
||||
- file_header
|
||||
- file_name
|
||||
- first_where
|
||||
- flatmap_over_map_reduce
|
||||
- identical_operands
|
||||
- joined_default_parameter
|
||||
- last_where
|
||||
- legacy_multiple
|
||||
- literal_expression_end_indentation
|
||||
- lower_acl_than_parent
|
||||
- modifier_order
|
||||
- nimble_operator
|
||||
- nslocalizedstring_key
|
||||
- number_separator
|
||||
- object_literal
|
||||
- operator_usage_whitespace
|
||||
- overridden_super_call
|
||||
- override_in_extension
|
||||
- pattern_matching_keywords
|
||||
- closure_body_length
|
||||
- conditional_returns_on_newline
|
||||
- convenience_type
|
||||
- discouraged_optional_collection
|
||||
- explicit_acl
|
||||
- explicit_enum_raw_value
|
||||
- explicit_top_level_acl
|
||||
- explicit_type_interface
|
||||
- file_types_order
|
||||
- force_unwrapping
|
||||
- function_default_parameter_at_end
|
||||
- implicit_return
|
||||
- implicitly_unwrapped_optional
|
||||
- indentation_width
|
||||
- inert_defer
|
||||
- missing_docs
|
||||
- multiline_arguments
|
||||
- multiline_arguments_brackets
|
||||
- multiline_function_chains
|
||||
- multiline_literal_brackets
|
||||
- multiline_parameters
|
||||
- multiline_parameters_brackets
|
||||
- no_extension_access_modifier
|
||||
- no_fallthrough_only
|
||||
- no_grouping_extension
|
||||
- no_magic_numbers
|
||||
- prefer_nimble
|
||||
- prefer_self_in_static_references
|
||||
- prefer_self_type_over_type_of_self
|
||||
- private_action
|
||||
- private_outlet
|
||||
- prohibited_interface_builder
|
||||
- prohibited_super_call
|
||||
- quick_discouraged_call
|
||||
- quick_discouraged_focused_test
|
||||
- quick_discouraged_pending_test
|
||||
- reduce_into
|
||||
- redundant_nil_coalescing
|
||||
- redundant_type_annotation
|
||||
- return_value_from_void_function
|
||||
- single_test_class
|
||||
- sorted_first_last
|
||||
- sorted_imports
|
||||
- static_operator
|
||||
- strong_iboutlet
|
||||
- test_case_accessibility
|
||||
- toggle_bool
|
||||
- unavailable_function
|
||||
- unneeded_parentheses_in_closure_argument
|
||||
- unowned_variable_capture
|
||||
- untyped_error_in_catch
|
||||
- vertical_parameter_alignment_on_call
|
||||
- vertical_whitespace_closing_braces
|
||||
- vertical_whitespace_opening_braces
|
||||
- xct_specific_matcher
|
||||
- yoda_condition
|
||||
- prefixed_toplevel_constant
|
||||
- redundant_self_in_closure
|
||||
- required_deinit
|
||||
- self_binding
|
||||
- sorted_enum_cases
|
||||
- strict_fileprivate
|
||||
- superfluous_else
|
||||
- switch_case_on_newline
|
||||
- todo
|
||||
- trailing_closure
|
||||
- type_contents_order
|
||||
- unused_capture_list
|
||||
- vertical_whitespace_between_cases
|
||||
|
||||
attributes:
|
||||
always_on_line_above:
|
||||
- "@OptionGroup"
|
||||
identifier_name:
|
||||
excluded:
|
||||
- id
|
||||
|
@ -85,15 +65,27 @@ number_separator:
|
|||
minimum_length: 5
|
||||
file_name:
|
||||
excluded:
|
||||
- Exports.swift
|
||||
- GeneratedTests.swift
|
||||
- SwiftSyntax+SwiftLint.swift
|
||||
- TestHelpers.swift
|
||||
|
||||
balanced_xctest_lifecycle: &unit_test_configuration
|
||||
test_parent_classes:
|
||||
- SwiftLintTestCase
|
||||
- XCTestCase
|
||||
empty_xctest_method: *unit_test_configuration
|
||||
single_test_class: *unit_test_configuration
|
||||
|
||||
function_body_length: 60
|
||||
type_body_length: 400
|
||||
|
||||
custom_rules:
|
||||
rule_id:
|
||||
included: Source/SwiftLintFramework/Rules/.+/\w+\.swift
|
||||
included: Source/SwiftLintBuiltInRules/Rules/.+/\w+\.swift
|
||||
name: Rule ID
|
||||
message: Rule IDs must be all lowercase, snake case and not end with `rule`
|
||||
regex: identifier:\s*("\w+_rule"|"\S*[^a-z_]\S*")
|
||||
regex: ^\s+identifier:\s*("\w+_rule"|"\S*[^a-z_]\S*")
|
||||
severity: error
|
||||
fatal_error:
|
||||
name: Fatal Error
|
||||
|
@ -109,3 +101,8 @@ custom_rules:
|
|||
message: Rule Test Function mustn't end with `rule`
|
||||
regex: func\s*test\w+(r|R)ule\(\)
|
||||
severity: error
|
||||
|
||||
unused_import:
|
||||
always_keep_imports:
|
||||
- SwiftSyntaxBuilder # we can't detect uses of string interpolation of swift syntax nodes
|
||||
- SwiftLintFramework # now that this is a wrapper around other modules, don't treat as unused
|
||||
|
|
179
BUILD
179
BUILD
|
@ -1,36 +1,78 @@
|
|||
load("@build_bazel_rules_apple//apple:apple.bzl", "apple_universal_binary")
|
||||
load(
|
||||
"@build_bazel_rules_swift//swift:swift.bzl",
|
||||
"swift_binary",
|
||||
"swift_library",
|
||||
)
|
||||
load(
|
||||
"@com_github_buildbuddy_io_rules_xcodeproj//xcodeproj:xcodeproj.bzl",
|
||||
"@rules_xcodeproj//xcodeproj:defs.bzl",
|
||||
"xcode_schemes",
|
||||
"xcodeproj",
|
||||
)
|
||||
|
||||
# Targets
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintCore",
|
||||
srcs = glob(["Source/SwiftLintCore/**/*.swift"]),
|
||||
module_name = "SwiftLintCore",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"@SwiftSyntax//:SwiftIDEUtils_opt",
|
||||
"@SwiftSyntax//:SwiftOperators_opt",
|
||||
"@SwiftSyntax//:SwiftParserDiagnostics_opt",
|
||||
"@SwiftSyntax//:SwiftSyntaxBuilder_opt",
|
||||
"@SwiftSyntax//:SwiftSyntax_opt",
|
||||
"@com_github_jpsim_sourcekitten//:SourceKittenFramework",
|
||||
"@sourcekitten_com_github_jpsim_yams//:Yams",
|
||||
"@swiftlint_com_github_scottrhoyt_swifty_text_table//:SwiftyTextTable",
|
||||
] + select({
|
||||
"@platforms//os:linux": ["@com_github_krzyzanowskim_cryptoswift//:CryptoSwift"],
|
||||
"//conditions:default": [":DyldWarningWorkaround"],
|
||||
}),
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintBuiltInRules",
|
||||
srcs = glob(["Source/SwiftLintBuiltInRules/**/*.swift"]),
|
||||
module_name = "SwiftLintBuiltInRules",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintCore",
|
||||
],
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintExtraRules",
|
||||
srcs = [
|
||||
"Source/SwiftLintExtraRules/Exports.swift",
|
||||
"@swiftlint_extra_rules//:extra_rules",
|
||||
],
|
||||
module_name = "SwiftLintExtraRules",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintCore",
|
||||
],
|
||||
)
|
||||
|
||||
swift_library(
|
||||
name = "SwiftLintFramework",
|
||||
srcs = glob(
|
||||
["Source/SwiftLintFramework/**/*.swift"],
|
||||
exclude = ["Source/SwiftLintFramework/Rules/ExcludedFromBazel/ExtraRules.swift"],
|
||||
) + ["@swiftlint_extra_rules//:extra_rules"],
|
||||
),
|
||||
module_name = "SwiftLintFramework",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"@com_github_jpsim_sourcekitten//:SourceKittenFramework",
|
||||
"@com_github_keith_swift_syntax//:SwiftSyntax",
|
||||
"@com_github_keith_swift_syntax//:SwiftSyntaxParser",
|
||||
"@sourcekitten_com_github_jpsim_yams//:Yams",
|
||||
] + select({
|
||||
"@platforms//os:linux": ["@com_github_krzyzanowskim_cryptoswift//:CryptoSwift"],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
":SwiftLintBuiltInRules",
|
||||
":SwiftLintCore",
|
||||
":SwiftLintExtraRules",
|
||||
],
|
||||
)
|
||||
|
||||
swift_binary(
|
||||
name = "swiftlint",
|
||||
swift_library(
|
||||
name = "swiftlint.library",
|
||||
srcs = glob(["Source/swiftlint/**/*.swift"]),
|
||||
module_name = "swiftlint",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":SwiftLintFramework",
|
||||
|
@ -40,35 +82,130 @@ swift_binary(
|
|||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "SwiftLintConfig",
|
||||
srcs = [".swiftlint.yml"],
|
||||
visibility = ["//Tests:__subpackages__"],
|
||||
swift_binary(
|
||||
name = "swiftlint",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
":swiftlint.library",
|
||||
],
|
||||
)
|
||||
|
||||
apple_universal_binary(
|
||||
name = "universal_swiftlint",
|
||||
binary = ":swiftlint",
|
||||
forced_cpus = [
|
||||
"x86_64",
|
||||
"arm64",
|
||||
],
|
||||
minimum_os_version = "12.0",
|
||||
platform_type = "macos",
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "SourceFilesToLint",
|
||||
srcs = glob(["Source/**"]),
|
||||
name = "DyldWarningWorkaroundSources",
|
||||
srcs = [
|
||||
"Source/DyldWarningWorkaround/DyldWarningWorkaround.c",
|
||||
"Source/DyldWarningWorkaround/include/objc_dupclass.h",
|
||||
],
|
||||
)
|
||||
|
||||
cc_library(
|
||||
name = "DyldWarningWorkaround",
|
||||
srcs = ["//:DyldWarningWorkaroundSources"],
|
||||
includes = ["Source/DyldWarningWorkaround/include"],
|
||||
alwayslink = True,
|
||||
)
|
||||
|
||||
# Linting
|
||||
|
||||
filegroup(
|
||||
name = "LintInputs",
|
||||
srcs = glob(["Source/**/*.swift"]) + [
|
||||
".swiftlint.yml",
|
||||
"//Tests:SwiftLintFrameworkTestsData",
|
||||
],
|
||||
visibility = ["//Tests:__subpackages__"],
|
||||
)
|
||||
|
||||
# Release
|
||||
|
||||
filegroup(
|
||||
name = "release_files",
|
||||
srcs = [
|
||||
"BUILD",
|
||||
"LICENSE",
|
||||
"MODULE.bazel",
|
||||
"//:DyldWarningWorkaroundSources",
|
||||
"//:LintInputs",
|
||||
"//Tests:BUILD",
|
||||
"//bazel:release_files",
|
||||
],
|
||||
)
|
||||
|
||||
# TODO: Use rules_pkg
|
||||
genrule(
|
||||
name = "release",
|
||||
srcs = [":release_files"],
|
||||
outs = [
|
||||
"bazel.tar.gz",
|
||||
"bazel.tar.gz.sha256",
|
||||
],
|
||||
cmd = """\
|
||||
set -euo pipefail
|
||||
|
||||
outs=($(OUTS))
|
||||
|
||||
COPYFILE_DISABLE=1 tar czvfh "$${outs[0]}" \
|
||||
--exclude ^bazel-out/ \
|
||||
--exclude ^external/ \
|
||||
*
|
||||
shasum -a 256 "$${outs[0]}" > "$${outs[1]}"
|
||||
""",
|
||||
)
|
||||
|
||||
# Xcode Integration
|
||||
|
||||
xcodeproj(
|
||||
name = "xcodeproj",
|
||||
build_mode = "bazel",
|
||||
project_name = "SwiftLint",
|
||||
schemes = [
|
||||
xcode_schemes.scheme(
|
||||
name = "SwiftLint",
|
||||
launch_action = xcode_schemes.launch_action("//:swiftlint"),
|
||||
launch_action = xcode_schemes.launch_action(
|
||||
"swiftlint",
|
||||
args = [
|
||||
"--progress",
|
||||
],
|
||||
),
|
||||
test_action = xcode_schemes.test_action([
|
||||
"//Tests:CLITests",
|
||||
"//Tests:SwiftLintFrameworkTests",
|
||||
"//Tests:GeneratedTests",
|
||||
"//Tests:IntegrationTests",
|
||||
"//Tests:ExtraRulesTests",
|
||||
]),
|
||||
),
|
||||
],
|
||||
top_level_targets = [
|
||||
"//:swiftlint",
|
||||
"//Tests:CLITests",
|
||||
"//Tests:SwiftLintFrameworkTests",
|
||||
"//Tests:GeneratedTests",
|
||||
"//Tests:IntegrationTests",
|
||||
"//Tests:ExtraRulesTests",
|
||||
],
|
||||
)
|
||||
|
||||
# Analyze
|
||||
|
||||
sh_test(
|
||||
name = "analyze",
|
||||
srcs = ["//tools:test-analyze.sh"],
|
||||
data = [
|
||||
"Package.resolved",
|
||||
"Package.swift",
|
||||
":LintInputs",
|
||||
":swiftlint",
|
||||
],
|
||||
)
|
||||
|
|
1001
CHANGELOG.md
1001
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
|
@ -1,8 +1,14 @@
|
|||
## Tutorial
|
||||
|
||||
If you'd like to write a SwiftLint rule but aren't sure how to start,
|
||||
please watch and follow along with
|
||||
[this video tutorial](https://vimeo.com/819268038).
|
||||
|
||||
## Pull Requests
|
||||
|
||||
All changes, no matter how trivial, must be done via pull request. Commits
|
||||
should never be made directly on the `master` branch. Prefer rebasing over
|
||||
merging `master` into your PR branch to update it and resolve conflicts.
|
||||
should never be made directly on the `main` branch. Prefer rebasing over
|
||||
merging `main` into your PR branch to update it and resolve conflicts.
|
||||
|
||||
_If you have commit access to SwiftLint and believe your change to be trivial
|
||||
and not worth waiting for review, you may open a pull request and merge
|
||||
|
@ -58,7 +64,7 @@ $ make docker_test
|
|||
|
||||
## Rules
|
||||
|
||||
New rules should be added in the `Source/SwiftLintFramework/Rules` directory.
|
||||
New rules should be added in the `Source/SwiftLintBuiltInRules/Rules` directory.
|
||||
|
||||
Rules should conform to either the `Rule` or `ASTRule` protocols.
|
||||
|
||||
|
@ -98,11 +104,11 @@ configuration object via the `configuration` property:
|
|||
* If none of the provided `RuleConfiguration`s are applicable, you can create one
|
||||
specifically for your rule.
|
||||
|
||||
See [`ForceCastRule`](https://github.com/realm/SwiftLint/blob/master/Source/SwiftLintFramework/Rules/Idiomatic/ForceCastRule.swift)
|
||||
See [`ForceCastRule`](https://github.com/realm/SwiftLint/blob/main/Source/SwiftLintBuiltInRules/Rules/Idiomatic/ForceCastRule.swift)
|
||||
for a rule that allows severity configuration,
|
||||
[`FileLengthRule`](https://github.com/realm/SwiftLint/blob/master/Source/SwiftLintFramework/Rules/Metrics/FileLengthRule.swift)
|
||||
[`FileLengthRule`](https://github.com/realm/SwiftLint/blob/main/Source/SwiftLintBuiltInRules/Rules/Metrics/FileLengthRule.swift)
|
||||
for a rule that has multiple severity levels,
|
||||
[`IdentifierNameRule`](https://github.com/realm/SwiftLint/blob/master/Source/SwiftLintFramework/Rules/Style/IdentifierNameRule.swift)
|
||||
[`IdentifierNameRule`](https://github.com/realm/SwiftLint/blob/main/Source/SwiftLintBuiltInRules/Rules/Style/IdentifierNameRule.swift)
|
||||
for a rule that allows name evaluation configuration:
|
||||
|
||||
``` yaml
|
||||
|
@ -170,9 +176,9 @@ To bring up a new Buildkite worker from MacStadium:
|
|||
1. Change account password
|
||||
1. Update macOS to the latest version
|
||||
1. Install Homebrew: https://brew.sh
|
||||
1. Install Buildkite agent and other tools via Homebrew: `brew install buildkite/buildkite/buildkite-agent aria2 htop`
|
||||
1. Install the xcodes CLI by downloading the zip and moving it to `/usr/local/bin`: https://github.com/RobotsAndPencils/xcodes/releases
|
||||
1. Install latest Xcode version: `xcodes install --latest`
|
||||
1. Install bundler: `sudo gem install bundler`
|
||||
1. Add `DANGER_GITHUB_API_TOKEN` to `/opt/homebrew/etc/buildkite-agent/hooks/environment`
|
||||
1. Configure and launch buildkite agent: `brew info buildkite-agent` / https://buildkite.com/organizations/swiftlint/agents#setup-macos
|
||||
1. Install Buildkite agent and other tools via Homebrew:
|
||||
`brew install aria2 bazelisk htop buildkite/buildkite/buildkite-agent robotsandpencils/made/xcodes`
|
||||
1. Install latest Xcode version: `xcodes update && xcodes install 14.0.0`
|
||||
1. Add `DANGER_GITHUB_API_TOKEN` and `HOME` to `/opt/homebrew/etc/buildkite-agent/hooks/environment`
|
||||
1. Configure and launch buildkite agent: `brew info buildkite-agent` /
|
||||
https://buildkite.com/organizations/swiftlint/agents#setup-macos
|
||||
|
|
|
@ -14,13 +14,13 @@ modified_files = git.modified_files + git.added_files
|
|||
# including in a CHANGELOG for example
|
||||
has_app_changes = !modified_files.grep(/Source/).empty?
|
||||
has_test_changes = !modified_files.grep(/Tests/).empty?
|
||||
has_danger_changes = !modified_files.grep(/Dangerfile|script\/oss-check|Gemfile/).empty?
|
||||
has_danger_changes = !modified_files.grep(/Dangerfile|tools\/oss-check|Gemfile/).empty?
|
||||
has_package_changes = !modified_files.grep(/Package\.swift/).empty?
|
||||
has_bazel_changes = !modified_files.grep(/WORKSPACE|bazel\/|BUILD/).empty?
|
||||
has_bazel_changes = !modified_files.grep(/\.bazelrc|\.bazelversion|WORKSPACE|bazel\/|BUILD|MODULE\.bazel/).empty?
|
||||
|
||||
# Add a CHANGELOG entry for app changes
|
||||
if !modified_files.include?('CHANGELOG.md') && has_app_changes
|
||||
warn("If this is a user-facing change, please include a CHANGELOG entry to credit yourself! \nYou can find it at [CHANGELOG.md](https://github.com/realm/SwiftLint/blob/master/CHANGELOG.md).")
|
||||
warn("If this is a user-facing change, please include a CHANGELOG entry to credit yourself! \nYou can find it at [CHANGELOG.md](https://github.com/realm/SwiftLint/blob/main/CHANGELOG.md).")
|
||||
markdown <<-MARKDOWN
|
||||
Here's an example of your CHANGELOG entry:
|
||||
```markdown
|
||||
|
@ -51,7 +51,8 @@ end
|
|||
|
||||
file = Tempfile.new('violations')
|
||||
|
||||
Open3.popen3("script/oss-check -v 2> #{file.path}") do |_, stdout, _, _|
|
||||
force_flag = has_danger_changes ? "--force" : ""
|
||||
Open3.popen3("tools/oss-check -v #{force_flag} 2> #{file.path}") do |_, stdout, _, _|
|
||||
while char = stdout.getc
|
||||
print char
|
||||
end
|
||||
|
|
19
Dockerfile
19
Dockerfile
|
@ -1,6 +1,6 @@
|
|||
# Explicitly specify `focal` because `swift:latest` does not use `ubuntu:latest`.
|
||||
ARG BUILDER_IMAGE=swift:focal
|
||||
ARG RUNTIME_IMAGE=ubuntu:focal
|
||||
# Explicitly specify `jammy` to keep the Swift & Ubuntu images in sync.
|
||||
ARG BUILDER_IMAGE=swift:jammy
|
||||
ARG RUNTIME_IMAGE=ubuntu:jammy
|
||||
|
||||
# builder image
|
||||
FROM ${BUILDER_IMAGE} AS builder
|
||||
|
@ -9,18 +9,16 @@ RUN apt-get update && apt-get install -y \
|
|||
libxml2-dev \
|
||||
&& rm -r /var/lib/apt/lists/*
|
||||
WORKDIR /workdir/
|
||||
COPY Plugins Plugins/
|
||||
COPY Source Source/
|
||||
COPY Tests Tests/
|
||||
COPY Package.* ./
|
||||
|
||||
RUN ln -s /usr/lib/swift/_InternalSwiftSyntaxParser .
|
||||
|
||||
RUN swift package update
|
||||
ARG SWIFT_FLAGS="-c release -Xswiftc -static-stdlib -Xlinker -lCFURLSessionInterface -Xlinker -lCFXMLInterface -Xlinker -lcurl -Xlinker -lxml2 -Xswiftc -I. -Xlinker -fuse-ld=lld -Xlinker -L/usr/lib/swift/linux"
|
||||
RUN swift build $SWIFT_FLAGS
|
||||
RUN swift build $SWIFT_FLAGS --product swiftlint
|
||||
RUN mkdir -p /executables
|
||||
RUN for executable in $(swift package completion-tool list-executables); do \
|
||||
install -v `swift build $SWIFT_FLAGS --show-bin-path`/$executable /executables; \
|
||||
done
|
||||
RUN install -v `swift build $SWIFT_FLAGS --show-bin-path`/swiftlint /executables
|
||||
|
||||
# runtime image
|
||||
FROM ${RUNTIME_IMAGE}
|
||||
|
@ -32,9 +30,10 @@ RUN apt-get update && apt-get install -y \
|
|||
COPY --from=builder /usr/lib/libsourcekitdInProc.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/libBlocksRuntime.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/libdispatch.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/lib_InternalSwiftSyntaxParser.so /usr/lib
|
||||
COPY --from=builder /usr/lib/swift/linux/libswiftCore.so /usr/lib
|
||||
COPY --from=builder /executables/* /usr/bin
|
||||
|
||||
RUN swiftlint version
|
||||
RUN echo "_ = 0" | swiftlint --use-stdin
|
||||
|
||||
CMD ["swiftlint"]
|
||||
|
|
99
Gemfile.lock
99
Gemfile.lock
|
@ -1,16 +1,15 @@
|
|||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
CFPropertyList (3.0.5)
|
||||
CFPropertyList (3.0.6)
|
||||
rexml
|
||||
activesupport (6.1.5.1)
|
||||
activesupport (7.0.4.3)
|
||||
concurrent-ruby (~> 1.0, >= 1.0.2)
|
||||
i18n (>= 1.6, < 2)
|
||||
minitest (>= 5.1)
|
||||
tzinfo (~> 2.0)
|
||||
zeitwerk (~> 2.3)
|
||||
addressable (2.8.0)
|
||||
public_suffix (>= 2.0.2, < 5.0)
|
||||
addressable (2.8.4)
|
||||
public_suffix (>= 2.0.2, < 6.0)
|
||||
algoliasearch (1.27.5)
|
||||
httpclient (~> 2.8, >= 2.8.3)
|
||||
json (>= 1.5.1)
|
||||
|
@ -20,15 +19,15 @@ GEM
|
|||
cork
|
||||
nap
|
||||
open4 (~> 1.3)
|
||||
cocoapods (1.11.3)
|
||||
cocoapods (1.12.1)
|
||||
addressable (~> 2.8)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
cocoapods-core (= 1.11.3)
|
||||
cocoapods-core (= 1.12.1)
|
||||
cocoapods-deintegrate (>= 1.0.3, < 2.0)
|
||||
cocoapods-downloader (>= 1.4.0, < 2.0)
|
||||
cocoapods-downloader (>= 1.6.0, < 2.0)
|
||||
cocoapods-plugins (>= 1.0.0, < 2.0)
|
||||
cocoapods-search (>= 1.0.0, < 2.0)
|
||||
cocoapods-trunk (>= 1.4.0, < 2.0)
|
||||
cocoapods-trunk (>= 1.6.0, < 2.0)
|
||||
cocoapods-try (>= 1.1.0, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
escape (~> 0.0.4)
|
||||
|
@ -36,10 +35,10 @@ GEM
|
|||
gh_inspector (~> 1.0)
|
||||
molinillo (~> 0.8.0)
|
||||
nap (~> 1.0)
|
||||
ruby-macho (>= 1.0, < 3.0)
|
||||
ruby-macho (>= 2.3.0, < 3.0)
|
||||
xcodeproj (>= 1.21.0, < 2.0)
|
||||
cocoapods-core (1.11.3)
|
||||
activesupport (>= 5.0, < 7)
|
||||
cocoapods-core (1.12.1)
|
||||
activesupport (>= 5.0, < 8)
|
||||
addressable (~> 2.8)
|
||||
algoliasearch (~> 1.0)
|
||||
concurrent-ruby (~> 1.1)
|
||||
|
@ -58,60 +57,42 @@ GEM
|
|||
netrc (~> 0.11)
|
||||
cocoapods-try (1.2.0)
|
||||
colored2 (3.1.2)
|
||||
concurrent-ruby (1.1.10)
|
||||
concurrent-ruby (1.2.2)
|
||||
cork (0.3.0)
|
||||
colored2 (~> 3.1)
|
||||
danger (8.6.1)
|
||||
danger (9.2.0)
|
||||
claide (~> 1.0)
|
||||
claide-plugins (>= 0.9.2)
|
||||
colored2 (~> 3.1)
|
||||
cork (~> 0.1)
|
||||
faraday (>= 0.9.0, < 2.0)
|
||||
faraday (>= 0.9.0, < 3.0)
|
||||
faraday-http-cache (~> 2.0)
|
||||
git (~> 1.7)
|
||||
kramdown (~> 2.3)
|
||||
kramdown-parser-gfm (~> 1.0)
|
||||
no_proxy_fix
|
||||
octokit (~> 4.7)
|
||||
octokit (~> 5.0)
|
||||
terminal-table (>= 1, < 4)
|
||||
escape (0.0.4)
|
||||
ethon (0.15.0)
|
||||
ethon (0.16.0)
|
||||
ffi (>= 1.15.0)
|
||||
faraday (1.10.0)
|
||||
faraday-em_http (~> 1.0)
|
||||
faraday-em_synchrony (~> 1.0)
|
||||
faraday-excon (~> 1.1)
|
||||
faraday-httpclient (~> 1.0)
|
||||
faraday-multipart (~> 1.0)
|
||||
faraday-net_http (~> 1.0)
|
||||
faraday-net_http_persistent (~> 1.0)
|
||||
faraday-patron (~> 1.0)
|
||||
faraday-rack (~> 1.0)
|
||||
faraday-retry (~> 1.0)
|
||||
faraday (2.7.4)
|
||||
faraday-net_http (>= 2.0, < 3.1)
|
||||
ruby2_keywords (>= 0.0.4)
|
||||
faraday-em_http (1.0.0)
|
||||
faraday-em_synchrony (1.0.0)
|
||||
faraday-excon (1.1.0)
|
||||
faraday-http-cache (2.2.0)
|
||||
faraday-http-cache (2.4.1)
|
||||
faraday (>= 0.8)
|
||||
faraday-httpclient (1.0.1)
|
||||
faraday-multipart (1.0.3)
|
||||
multipart-post (>= 1.2, < 3)
|
||||
faraday-net_http (1.0.1)
|
||||
faraday-net_http_persistent (1.2.0)
|
||||
faraday-patron (1.0.0)
|
||||
faraday-rack (1.0.0)
|
||||
faraday-retry (1.0.3)
|
||||
faraday-net_http (3.0.2)
|
||||
ffi (1.15.5)
|
||||
fourflusher (2.3.1)
|
||||
fuzzy_match (2.0.4)
|
||||
gh_inspector (1.1.3)
|
||||
git (1.11.0)
|
||||
git (1.18.0)
|
||||
addressable (~> 2.8)
|
||||
rchardet (~> 1.8)
|
||||
httpclient (2.8.3)
|
||||
i18n (1.10.0)
|
||||
i18n (1.12.0)
|
||||
concurrent-ruby (~> 1.0)
|
||||
jazzy (0.14.2)
|
||||
jazzy (0.14.3)
|
||||
cocoapods (~> 1.5)
|
||||
mustache (~> 1.1)
|
||||
open4 (~> 1.3)
|
||||
|
@ -121,58 +102,56 @@ GEM
|
|||
sassc (~> 2.1)
|
||||
sqlite3 (~> 1.3)
|
||||
xcinvoke (~> 0.3.0)
|
||||
json (2.6.1)
|
||||
json (2.6.3)
|
||||
kramdown (2.4.0)
|
||||
rexml
|
||||
kramdown-parser-gfm (1.1.0)
|
||||
kramdown (~> 2.0)
|
||||
liferaft (0.0.6)
|
||||
minitest (5.15.0)
|
||||
minitest (5.18.0)
|
||||
molinillo (0.8.0)
|
||||
multipart-post (2.1.1)
|
||||
mustache (1.1.1)
|
||||
nanaimo (0.3.0)
|
||||
nap (1.1.0)
|
||||
netrc (0.11.0)
|
||||
no_proxy_fix (0.1.2)
|
||||
octokit (4.22.0)
|
||||
faraday (>= 0.9)
|
||||
sawyer (~> 0.8.0, >= 0.5.3)
|
||||
octokit (5.6.1)
|
||||
faraday (>= 1, < 3)
|
||||
sawyer (~> 0.9)
|
||||
open4 (1.3.4)
|
||||
public_suffix (4.0.7)
|
||||
rchardet (1.8.0)
|
||||
redcarpet (3.5.1)
|
||||
redcarpet (3.6.0)
|
||||
rexml (3.2.5)
|
||||
rouge (3.28.0)
|
||||
rouge (3.30.0)
|
||||
ruby-macho (2.5.1)
|
||||
ruby2_keywords (0.0.5)
|
||||
sassc (2.4.0)
|
||||
ffi (~> 1.9)
|
||||
sawyer (0.8.2)
|
||||
sawyer (0.9.2)
|
||||
addressable (>= 2.3.5)
|
||||
faraday (> 0.8, < 2.0)
|
||||
sqlite3 (1.4.2)
|
||||
faraday (>= 0.17.3, < 3)
|
||||
sqlite3 (1.6.2-arm64-darwin)
|
||||
terminal-table (3.0.2)
|
||||
unicode-display_width (>= 1.1.1, < 3)
|
||||
typhoeus (1.4.0)
|
||||
ethon (>= 0.9.0)
|
||||
tzinfo (2.0.4)
|
||||
tzinfo (2.0.6)
|
||||
concurrent-ruby (~> 1.0)
|
||||
unicode-display_width (2.1.0)
|
||||
unicode-display_width (2.4.2)
|
||||
xcinvoke (0.3.0)
|
||||
liferaft (~> 0.0.6)
|
||||
xcodeproj (1.21.0)
|
||||
xcodeproj (1.22.0)
|
||||
CFPropertyList (>= 2.3.3, < 4.0)
|
||||
atomos (~> 0.1.3)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
nanaimo (~> 0.3.0)
|
||||
rexml (~> 3.2.4)
|
||||
zeitwerk (2.5.4)
|
||||
|
||||
PLATFORMS
|
||||
arm64-darwin-21
|
||||
ruby
|
||||
arm64-darwin-22
|
||||
|
||||
DEPENDENCIES
|
||||
cocoapods
|
||||
|
@ -180,4 +159,4 @@ DEPENDENCIES
|
|||
jazzy
|
||||
|
||||
BUNDLED WITH
|
||||
2.3.8
|
||||
2.4.12
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
module(
|
||||
name = "swiftlint",
|
||||
version = "0.52.2",
|
||||
compatibility_level = 1,
|
||||
repo_name = "SwiftLint",
|
||||
)
|
||||
|
||||
bazel_dep(name = "bazel_skylib", version = "1.4.1", dev_dependency = True)
|
||||
bazel_dep(name = "platforms", version = "0.0.6")
|
||||
bazel_dep(name = "rules_apple", version = "2.3.0", repo_name = "build_bazel_rules_apple")
|
||||
bazel_dep(name = "rules_swift", version = "1.8.0", repo_name = "build_bazel_rules_swift")
|
||||
bazel_dep(name = "rules_xcodeproj", version = "1.7.0")
|
||||
bazel_dep(name = "sourcekitten", version = "0.34.1", repo_name = "com_github_jpsim_sourcekitten")
|
||||
bazel_dep(name = "swift_argument_parser", version = "1.2.1", repo_name = "sourcekitten_com_github_apple_swift_argument_parser")
|
||||
bazel_dep(name = "yams", version = "5.0.5", repo_name = "sourcekitten_com_github_jpsim_yams")
|
||||
|
||||
swiftlint_repos = use_extension("//bazel:repos.bzl", "swiftlint_repos_bzlmod")
|
||||
use_repo(
|
||||
swiftlint_repos,
|
||||
"SwiftSyntax",
|
||||
"com_github_johnsundell_collectionconcurrencykit",
|
||||
"com_github_krzyzanowskim_cryptoswift",
|
||||
"swiftlint_com_github_scottrhoyt_swifty_text_table",
|
||||
)
|
||||
|
||||
extra_rules = use_extension("//bazel:extensions.bzl", "extra_rules")
|
||||
use_repo(extra_rules, "swiftlint_extra_rules")
|
77
Makefile
77
Makefile
|
@ -7,10 +7,7 @@ XCODEFLAGS=-scheme 'swiftlint' \
|
|||
OTHER_LDFLAGS=-Wl,-headerpad_max_install_names
|
||||
|
||||
SWIFT_BUILD_FLAGS=--configuration release -Xlinker -dead_strip
|
||||
UNAME=$(shell uname)
|
||||
|
||||
SWIFTLINT_EXECUTABLE_X86=$(shell swift build $(SWIFT_BUILD_FLAGS) --arch x86_64 --show-bin-path)/swiftlint
|
||||
SWIFTLINT_EXECUTABLE_ARM64=$(shell swift build $(SWIFT_BUILD_FLAGS) --arch arm64 --show-bin-path)/swiftlint
|
||||
SWIFTLINT_EXECUTABLE_PARENT=.build/universal
|
||||
SWIFTLINT_EXECUTABLE=$(SWIFTLINT_EXECUTABLE_PARENT)/swiftlint
|
||||
|
||||
|
@ -27,21 +24,25 @@ LICENSE_PATH="$(shell pwd)/LICENSE"
|
|||
|
||||
OUTPUT_PACKAGE=SwiftLint.pkg
|
||||
|
||||
VERSION_STRING=$(shell ./script/get-version)
|
||||
VERSION_STRING=$(shell ./tools/get-version)
|
||||
|
||||
.PHONY: all clean build install package test uninstall docs
|
||||
|
||||
all: build
|
||||
|
||||
sourcery: Source/SwiftLintFramework/Models/PrimaryRuleList.swift Tests/SwiftLintFrameworkTests/GeneratedTests.swift
|
||||
sourcery: Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift Source/SwiftLintCore/Models/ReportersList.swift Tests/GeneratedTests/GeneratedTests.swift
|
||||
|
||||
Source/SwiftLintFramework/Models/PrimaryRuleList.swift: Source/SwiftLintFramework/Rules/**/*.swift .sourcery/PrimaryRuleList.stencil
|
||||
sourcery --sources Source/SwiftLintFramework/Rules --templates .sourcery/PrimaryRuleList.stencil --output .sourcery
|
||||
mv .sourcery/PrimaryRuleList.generated.swift Source/SwiftLintFramework/Models/PrimaryRuleList.swift
|
||||
Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift: Source/SwiftLintBuiltInRules/Rules/**/*.swift .sourcery/BuiltInRules.stencil
|
||||
./tools/sourcery --sources Source/SwiftLintBuiltInRules/Rules --templates .sourcery/BuiltInRules.stencil --output .sourcery
|
||||
mv .sourcery/BuiltInRules.generated.swift Source/SwiftLintBuiltInRules/Models/BuiltInRules.swift
|
||||
|
||||
Tests/SwiftLintFrameworkTests/GeneratedTests.swift: Source/SwiftLintFramework/Rules/**/*.swift .sourcery/GeneratedTests.stencil
|
||||
sourcery --sources Source/SwiftLintFramework/Rules --templates .sourcery/GeneratedTests.stencil --output .sourcery
|
||||
mv .sourcery/GeneratedTests.generated.swift Tests/SwiftLintFrameworkTests/GeneratedTests.swift
|
||||
Source/SwiftLintCore/Models/ReportersList.swift: Source/SwiftLintCore/Reporters/*.swift .sourcery/ReportersList.stencil
|
||||
./tools/sourcery --sources Source/SwiftLintCore/Reporters --templates .sourcery/ReportersList.stencil --output .sourcery
|
||||
mv .sourcery/ReportersList.generated.swift Source/SwiftLintCore/Models/ReportersList.swift
|
||||
|
||||
Tests/GeneratedTests/GeneratedTests.swift: Source/SwiftLint*/Rules/**/*.swift .sourcery/GeneratedTests.stencil
|
||||
./tools/sourcery --sources Source/SwiftLintCore/Rules --sources Source/SwiftLintBuiltInRules/Rules --templates .sourcery/GeneratedTests.stencil --output .sourcery
|
||||
mv .sourcery/GeneratedTests.generated.swift Tests/GeneratedTests/GeneratedTests.swift
|
||||
|
||||
test: clean_xcode
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) test
|
||||
|
@ -62,25 +63,18 @@ analyze_autocorrect: write_xcodebuild_log
|
|||
clean:
|
||||
rm -f "$(OUTPUT_PACKAGE)"
|
||||
rm -rf "$(TEMPORARY_FOLDER)"
|
||||
rm -f "./*.zip"
|
||||
rm -f "./*.zip" "bazel.tar.gz" "bazel.tar.gz.sha256"
|
||||
swift package clean
|
||||
|
||||
clean_xcode:
|
||||
$(BUILD_TOOL) $(XCODEFLAGS) -configuration Test clean
|
||||
|
||||
build_x86_64:
|
||||
swift build $(SWIFT_BUILD_FLAGS) --arch x86_64
|
||||
|
||||
build_arm64:
|
||||
swift build $(SWIFT_BUILD_FLAGS) --arch arm64
|
||||
|
||||
build: clean build_x86_64 build_arm64
|
||||
# Need to build for each arch independently to work around https://bugs.swift.org/browse/SR-15802
|
||||
mkdir -p $(SWIFTLINT_EXECUTABLE_PARENT)
|
||||
lipo -create -output \
|
||||
"$(SWIFTLINT_EXECUTABLE)" \
|
||||
"$(SWIFTLINT_EXECUTABLE_X86)" \
|
||||
"$(SWIFTLINT_EXECUTABLE_ARM64)"
|
||||
build:
|
||||
mkdir -p "$(SWIFTLINT_EXECUTABLE_PARENT)"
|
||||
bazel build --config release universal_swiftlint
|
||||
$(eval SWIFTLINT_BINARY := $(shell bazel cquery --config release --output=files universal_swiftlint))
|
||||
mv "$(SWIFTLINT_BINARY)" "$(SWIFTLINT_EXECUTABLE)"
|
||||
chmod +w "$(SWIFTLINT_EXECUTABLE)"
|
||||
strip -rSTX "$(SWIFTLINT_EXECUTABLE)"
|
||||
|
||||
build_with_disable_sandbox:
|
||||
|
@ -109,7 +103,7 @@ portable_zip: installables
|
|||
|
||||
spm_artifactbundle_macos: installables
|
||||
mkdir -p "$(ARTIFACT_BUNDLE_PATH)/swiftlint-$(VERSION_STRING)-macos/bin"
|
||||
sed 's/__VERSION__/$(VERSION_STRING)/g' script/info-macos.json.template > "$(ARTIFACT_BUNDLE_PATH)/info.json"
|
||||
sed 's/__VERSION__/$(VERSION_STRING)/g' tools/info-macos.json.template > "$(ARTIFACT_BUNDLE_PATH)/info.json"
|
||||
cp -f "$(SWIFTLINT_EXECUTABLE)" "$(ARTIFACT_BUNDLE_PATH)/swiftlint-$(VERSION_STRING)-macos/bin"
|
||||
cp -f "$(LICENSE_PATH)" "$(ARTIFACT_BUNDLE_PATH)"
|
||||
(cd "$(TEMPORARY_FOLDER)"; zip -yr - "SwiftLintBinary.artifactbundle") > "./SwiftLintBinary-macos.artifactbundle.zip"
|
||||
|
@ -123,10 +117,11 @@ zip_linux: docker_image
|
|||
|
||||
zip_linux_release:
|
||||
$(eval TMP_FOLDER := $(shell mktemp -d))
|
||||
docker run "ghcr.io/realm/swiftlint:$(VERSION_STRING)" cat /usr/bin/swiftlint > "$(TMP_FOLDER)/swiftlint"
|
||||
docker run --platform linux/amd64 "ghcr.io/realm/swiftlint:$(VERSION_STRING)" cat /usr/bin/swiftlint > "$(TMP_FOLDER)/swiftlint"
|
||||
chmod +x "$(TMP_FOLDER)/swiftlint"
|
||||
cp -f "$(LICENSE_PATH)" "$(TMP_FOLDER)"
|
||||
(cd "$(TMP_FOLDER)"; zip -yr - "swiftlint" "LICENSE") > "./swiftlint_linux.zip"
|
||||
gh release upload "$(VERSION_STRING)" swiftlint_linux.zip
|
||||
|
||||
package: build
|
||||
$(eval PACKAGE_ROOT := $(shell mktemp -d))
|
||||
|
@ -138,13 +133,15 @@ package: build
|
|||
--version "$(VERSION_STRING)" \
|
||||
"$(OUTPUT_PACKAGE)"
|
||||
|
||||
release: package portable_zip spm_artifactbundle_macos zip_linux_release
|
||||
bazel_release:
|
||||
bazel build :release
|
||||
mv bazel-bin/bazel.tar.gz bazel-bin/bazel.tar.gz.sha256 .
|
||||
|
||||
docker_image:
|
||||
docker build --platform linux/amd64 --force-rm --tag swiftlint .
|
||||
|
||||
docker_test:
|
||||
docker run -v `pwd`:`pwd` -w `pwd` --name swiftlint --rm swift:5.6-focal swift test --parallel
|
||||
docker run -v `pwd`:`pwd` -w `pwd` --name swiftlint --rm swift:5.7-focal swift test --parallel
|
||||
|
||||
docker_htop:
|
||||
docker run --platform linux/amd64 -it --rm --pid=container:swiftlint terencewestphal/htop || reset
|
||||
|
@ -155,8 +152,8 @@ display_compilation_time:
|
|||
|
||||
publish:
|
||||
brew update && brew bump-formula-pr --tag=$(shell git describe --tags) --revision=$(shell git rev-parse HEAD) swiftlint
|
||||
# Workaround for https://github.com/CocoaPods/CocoaPods/issues/11185
|
||||
arch -arch x86_64 pod trunk push SwiftLint.podspec
|
||||
bundle install
|
||||
bundle exec pod trunk push SwiftLint.podspec
|
||||
|
||||
docs:
|
||||
swift run swiftlint generate-docs
|
||||
|
@ -166,18 +163,30 @@ docs:
|
|||
get_version:
|
||||
@echo "$(VERSION_STRING)"
|
||||
|
||||
push_version:
|
||||
release:
|
||||
ifneq ($(strip $(shell git status --untracked-files=no --porcelain 2>/dev/null)),)
|
||||
$(error git state is not clean)
|
||||
endif
|
||||
$(eval NEW_VERSION_AND_NAME := $(filter-out $@,$(MAKECMDGOALS)))
|
||||
$(eval NEW_VERSION := $(shell echo $(NEW_VERSION_AND_NAME) | sed 's/:.*//' ))
|
||||
@sed -i '' 's/## Master/## $(NEW_VERSION_AND_NAME)/g' CHANGELOG.md
|
||||
@sed 's/__VERSION__/$(NEW_VERSION)/g' script/Version.swift.template > Source/SwiftLintFramework/Models/Version.swift
|
||||
@sed -i '' 's/## Main/## $(NEW_VERSION_AND_NAME)/g' CHANGELOG.md
|
||||
@sed 's/__VERSION__/$(NEW_VERSION)/g' tools/Version.swift.template > Source/SwiftLintCore/Models/Version.swift
|
||||
@sed -e '3s/.*/ version = "$(NEW_VERSION)",/' -i '' MODULE.bazel
|
||||
make clean
|
||||
make package
|
||||
make bazel_release
|
||||
make portable_zip
|
||||
make spm_artifactbundle_macos
|
||||
./tools/update-artifact-bundle.sh "$(NEW_VERSION)"
|
||||
git commit -a -m "release $(NEW_VERSION)"
|
||||
git tag -a $(NEW_VERSION) -m "$(NEW_VERSION_AND_NAME)"
|
||||
git push origin HEAD
|
||||
git push origin $(NEW_VERSION)
|
||||
./tools/create-github-release.sh "$(NEW_VERSION)"
|
||||
make publish
|
||||
./tools/add-new-changelog-section.sh
|
||||
git commit -a -m "Add new changelog section"
|
||||
git push origin HEAD
|
||||
|
||||
%:
|
||||
@:
|
||||
|
|
141
Package.resolved
141
Package.resolved
|
@ -1,70 +1,77 @@
|
|||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "CollectionConcurrencyKit",
|
||||
"repositoryURL": "https://github.com/JohnSundell/CollectionConcurrencyKit.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "b4f23e24b5a1bff301efc5e70871083ca029ff95",
|
||||
"version": "0.2.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SourceKitten",
|
||||
"repositoryURL": "https://github.com/jpsim/SourceKitten.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "b5f9bb749057dd396e93f97956bef64672bc2a04",
|
||||
"version": "0.33.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "swift-argument-parser",
|
||||
"repositoryURL": "https://github.com/apple/swift-argument-parser.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "df9ee6676cd5b3bf5b330ec7568a5644f547201b",
|
||||
"version": "1.1.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SwiftSyntax",
|
||||
"repositoryURL": "https://github.com/apple/swift-syntax.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "0b6c22b97f8e9320bca62e82cdbee601cf37ad3f",
|
||||
"version": "0.50600.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SwiftyTextTable",
|
||||
"repositoryURL": "https://github.com/scottrhoyt/SwiftyTextTable.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "c6df6cf533d120716bff38f8ff9885e1ce2a4ac3",
|
||||
"version": "0.9.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SWXMLHash",
|
||||
"repositoryURL": "https://github.com/drmohundro/SWXMLHash.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4d0f62f561458cbe1f732171e625f03195151b60",
|
||||
"version": "7.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Yams",
|
||||
"repositoryURL": "https://github.com/jpsim/Yams.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "01835dc202670b5bb90d07f3eae41867e9ed29f6",
|
||||
"version": "5.0.1"
|
||||
}
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "collectionconcurrencykit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/JohnSundell/CollectionConcurrencyKit.git",
|
||||
"state" : {
|
||||
"revision" : "b4f23e24b5a1bff301efc5e70871083ca029ff95",
|
||||
"version" : "0.2.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"identity" : "cryptoswift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/krzyzanowskim/CryptoSwift.git",
|
||||
"state" : {
|
||||
"revision" : "32f641cf24fc7abc1c591a2025e9f2f572648b0f",
|
||||
"version" : "1.7.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sourcekitten",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/jpsim/SourceKitten.git",
|
||||
"state" : {
|
||||
"revision" : "b6dc09ee51dfb0c66e042d2328c017483a1a5d56",
|
||||
"version" : "0.34.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser.git",
|
||||
"state" : {
|
||||
"revision" : "4ad606ba5d7673ea60679a61ff867cc1ff8c8e86",
|
||||
"version" : "1.2.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-syntax",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-syntax.git",
|
||||
"state" : {
|
||||
"revision" : "165fc6d22394c1168ff76ab5d951245971ef07e5",
|
||||
"version" : "509.0.0-swift-DEVELOPMENT-SNAPSHOT-2023-06-05-a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftytexttable",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/scottrhoyt/SwiftyTextTable.git",
|
||||
"state" : {
|
||||
"revision" : "c6df6cf533d120716bff38f8ff9885e1ce2a4ac3",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swxmlhash",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/drmohundro/SWXMLHash.git",
|
||||
"state" : {
|
||||
"revision" : "4d0f62f561458cbe1f732171e625f03195151b60",
|
||||
"version" : "7.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "yams",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/jpsim/Yams.git",
|
||||
"state" : {
|
||||
"revision" : "f47ba4838c30dbd59998a4e4c87ab620ff959e8a",
|
||||
"version" : "5.0.5"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
|
|
125
Package.swift
125
Package.swift
|
@ -1,39 +1,32 @@
|
|||
// swift-tools-version:5.5
|
||||
// swift-tools-version:5.7
|
||||
import PackageDescription
|
||||
|
||||
#if os(macOS)
|
||||
private let addCryptoSwift = false
|
||||
private let staticSwiftSyntax = true
|
||||
#else
|
||||
private let addCryptoSwift = true
|
||||
private let staticSwiftSyntax = false
|
||||
#endif
|
||||
|
||||
let frameworkDependencies: [Target.Dependency] = [
|
||||
.product(name: "SourceKittenFramework", package: "SourceKitten"),
|
||||
.product(name: "SwiftSyntax", package: "SwiftSyntax"),
|
||||
.product(name: "SwiftSyntaxParser", package: "SwiftSyntax"),
|
||||
"Yams",
|
||||
]
|
||||
+ (addCryptoSwift ? ["CryptoSwift"] : [])
|
||||
+ (staticSwiftSyntax ? ["lib_InternalSwiftSyntaxParser"] : [])
|
||||
|
||||
let package = Package(
|
||||
name: "SwiftLint",
|
||||
platforms: [.macOS(.v12)],
|
||||
products: [
|
||||
.executable(name: "swiftlint", targets: ["swiftlint"]),
|
||||
.library(name: "SwiftLintFramework", targets: ["SwiftLintFramework"])
|
||||
.library(name: "SwiftLintFramework", targets: ["SwiftLintFramework"]),
|
||||
.plugin(name: "SwiftLintPlugin", targets: ["SwiftLintPlugin"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "swift-argument-parser", url: "https://github.com/apple/swift-argument-parser.git", .upToNextMinor(from: "1.1.3")),
|
||||
.package(name: "SwiftSyntax", url: "https://github.com/apple/swift-syntax.git", .exact("0.50600.1")),
|
||||
.package(url: "https://github.com/jpsim/SourceKitten.git", from: "0.33.0"),
|
||||
.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.1"),
|
||||
.package(url: "https://github.com/apple/swift-argument-parser.git", .upToNextMinor(from: "1.2.1")),
|
||||
.package(url: "https://github.com/apple/swift-syntax.git", exact: "509.0.0-swift-DEVELOPMENT-SNAPSHOT-2023-06-05-a"),
|
||||
.package(url: "https://github.com/jpsim/SourceKitten.git", .upToNextMinor(from: "0.34.1")),
|
||||
.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.5"),
|
||||
.package(url: "https://github.com/scottrhoyt/SwiftyTextTable.git", from: "0.9.0"),
|
||||
.package(url: "https://github.com/JohnSundell/CollectionConcurrencyKit.git", from: "0.2.0")
|
||||
] + (addCryptoSwift ? [.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.5.1"))] : []),
|
||||
.package(url: "https://github.com/JohnSundell/CollectionConcurrencyKit.git", from: "0.2.0"),
|
||||
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.7.2"))
|
||||
],
|
||||
targets: [
|
||||
.plugin(
|
||||
name: "SwiftLintPlugin",
|
||||
capability: .buildTool(),
|
||||
dependencies: [
|
||||
.target(name: "SwiftLintBinary", condition: .when(platforms: [.macOS])),
|
||||
.target(name: "swiftlint", condition: .when(platforms: [.linux]))
|
||||
]
|
||||
),
|
||||
.executableTarget(
|
||||
name: "swiftlint",
|
||||
dependencies: [
|
||||
|
@ -43,26 +36,86 @@ let package = Package(
|
|||
"SwiftyTextTable",
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "CLITests",
|
||||
dependencies: [
|
||||
"swiftlint"
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintCore",
|
||||
dependencies: [
|
||||
.product(name: "CryptoSwift", package: "CryptoSwift", condition: .when(platforms: [.linux])),
|
||||
.target(name: "DyldWarningWorkaround", condition: .when(platforms: [.macOS])),
|
||||
.product(name: "SourceKittenFramework", package: "SourceKitten"),
|
||||
.product(name: "SwiftIDEUtils", package: "swift-syntax"),
|
||||
.product(name: "SwiftOperators", package: "swift-syntax"),
|
||||
.product(name: "SwiftParser", package: "swift-syntax"),
|
||||
.product(name: "SwiftSyntax", package: "swift-syntax"),
|
||||
.product(name: "SwiftSyntaxBuilder", package: "swift-syntax"),
|
||||
.product(name: "SwiftyTextTable", package: "SwiftyTextTable"),
|
||||
.product(name: "Yams", package: "Yams"),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintBuiltInRules",
|
||||
dependencies: ["SwiftLintCore"]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintExtraRules",
|
||||
dependencies: ["SwiftLintCore"]
|
||||
),
|
||||
.target(
|
||||
name: "SwiftLintFramework",
|
||||
dependencies: frameworkDependencies,
|
||||
// Pass `-dead_strip_dylibs` to ignore the dynamic version of `lib_InternalSwiftSyntaxParser`
|
||||
// that ships with SwiftSyntax because we want the static version from
|
||||
// `StaticInternalSwiftSyntaxParser`.
|
||||
linkerSettings: staticSwiftSyntax ? [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])] : []
|
||||
dependencies: [
|
||||
"SwiftLintBuiltInRules",
|
||||
"SwiftLintCore",
|
||||
"SwiftLintExtraRules"
|
||||
]
|
||||
),
|
||||
.target(name: "DyldWarningWorkaround"),
|
||||
.target(
|
||||
name: "SwiftLintTestHelpers",
|
||||
dependencies: [
|
||||
"SwiftLintFramework"
|
||||
],
|
||||
path: "Tests/SwiftLintTestHelpers"
|
||||
),
|
||||
.testTarget(
|
||||
name: "SwiftLintFrameworkTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework"
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
],
|
||||
exclude: [
|
||||
"Resources",
|
||||
]
|
||||
),
|
||||
] + (staticSwiftSyntax ? [.binaryTarget(
|
||||
name: "lib_InternalSwiftSyntaxParser",
|
||||
url: "https://github.com/keith/StaticInternalSwiftSyntaxParser/releases/download/5.6/lib_InternalSwiftSyntaxParser.xcframework.zip",
|
||||
checksum: "88d748f76ec45880a8250438bd68e5d6ba716c8042f520998a438db87083ae9d"
|
||||
)] : [])
|
||||
.testTarget(
|
||||
name: "GeneratedTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "IntegrationTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "ExtraRulesTests",
|
||||
dependencies: [
|
||||
"SwiftLintFramework",
|
||||
"SwiftLintTestHelpers"
|
||||
]
|
||||
),
|
||||
.binaryTarget(
|
||||
name: "SwiftLintBinary",
|
||||
url: "https://github.com/realm/SwiftLint/releases/download/0.52.2/SwiftLintBinary-macos.artifactbundle.zip",
|
||||
checksum: "89651e1c87fb62faf076ef785a5b1af7f43570b2b74c6773526e0d5114e0578e"
|
||||
)
|
||||
]
|
||||
)
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
import Foundation
|
||||
import PackagePlugin
|
||||
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#else
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
extension Path {
|
||||
/// Scans the receiver, then all of its parents looking for a configuration file with the name ".swiftlint.yml".
|
||||
///
|
||||
/// - returns: Path to the configuration file, or nil if one cannot be found.
|
||||
func firstConfigurationFileInParentDirectories() -> Path? {
|
||||
let defaultConfigurationFileName = ".swiftlint.yml"
|
||||
let proposedDirectory = sequence(
|
||||
first: self,
|
||||
next: { path in
|
||||
guard path.stem.count > 1 else {
|
||||
// Check we're not at the root of this filesystem, as `removingLastComponent()`
|
||||
// will continually return the root from itself.
|
||||
return nil
|
||||
}
|
||||
|
||||
return path.removingLastComponent()
|
||||
}
|
||||
).first { path in
|
||||
let potentialConfigurationFile = path.appending(subpath: defaultConfigurationFileName)
|
||||
return potentialConfigurationFile.isAccessible()
|
||||
}
|
||||
return proposedDirectory?.appending(subpath: defaultConfigurationFileName)
|
||||
}
|
||||
|
||||
/// Safe way to check if the file is accessible from within the current process sandbox.
|
||||
private func isAccessible() -> Bool {
|
||||
let result = string.withCString { pointer in
|
||||
access(pointer, R_OK)
|
||||
}
|
||||
|
||||
return result == 0
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
import Foundation
|
||||
import PackagePlugin
|
||||
|
||||
@main
|
||||
struct SwiftLintPlugin: BuildToolPlugin {
|
||||
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
|
||||
guard let sourceTarget = target as? SourceModuleTarget else {
|
||||
return []
|
||||
}
|
||||
return createBuildCommands(
|
||||
inputFiles: sourceTarget.sourceFiles(withSuffix: "swift").map(\.path),
|
||||
packageDirectory: context.package.directory,
|
||||
workingDirectory: context.pluginWorkDirectory,
|
||||
tool: try context.tool(named: "swiftlint")
|
||||
)
|
||||
}
|
||||
|
||||
private func createBuildCommands(
|
||||
inputFiles: [Path],
|
||||
packageDirectory: Path,
|
||||
workingDirectory: Path,
|
||||
tool: PluginContext.Tool
|
||||
) -> [Command] {
|
||||
if inputFiles.isEmpty {
|
||||
// Don't lint anything if there are no Swift source files in this target
|
||||
return []
|
||||
}
|
||||
|
||||
var arguments = [
|
||||
"lint",
|
||||
"--quiet",
|
||||
// We always pass all of the Swift source files in the target to the tool,
|
||||
// so we need to ensure that any exclusion rules in the configuration are
|
||||
// respected.
|
||||
"--force-exclude",
|
||||
"--cache-path", "\(workingDirectory)"
|
||||
]
|
||||
|
||||
// Manually look for configuration files, to avoid issues when the plugin does not execute our tool from the
|
||||
// package source directory.
|
||||
if let configuration = packageDirectory.firstConfigurationFileInParentDirectories() {
|
||||
arguments.append(contentsOf: ["--config", "\(configuration.string)"])
|
||||
}
|
||||
arguments += inputFiles.map(\.string)
|
||||
|
||||
// We are not producing output files and this is needed only to not include cache files into bundle
|
||||
let outputFilesDirectory = workingDirectory.appending("Output")
|
||||
|
||||
return [
|
||||
.prebuildCommand(
|
||||
displayName: "SwiftLint",
|
||||
executable: tool.path,
|
||||
arguments: arguments,
|
||||
outputFilesDirectory: outputFilesDirectory
|
||||
)
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(XcodeProjectPlugin)
|
||||
import XcodeProjectPlugin
|
||||
|
||||
extension SwiftLintPlugin: XcodeBuildToolPlugin {
|
||||
func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] {
|
||||
let inputFilePaths = target.inputFiles
|
||||
.filter { $0.type == .source && $0.path.extension == "swift" }
|
||||
.map(\.path)
|
||||
return createBuildCommands(
|
||||
inputFiles: inputFilePaths,
|
||||
packageDirectory: context.xcodeProject.directory,
|
||||
workingDirectory: context.pluginWorkDirectory,
|
||||
tool: try context.tool(named: "swiftlint")
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif
|
182
README.md
182
README.md
|
@ -1,14 +1,14 @@
|
|||
# SwiftLint
|
||||
|
||||
A tool to enforce Swift style and conventions, loosely based on the now archived [GitHub Swift Style Guide](https://github.com/github/swift-style-guide). SwiftLint enforces the style guide rules that are generally accepted by the Swift community. These rules are well described in popular style guides like [Ray Wenderlich's Swift Style Guide](https://github.com/raywenderlich/swift-style-guide).
|
||||
A tool to enforce Swift style and conventions, loosely based on the now archived [GitHub Swift Style Guide](https://github.com/github/swift-style-guide). SwiftLint enforces the style guide rules that are generally accepted by the Swift community. These rules are well described in popular style guides like [Kodeco's Swift Style Guide](https://github.com/kodecocodes/swift-style-guide).
|
||||
|
||||
SwiftLint hooks into [Clang](http://clang.llvm.org) and
|
||||
[SourceKit](http://www.jpsim.com/uncovering-sourcekit) to use the
|
||||
[AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) representation
|
||||
of your source files for more accurate results.
|
||||
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=master)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=master)
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=main)
|
||||
|
||||

|
||||
|
||||
|
@ -16,7 +16,7 @@ This project adheres to the [Contributor Covenant Code of Conduct](https://realm
|
|||
By participating, you are expected to uphold this code. Please report
|
||||
unacceptable behavior to [info@realm.io](mailto:info@realm.io).
|
||||
|
||||
> Language Switch: [中文](https://github.com/realm/SwiftLint/blob/master/README_CN.md), [한국어](https://github.com/realm/SwiftLint/blob/master/README_KR.md).
|
||||
> Language Switch: [中文](https://github.com/realm/SwiftLint/blob/main/README_CN.md), [한국어](https://github.com/realm/SwiftLint/blob/main/README_KR.md).
|
||||
|
||||
## Installation
|
||||
|
||||
|
@ -64,19 +64,25 @@ You can also build and install from source by cloning this project and running
|
|||
|
||||
### Using Bazel
|
||||
|
||||
Put this in your `WORKSPACE`:
|
||||
Put this in your `MODULE.bazel`:
|
||||
|
||||
```bzl
|
||||
bazel_dep(name = "swiftlint", version = "0.50.4", repo_name = "SwiftLint")
|
||||
```
|
||||
|
||||
Or put this in your `WORKSPACE`:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>WORKSPACE</summary>
|
||||
|
||||
```python
|
||||
```bzl
|
||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
||||
|
||||
http_archive(
|
||||
name = "build_bazel_rules_apple",
|
||||
sha256 = "36072d4f3614d309d6a703da0dfe48684ec4c65a89611aeb9590b45af7a3e592",
|
||||
url = "https://github.com/bazelbuild/rules_apple/releases/download/1.0.1/rules_apple.1.0.1.tar.gz",
|
||||
sha256 = "f94e6dddf74739ef5cb30f000e13a2a613f6ebfa5e63588305a71fce8a8a9911",
|
||||
url = "https://github.com/bazelbuild/rules_apple/releases/download/1.1.3/rules_apple.1.1.3.tar.gz",
|
||||
)
|
||||
|
||||
load(
|
||||
|
@ -102,8 +108,8 @@ swift_rules_extra_dependencies()
|
|||
|
||||
http_archive(
|
||||
name = "SwiftLint",
|
||||
sha256 = "e954f4483f7f4cf523896693ee3505585f6beb0f791e362b42d9bdbb615f051a",
|
||||
url = "https://github.com/realm/SwiftLint/releases/download/0.49.0-rc.1/bazel.tar.gz",
|
||||
sha256 = "7c454ff4abeeecdd9513f6293238a6d9f803b587eb93de147f9aa1be0d8337c4",
|
||||
url = "https://github.com/realm/SwiftLint/releases/download/0.49.1/bazel.tar.gz",
|
||||
)
|
||||
|
||||
load("@SwiftLint//bazel:repos.bzl", "swiftlint_repos")
|
||||
|
@ -130,7 +136,7 @@ bazel run -c opt @SwiftLint//:swiftlint
|
|||
To get a high-level overview of recommended ways to integrate SwiftLint into your project,
|
||||
we encourage you to watch this presentation or read the transcript:
|
||||
|
||||
[](https://academy.realm.io/posts/slug-jp-simard-swiftlint/)
|
||||
[](https://youtu.be/9Z1nTMTejqU)
|
||||
|
||||
### Xcode
|
||||
|
||||
|
@ -152,7 +158,10 @@ folder by default. To instruct Xcode where to find SwiftLint, you can either add
|
|||
`/opt/homebrew/bin` to the `PATH` environment variable in your build phase
|
||||
|
||||
```bash
|
||||
export PATH="$PATH:/opt/homebrew/bin"
|
||||
if [[ "$(uname -m)" == arm64 ]]; then
|
||||
export PATH="/opt/homebrew/bin:$PATH"
|
||||
fi
|
||||
|
||||
if which swiftlint > /dev/null; then
|
||||
swiftlint
|
||||
else
|
||||
|
@ -183,19 +192,52 @@ If you've installed SwiftLint via CocoaPods the script should look like this:
|
|||
"${PODS_ROOT}/SwiftLint/swiftlint"
|
||||
```
|
||||
|
||||
### AppCode
|
||||
### Plug-in Support
|
||||
|
||||
To integrate SwiftLint with AppCode, install
|
||||
[this plugin](https://plugins.jetbrains.com/plugin/9175) and configure
|
||||
SwiftLint's installed path in the plugin's preferences.
|
||||
The `fix` action is available via `⌥⏎`.
|
||||
SwiftLint can be used as a build tool plug-in for both Xcode projects as well as
|
||||
Swift packages.
|
||||
|
||||
### Atom
|
||||
> Due to limitations with Swift Package Manager Plug-ins this is only
|
||||
recommended for projects that have a SwiftLint configuration in their root directory as
|
||||
there is currently no way to pass any additional options to the SwiftLint executable.
|
||||
|
||||
To integrate SwiftLint with [Atom](https://atom.io/), install the
|
||||
[`linter-swiftlint`](https://atom.io/packages/linter-swiftlint) package from
|
||||
APM.
|
||||
#### Xcode
|
||||
|
||||
You can integrate SwiftLint as an Xcode Build Tool Plug-in if you're working
|
||||
with a project in Xcode.
|
||||
|
||||
Add SwiftLint as a package dependency to your project without linking any of the
|
||||
products.
|
||||
|
||||
Select the target you want to add linting to and open the `Build Phases` inspector.
|
||||
Open `Run Build Tool Plug-ins` and select the `+` button.
|
||||
Select `SwiftLintPlugin` from the list and add it to the project.
|
||||
|
||||

|
||||
|
||||
For unattended use (e.g. on CI), you can disable the package validation dialog by
|
||||
|
||||
* individually passing `-skipPackagePluginValidation` to `xcodebuild` or
|
||||
* globally setting `defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES`
|
||||
for that user.
|
||||
|
||||
_Note: This implicitly trusts all Xcode package plugins and bypasses Xcode's package validation
|
||||
dialogs, which has security implications._
|
||||
|
||||
#### Swift Package
|
||||
|
||||
You can integrate SwiftLint as a Swift Package Manager Plug-in if you're working with
|
||||
a Swift Package with a `Package.swift` manifest.
|
||||
|
||||
Add SwiftLint as a package dependency to your `Package.swift` file.
|
||||
Add SwiftLint to a target using the `plugins` parameter.
|
||||
|
||||
```swift
|
||||
.target(
|
||||
...
|
||||
plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")]
|
||||
),
|
||||
```
|
||||
|
||||
### Visual Studio Code
|
||||
|
||||
|
@ -266,6 +308,7 @@ SUBCOMMANDS:
|
|||
docs Open SwiftLint documentation website in the default web browser
|
||||
generate-docs Generates markdown documentation for all rules
|
||||
lint (default) Print lint warnings and errors
|
||||
reporters Display the list of reporters and their identifiers
|
||||
rules Display the list of rules and their identifiers
|
||||
version Display the current version of SwiftLint
|
||||
|
||||
|
@ -333,12 +376,21 @@ Once [installed](https://pre-commit.com/#install), add this to the
|
|||
```yaml
|
||||
repos:
|
||||
- repo: https://github.com/realm/SwiftLint
|
||||
rev: 0.44.0
|
||||
rev: 0.50.3
|
||||
hooks:
|
||||
- id: swiftlint
|
||||
```
|
||||
|
||||
Adjust `rev` to the SwiftLint version of your choice.
|
||||
Adjust `rev` to the SwiftLint version of your choice. `pre-commit autoupdate` can be used to update to the current version.
|
||||
|
||||
SwiftLint can be configured using `entry` to apply fixes and fail on errors:
|
||||
```yaml
|
||||
- repo: https://github.com/realm/SwiftLint
|
||||
rev: 0.50.3
|
||||
hooks:
|
||||
- id: swiftlint
|
||||
entry: swiftlint --fix --strict
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
|
@ -349,7 +401,7 @@ continues to contribute more over time.
|
|||
You can find an updated list of rules and more information about them
|
||||
[here](https://realm.github.io/SwiftLint/rule-directory.html).
|
||||
|
||||
You can also check [Source/SwiftLintFramework/Rules](https://github.com/realm/SwiftLint/tree/master/Source/SwiftLintFramework/Rules)
|
||||
You can also check [Source/SwiftLintBuiltInRules/Rules](https://github.com/realm/SwiftLint/tree/main/Source/SwiftLintBuiltInRules/Rules)
|
||||
directory to see their implementation.
|
||||
|
||||
### Opt-In Rules
|
||||
|
@ -427,7 +479,9 @@ run SwiftLint from. The following parameters can be configured:
|
|||
Rule inclusion:
|
||||
|
||||
* `disabled_rules`: Disable rules from the default enabled set.
|
||||
* `opt_in_rules`: Enable rules that are not part of the default set.
|
||||
* `opt_in_rules`: Enable rules that are not part of the default set. The
|
||||
special `all` identifier will enable all opt in linter rules, except the ones
|
||||
listed in `disabled_rules`.
|
||||
* `only_rules`: Only the rules specified in this list will be enabled.
|
||||
Cannot be specified alongside `disabled_rules` or `opt_in_rules`.
|
||||
* `analyzer_rules`: This is an entirely separate list of rules that are only
|
||||
|
@ -449,6 +503,9 @@ opt_in_rules: # some rules are turned off by default, so you need to opt-in
|
|||
# - empty_parameters
|
||||
# - vertical_whitespace
|
||||
|
||||
analyzer_rules: # Rules run by `swiftlint analyze`
|
||||
- explicit_self
|
||||
|
||||
included: # paths to include during linting. `--path` is ignored if present.
|
||||
- Source
|
||||
excluded: # paths to ignore during linting. Takes precedence over `included`.
|
||||
|
@ -457,8 +514,9 @@ excluded: # paths to ignore during linting. Takes precedence over `included`.
|
|||
- Source/ExcludedFolder
|
||||
- Source/ExcludedFile.swift
|
||||
- Source/*/ExcludedFile.swift # Exclude files with a wildcard
|
||||
analyzer_rules: # Rules run by `swiftlint analyze`
|
||||
- explicit_self
|
||||
|
||||
# If true, SwiftLint will not fail if no lintable files are found.
|
||||
allow_zero_lintable_files: false
|
||||
|
||||
# configurable rules can be customized from this configuration file
|
||||
# binary rules can set their severity level
|
||||
|
@ -492,13 +550,29 @@ identifier_name:
|
|||
- id
|
||||
- URL
|
||||
- GlobalAPIKey
|
||||
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging)
|
||||
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, codeclimate, junit, html, emoji, sonarqube, markdown, github-actions-logging, summary)
|
||||
```
|
||||
|
||||
You can also use environment variables in your configuration file,
|
||||
by using `${SOME_VARIABLE}` in a string.
|
||||
|
||||
#### Defining Custom Rules
|
||||
### Defining Custom Rules
|
||||
|
||||
In addition to the rules that the main SwiftLint project ships with, SwiftLint
|
||||
can also run two types of custom rules that you can define yourself in your own
|
||||
projects:
|
||||
|
||||
#### 1. Swift Custom Rules
|
||||
|
||||
These rules are written the same way as the Swift-based rules that ship with
|
||||
SwiftLint so they're fast, accurate, can leverage SwiftSyntax, can be unit
|
||||
tested, and more.
|
||||
|
||||
Using these requires building SwiftLint with Bazel as described in
|
||||
[this video](https://vimeo.com/820572803) or its associated code in
|
||||
[github.com/jpsim/swiftlint-bazel-example](https://github.com/jpsim/swiftlint-bazel-example).
|
||||
|
||||
#### 2. Regex Custom Rules
|
||||
|
||||
You can define custom regex-based rules in your configuration file using the
|
||||
following syntax:
|
||||
|
@ -531,29 +605,41 @@ You can filter the matches by providing one or more `match_kinds`, which will
|
|||
reject matches that include syntax kinds that are not present in this list. Here
|
||||
are all the possible syntax kinds:
|
||||
|
||||
* argument
|
||||
* attribute.builtin
|
||||
* attribute.id
|
||||
* buildconfig.id
|
||||
* buildconfig.keyword
|
||||
* comment
|
||||
* comment.mark
|
||||
* comment.url
|
||||
* doccomment
|
||||
* doccomment.field
|
||||
* identifier
|
||||
* keyword
|
||||
* number
|
||||
* objectliteral
|
||||
* parameter
|
||||
* placeholder
|
||||
* string
|
||||
* string_interpolation_anchor
|
||||
* typeidentifier
|
||||
* `argument`
|
||||
* `attribute.builtin`
|
||||
* `attribute.id`
|
||||
* `buildconfig.id`
|
||||
* `buildconfig.keyword`
|
||||
* `comment`
|
||||
* `comment.mark`
|
||||
* `comment.url`
|
||||
* `doccomment`
|
||||
* `doccomment.field`
|
||||
* `identifier`
|
||||
* `keyword`
|
||||
* `number`
|
||||
* `objectliteral`
|
||||
* `parameter`
|
||||
* `placeholder`
|
||||
* `string`
|
||||
* `string_interpolation_anchor`
|
||||
* `typeidentifier`
|
||||
|
||||
All syntax kinds used in a snippet of Swift code can be extracted asking
|
||||
[SourceKitten](https://github.com/jpsim/SourceKitten). For example,
|
||||
`sourcekitten syntax --text "struct S {}"` delivers
|
||||
|
||||
* `source.lang.swift.syntaxtype.keyword` for the `struct` keyword and
|
||||
* `source.lang.swift.syntaxtype.identifier` for its name `S`
|
||||
|
||||
which match to `keyword` and `identifier` in the above list.
|
||||
|
||||
If using custom rules in combination with `only_rules`, make sure to add
|
||||
`custom_rules` as an item under `only_rules`.
|
||||
|
||||
Unlike Swift custom rules, you can use official SwiftLint builds
|
||||
(e.g. from Homebrew) to run regex custom rules.
|
||||
|
||||
### Auto-correct
|
||||
|
||||
SwiftLint can automatically correct certain violations. Files on disk are
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
# SwiftLint
|
||||
|
||||
SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 [Ray Wenderlich's Swift 代码风格指南](https://github.com/raywenderlich/swift-style-guide)为基础。
|
||||
SwiftLint 是一个用于强制检查 Swift 代码风格和规定的一个工具,基本上以 [Kodeco's Swift 代码风格指南](https://github.com/kodecocodes/swift-style-guide)为基础。
|
||||
|
||||
SwiftLint Hook 了 [Clang](http://clang.llvm.org) 和 [SourceKit](http://www.jpsim.com/uncovering-sourcekit) 从而能够使用 [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) 来表示源代码文件的更多精确结果。
|
||||
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=master)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=master)
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=main)
|
||||
|
||||

|
||||
|
||||
|
@ -167,7 +167,7 @@ SwiftLint 已经包含了超过 75 条规则,并且我们希望 Swift 社区
|
|||
|
||||
你可以在 [Rule Directory](https://realm.github.io/SwiftLint/rule-directory.html) 找到规则的更新列表和更多信息。
|
||||
|
||||
你也可以检视 [Source/SwiftLintFramework/Rules](Source/SwiftLintFramework/Rules) 目录来查看它们的实现。
|
||||
你也可以检视 [Source/SwiftLintBuiltInRules/Rules](Source/SwiftLintBuiltInRules/Rules) 目录来查看它们的实现。
|
||||
|
||||
`opt_in_rules` 默认是关闭的(即,你需要在你的配置文件中明确地打开它们)。
|
||||
|
||||
|
|
15
README_KR.md
15
README_KR.md
|
@ -1,11 +1,11 @@
|
|||
# SwiftLint
|
||||
|
||||
SwiftLint는 스위프트 스타일 및 컨벤션을 강제하기 위한 도구로, [Ray Wenderlich 스위프트 스타일 가이드](https://github.com/raywenderlich/swift-style-guide)에 대략적인 기반을 두고 있습니다.
|
||||
SwiftLint는 스위프트 스타일 및 컨벤션을 강제하기 위한 도구로, [Kodeco 스위프트 스타일 가이드](https://github.com/kodecocodes/swift-style-guide)에 대략적인 기반을 두고 있습니다.
|
||||
|
||||
SwiftLint는 좀 더 정확한 결과를 위해 [Clang](http://clang.llvm.org)과 [SourceKit](http://www.jpsim.com/uncovering-sourcekit)에 연결하여 소스 파일의 [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) 표현을 사용합니다.
|
||||
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=master)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=master)
|
||||
[](https://dev.azure.com/jpsim/SwiftLint/_build/latest?definitionId=4?branchName=main)
|
||||
[](https://codecov.io/github/realm/SwiftLint?branch=main)
|
||||
|
||||

|
||||
|
||||
|
@ -75,7 +75,10 @@ fi
|
|||
그 이유는, 애플 실리콘 기반 맥에서 Homebrew는 기본적으로 바이너리들을 `/opt/homebrew/bin`에 저장하기 때문입니다. SwiftLint가 어디 있는지 찾는 것을 Xcode에 알려주기 위해, build phase에서 `/opt/homebrew/bin`를 `PATH` 환경 변수에 동시에 추가하여야 합니다.
|
||||
|
||||
```bash
|
||||
export PATH="$PATH:/opt/homebrew/bin"
|
||||
if [[ "$(uname -m)" == arm64 ]]; then
|
||||
export PATH="/opt/homebrew/bin:$PATH"
|
||||
fi
|
||||
|
||||
if which swiftlint > /dev/null; then
|
||||
swiftlint
|
||||
else
|
||||
|
@ -180,9 +183,9 @@ $ TOOLCHAINS=com.apple.dt.toolchain.Swift_2_3 swiftlint autocorrect
|
|||
|
||||
## 룰
|
||||
|
||||
SwiftLint에는 75개가 넘는 룰들이 있고, 스위프트 커뮤니티(바로 여러분들!)는 이를 지속적으로 발전시켜 가고 있습니다. [풀 리퀘스트](CONTRIBUTING.md)는 언제나 환영입니다.
|
||||
SwiftLint에는 200개가 넘는 룰들이 있고, 스위프트 커뮤니티(바로 여러분들!)는 이를 지속적으로 발전시켜 가고 있습니다. [풀 리퀘스트](CONTRIBUTING.md)는 언제나 환영입니다.
|
||||
|
||||
현재 구현된 룰 전체를 확인하려면 [Source/SwiftLintFramework/Rules](Source/SwiftLintFramework/Rules)를 살펴보세요.
|
||||
현재 구현된 룰 전체를 확인하려면 [Source/SwiftLintBuiltInRules/Rules](Source/SwiftLintBuiltInRules/Rules)를 살펴보세요.
|
||||
|
||||
`opt_in_rules`는 기본적으로 비활성화되어 있습니다. (즉, 설정 파일에서 명시적으로 해당 룰을 활성화해야 합니다.)
|
||||
|
||||
|
|
17
Releasing.md
17
Releasing.md
|
@ -7,19 +7,8 @@ For SwiftLint contributors, follow these steps to cut a release:
|
|||
* FabricSoftenerRule
|
||||
* Top Loading
|
||||
* Fresh Out Of The Dryer
|
||||
1. Push new version: `make push_version "0.2.0: Tumble Dry"`
|
||||
1. Make sure you have the latest stable Xcode version installed and
|
||||
`xcode-select`ed.
|
||||
1. Create the pkg installer, framework zip, portable zip,
|
||||
macos artifactbundle zip, and Linux zip:
|
||||
`make release`
|
||||
1. Create a GitHub release: https://github.com/realm/SwiftLint/releases/new
|
||||
* Specify the tag you just pushed from the dropdown.
|
||||
* Set the release title to the new version number & release name.
|
||||
* Add the changelog section to the release description text box.
|
||||
* Upload the pkg installer, framework zip, portable zip,
|
||||
macos artifactbundle zip, and Linux zip you just built
|
||||
to the GitHub release binaries.
|
||||
* Click "Publish release".
|
||||
1. Publish to Homebrew and CocoaPods trunk: `make publish`
|
||||
`xcode-select`ed
|
||||
1. Release new version: `make release "0.2.0: Tumble Dry"`
|
||||
1. Wait for the Docker CI job to finish then run: `make zip_linux_release`
|
||||
1. Celebrate. :tada:
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
#ifdef __APPLE__
|
||||
|
||||
#include "objc_dupclass.h"
|
||||
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax11SyntaxArena);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax13SyntaxVisitor);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax14SyntaxRewriter);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax16BumpPtrAllocator);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax16SyntaxAnyVisitor);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax18ParsingSyntaxArena);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax23SourceLocationConverter);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax26IncrementalParseTransition);
|
||||
OBJC_DUPCLASS(_TtC11SwiftSyntax35IncrementalParseReusedNodeCollector);
|
||||
|
||||
#endif // __APPLE__
|
|
@ -0,0 +1,19 @@
|
|||
// https://github.com/keith/objc_dupclass
|
||||
#include <stdint.h>
|
||||
|
||||
// TODO: This isn't entirely accurate, but I'm not sure how to more accurately determine
|
||||
#if (defined(__arm64__) || defined(DUPCLASS_FORCE_DATA_CONST)) && !defined(DUPCLASS_FORCE_DATA)
|
||||
#define SECTION "__DATA_CONST"
|
||||
#else
|
||||
#define SECTION "__DATA"
|
||||
#endif
|
||||
|
||||
// Struct layout from https://github.com/apple-oss-distributions/objc4/blob/8701d5672d3fd3cd817aeb84db1077aafe1a1604/runtime/objc-abi.h#L175-L183
|
||||
#define OBJC_DUPCLASS(kclass) \
|
||||
__attribute__((used)) __attribute__((visibility("hidden"))) \
|
||||
static struct { uint32_t version; uint32_t flags; const char name[64]; } \
|
||||
const __duplicate_class_##kclass = { 0, 0, #kclass }; \
|
||||
\
|
||||
__attribute__((used)) __attribute__((visibility("hidden"))) \
|
||||
__attribute__((section (SECTION",__objc_dupclass"))) \
|
||||
const void* __set___objc_dupclass_sym___duplicate_class_##kclass = &__duplicate_class_##kclass
|
|
@ -0,0 +1 @@
|
|||
@_exported import SwiftLintCore
|
|
@ -0,0 +1,187 @@
|
|||
import SourceKittenFramework
|
||||
|
||||
/// Struct to represent SwiftUI ViewModifiers for the purpose of finding modifiers in a substructure.
|
||||
struct SwiftUIModifier {
|
||||
/// Name of the modifier.
|
||||
let name: String
|
||||
|
||||
/// List of arguments to check for in the modifier.
|
||||
let arguments: [Argument]
|
||||
|
||||
struct Argument {
|
||||
/// Name of the argument we want to find. For single unnamed arguments, use the empty string.
|
||||
let name: String
|
||||
|
||||
/// Whether or not the argument is required. If the argument is present, value checks are enforced.
|
||||
/// Allows for better handling of modifiers with default values for certain arguments where we want
|
||||
/// to ensure that the default value is used.
|
||||
let required: Bool
|
||||
|
||||
/// List of possible values for the argument. Typically should just be a list with a single element,
|
||||
/// but allows for the flexibility of checking for multiple possible values. To only check for the presence
|
||||
/// of the modifier and not enforce any certain values, pass an empty array. All values are parsed as
|
||||
/// Strings; for other types (boolean, numeric, optional, etc) types you can check for "true", "5", "nil", etc.
|
||||
let values: [String]
|
||||
|
||||
/// Success criteria used for matching values (prefix, suffix, substring, exact match, or none).
|
||||
let matchType: MatchType
|
||||
|
||||
init(name: String, required: Bool = true, values: [String], matchType: MatchType = .exactMatch) {
|
||||
self.name = name
|
||||
self.required = required
|
||||
self.values = values
|
||||
self.matchType = matchType
|
||||
}
|
||||
}
|
||||
|
||||
enum MatchType {
|
||||
case prefix, suffix, substring, exactMatch
|
||||
|
||||
/// Compares the parsed argument value to a target value for the given match type
|
||||
/// and returns true is a match is found.
|
||||
func matches(argumentValue: String, targetValue: String) -> Bool {
|
||||
switch self {
|
||||
case .prefix:
|
||||
return argumentValue.hasPrefix(targetValue)
|
||||
case .suffix:
|
||||
return argumentValue.hasSuffix(targetValue)
|
||||
case .substring:
|
||||
return argumentValue.contains(targetValue)
|
||||
case .exactMatch:
|
||||
return argumentValue == targetValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions for recursively checking SwiftUI code for certain modifiers.
|
||||
extension SourceKittenDictionary {
|
||||
/// Call on a SwiftUI View to recursively check the substructure for a certain modifier with certain arguments.
|
||||
/// - Parameters:
|
||||
/// - modifiers: A list of `SwiftUIModifier` structs to check for in the view's substructure.
|
||||
/// In most cases, this can just be a single modifier, but since some modifiers have
|
||||
/// multiple versions, this enables checking for any modifier from the list.
|
||||
/// - file: The SwiftLintFile object for the current file, used to extract argument values.
|
||||
/// - Returns: A boolean value representing whether or not the given modifier with the specified
|
||||
/// arguments appears in the view's substructure.
|
||||
func hasModifier(anyOf modifiers: [SwiftUIModifier], in file: SwiftLintFile) -> Bool {
|
||||
// SwiftUI ViewModifiers are treated as `call` expressions, and we make sure we can get the expression's name.
|
||||
guard expressionKind == .call, let name else {
|
||||
return false
|
||||
}
|
||||
|
||||
// If any modifier from the list matches, return true.
|
||||
for modifier in modifiers {
|
||||
// Check for the given modifier name
|
||||
guard name.hasSuffix(modifier.name) else {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check arguments.
|
||||
var matchesArgs = true
|
||||
for argument in modifier.arguments {
|
||||
var foundArg = false
|
||||
var argValue: String?
|
||||
|
||||
// Check for single unnamed argument.
|
||||
if argument.name.isEmpty {
|
||||
foundArg = true
|
||||
argValue = getSingleUnnamedArgumentValue(in: file)
|
||||
} else if let parsedArgument = enclosedArguments.first(where: { $0.name == argument.name }) {
|
||||
foundArg = true
|
||||
argValue = parsedArgument.getArgumentValue(in: file)
|
||||
}
|
||||
|
||||
// If argument is not required and we didn't find it, continue.
|
||||
if !foundArg && !argument.required {
|
||||
continue
|
||||
}
|
||||
|
||||
// Otherwise, we must have found an argument with a non-nil value to continue.
|
||||
guard foundArg, let argumentValue = argValue else {
|
||||
matchesArgs = false
|
||||
break
|
||||
}
|
||||
|
||||
// Argument value can match any of the options given in the argument struct.
|
||||
if argument.values.isEmpty || argument.values.contains(where: {
|
||||
argument.matchType.matches(argumentValue: argumentValue, targetValue: $0)
|
||||
}) {
|
||||
// Found a match, continue to next argument.
|
||||
continue
|
||||
} else {
|
||||
// Did not find a match, exit loop over arguments.
|
||||
matchesArgs = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Return true if all arguments matched
|
||||
if matchesArgs {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively check substructure.
|
||||
// SwiftUI literal Views with modifiers will have a SourceKittenDictionary structure like:
|
||||
// Image("myImage").resizable().accessibility(hidden: true).frame
|
||||
// --> Image("myImage").resizable().accessibility
|
||||
// --> Image("myImage").resizable
|
||||
// --> Image
|
||||
return substructure.contains(where: { $0.hasModifier(anyOf: modifiers, in: file) })
|
||||
}
|
||||
|
||||
// MARK: Sample use cases of `hasModifier` that are used in multiple rules
|
||||
|
||||
/// Whether or not the dictionary represents a SwiftUI View with an `accesibilityHidden(true)`
|
||||
/// or `accessibility(hidden: true)` modifier.
|
||||
func hasAccessibilityHiddenModifier(in file: SwiftLintFile) -> Bool {
|
||||
return hasModifier(
|
||||
anyOf: [
|
||||
SwiftUIModifier(
|
||||
name: "accessibilityHidden",
|
||||
arguments: [.init(name: "", values: ["true"])]
|
||||
),
|
||||
SwiftUIModifier(
|
||||
name: "accessibility",
|
||||
arguments: [.init(name: "hidden", values: ["true"])]
|
||||
)
|
||||
],
|
||||
in: file
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether or not the dictionary represents a SwiftUI View with an `accessibilityElement()` or
|
||||
/// `accessibilityElement(children: .ignore)` modifier (`.ignore` is the default parameter value).
|
||||
func hasAccessibilityElementChildrenIgnoreModifier(in file: SwiftLintFile) -> Bool {
|
||||
return hasModifier(
|
||||
anyOf: [
|
||||
SwiftUIModifier(
|
||||
name: "accessibilityElement",
|
||||
arguments: [.init(name: "children", required: false, values: [".ignore"], matchType: .suffix)]
|
||||
)
|
||||
],
|
||||
in: file
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: Helpers to extract argument values
|
||||
|
||||
/// Helper to get the value of an argument.
|
||||
func getArgumentValue(in file: SwiftLintFile) -> String? {
|
||||
guard expressionKind == .argument, let bodyByteRange else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return file.stringView.substringWithByteRange(bodyByteRange)
|
||||
}
|
||||
|
||||
/// Helper to get the value of a single unnamed argument to a function call.
|
||||
func getSingleUnnamedArgumentValue(in file: SwiftLintFile) -> String? {
|
||||
guard expressionKind == .call, let bodyByteRange else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return file.stringView.substringWithByteRange(bodyByteRange)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
import SwiftSyntax
|
||||
import SwiftSyntaxBuilder
|
||||
|
||||
/// A helper to hold a visitor and rewriter that can lint and correct legacy NS/CG functions to a more modern syntax.
|
||||
enum LegacyFunctionRuleHelper {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let legacyFunctions: [String: RewriteStrategy]
|
||||
|
||||
init(legacyFunctions: [String: RewriteStrategy]) {
|
||||
self.legacyFunctions = legacyFunctions
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if node.isLegacyFunctionExpression(legacyFunctions: legacyFunctions) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RewriteStrategy {
|
||||
case equal
|
||||
case property(name: String)
|
||||
case function(name: String, argumentLabels: [String], reversed: Bool = false)
|
||||
|
||||
var expectedInitialArguments: Int {
|
||||
switch self {
|
||||
case .equal:
|
||||
return 2
|
||||
case .property:
|
||||
return 1
|
||||
case .function(name: _, argumentLabels: let argumentLabels, reversed: _):
|
||||
return argumentLabels.count + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
private let locationConverter: SourceLocationConverter
|
||||
private let disabledRegions: [SourceRange]
|
||||
private let legacyFunctions: [String: RewriteStrategy]
|
||||
|
||||
init(
|
||||
legacyFunctions: [String: RewriteStrategy],
|
||||
locationConverter: SourceLocationConverter,
|
||||
disabledRegions: [SourceRange]
|
||||
) {
|
||||
self.legacyFunctions = legacyFunctions
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
node.isLegacyFunctionExpression(legacyFunctions: legacyFunctions),
|
||||
let funcName = node.calledExpression.as(IdentifierExprSyntax.self)?.identifier.text,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
|
||||
let trimmedArguments = node.argumentList.map { $0.trimmingTrailingComma() }
|
||||
let rewriteStrategy = legacyFunctions[funcName]
|
||||
|
||||
let expr: ExprSyntax
|
||||
switch rewriteStrategy {
|
||||
case .equal:
|
||||
expr = "\(trimmedArguments[0]) == \(trimmedArguments[1])"
|
||||
case let .property(name: propertyName):
|
||||
expr = "\(trimmedArguments[0]).\(raw: propertyName)"
|
||||
case let .function(name: functionName, argumentLabels: argumentLabels, reversed: reversed):
|
||||
let arguments = reversed ? trimmedArguments.reversed() : trimmedArguments
|
||||
let params = zip(argumentLabels, arguments.dropFirst())
|
||||
.map { $0.isEmpty ? "\($1)" : "\($0): \($1)" }
|
||||
.joined(separator: ", ")
|
||||
expr = "\(arguments[0]).\(raw: functionName)(\(raw: params))"
|
||||
case .none:
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
return expr
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
func isLegacyFunctionExpression(legacyFunctions: [String: LegacyFunctionRuleHelper.RewriteStrategy]) -> Bool {
|
||||
guard
|
||||
let calledExpression = calledExpression.as(IdentifierExprSyntax.self),
|
||||
let rewriteStrategy = legacyFunctions[calledExpression.identifier.text],
|
||||
argumentList.count == rewriteStrategy.expectedInitialArguments
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private extension TupleExprElementSyntax {
|
||||
func trimmingTrailingComma() -> TupleExprElementSyntax {
|
||||
self.trimmed.with(\.trailingComma, nil).trimmed
|
||||
}
|
||||
}
|
|
@ -1,13 +1,16 @@
|
|||
// Generated using Sourcery 1.8.2 — https://github.com/krzysztofzablocki/Sourcery
|
||||
// Generated using Sourcery 2.0.2 — https://github.com/krzysztofzablocki/Sourcery
|
||||
// DO NOT EDIT
|
||||
|
||||
/// The rule list containing all available rules built into SwiftLint.
|
||||
public let primaryRuleList = RuleList(rules: [
|
||||
public let builtInRules: [Rule.Type] = [
|
||||
AccessibilityLabelForImageRule.self,
|
||||
AccessibilityTraitForButtonRule.self,
|
||||
AnonymousArgumentInMultilineClosureRule.self,
|
||||
AnyObjectProtocolRule.self,
|
||||
ArrayInitRule.self,
|
||||
AttributesRule.self,
|
||||
BalancedXCTestLifecycleRule.self,
|
||||
BlanketDisableCommandRule.self,
|
||||
BlockBasedKVORule.self,
|
||||
CaptureVariableRule.self,
|
||||
ClassDelegateProtocolRule.self,
|
||||
|
@ -30,9 +33,9 @@ public let primaryRuleList = RuleList(rules: [
|
|||
ContainsOverRangeNilComparisonRule.self,
|
||||
ControlStatementRule.self,
|
||||
ConvenienceTypeRule.self,
|
||||
CustomRules.self,
|
||||
CyclomaticComplexityRule.self,
|
||||
DeploymentTargetRule.self,
|
||||
DirectReturnRule.self,
|
||||
DiscardedNotificationCenterObserverRule.self,
|
||||
DiscouragedAssertRule.self,
|
||||
DiscouragedDirectInitRule.self,
|
||||
|
@ -40,6 +43,7 @@ public let primaryRuleList = RuleList(rules: [
|
|||
DiscouragedObjectLiteralRule.self,
|
||||
DiscouragedOptionalBooleanRule.self,
|
||||
DiscouragedOptionalCollectionRule.self,
|
||||
DuplicateConditionsRule.self,
|
||||
DuplicateEnumCasesRule.self,
|
||||
DuplicateImportsRule.self,
|
||||
DuplicatedKeyInDictionaryLiteralRule.self,
|
||||
|
@ -86,6 +90,7 @@ public let primaryRuleList = RuleList(rules: [
|
|||
InclusiveLanguageRule.self,
|
||||
IndentationWidthRule.self,
|
||||
InertDeferRule.self,
|
||||
InvalidSwiftLintCommandRule.self,
|
||||
IsDisjointRule.self,
|
||||
JoinedDefaultParameterRule.self,
|
||||
LargeTupleRule.self,
|
||||
|
@ -101,7 +106,8 @@ public let primaryRuleList = RuleList(rules: [
|
|||
LegacyRandomRule.self,
|
||||
LetVarWhitespaceRule.self,
|
||||
LineLengthRule.self,
|
||||
LiteralExpressionEndIdentationRule.self,
|
||||
LiteralExpressionEndIndentationRule.self,
|
||||
LocalDocCommentRule.self,
|
||||
LowerACLThanParentRule.self,
|
||||
MarkRule.self,
|
||||
MissingDocsRule.self,
|
||||
|
@ -115,12 +121,14 @@ public let primaryRuleList = RuleList(rules: [
|
|||
MultipleClosuresWithTrailingClosureRule.self,
|
||||
NSLocalizedStringKeyRule.self,
|
||||
NSLocalizedStringRequireBundleRule.self,
|
||||
NSNumberInitAsFunctionReferenceRule.self,
|
||||
NSObjectPreferIsEqualRule.self,
|
||||
NestingRule.self,
|
||||
NimbleOperatorRule.self,
|
||||
NoExtensionAccessModifierRule.self,
|
||||
NoFallthroughOnlyRule.self,
|
||||
NoGroupingExtensionRule.self,
|
||||
NoMagicNumbersRule.self,
|
||||
NoSpaceInMethodCallRule.self,
|
||||
NotificationCenterDetachmentRule.self,
|
||||
NumberSeparatorRule.self,
|
||||
|
@ -133,6 +141,7 @@ public let primaryRuleList = RuleList(rules: [
|
|||
OverriddenSuperCallRule.self,
|
||||
OverrideInExtensionRule.self,
|
||||
PatternMatchingKeywordsRule.self,
|
||||
PeriodSpacingRule.self,
|
||||
PreferNimbleRule.self,
|
||||
PreferSelfInStaticReferencesRule.self,
|
||||
PreferSelfTypeOverTypeOfSelfRule.self,
|
||||
|
@ -156,6 +165,7 @@ public let primaryRuleList = RuleList(rules: [
|
|||
RedundantNilCoalescingRule.self,
|
||||
RedundantObjcAttributeRule.self,
|
||||
RedundantOptionalInitializationRule.self,
|
||||
RedundantSelfInClosureRule.self,
|
||||
RedundantSetAccessControlRule.self,
|
||||
RedundantStringEnumValueRule.self,
|
||||
RedundantTypeAnnotationRule.self,
|
||||
|
@ -164,16 +174,19 @@ public let primaryRuleList = RuleList(rules: [
|
|||
RequiredEnumCaseRule.self,
|
||||
ReturnArrowWhitespaceRule.self,
|
||||
ReturnValueFromVoidFunctionRule.self,
|
||||
SelfBindingRule.self,
|
||||
SelfInPropertyInitializationRule.self,
|
||||
ShorthandOperatorRule.self,
|
||||
ShorthandOptionalBindingRule.self,
|
||||
SingleTestClassRule.self,
|
||||
SortedEnumCasesRule.self,
|
||||
SortedFirstLastRule.self,
|
||||
SortedImportsRule.self,
|
||||
StatementPositionRule.self,
|
||||
StaticOperatorRule.self,
|
||||
StrictFilePrivateRule.self,
|
||||
StrongIBOutletRule.self,
|
||||
SuperfluousDisableCommandRule.self,
|
||||
SuperfluousElseRule.self,
|
||||
SwitchCaseAlignmentRule.self,
|
||||
SwitchCaseOnNewlineRule.self,
|
||||
SyntacticSugarRule.self,
|
||||
|
@ -191,6 +204,7 @@ public let primaryRuleList = RuleList(rules: [
|
|||
TypesafeArrayInitRule.self,
|
||||
UnavailableConditionRule.self,
|
||||
UnavailableFunctionRule.self,
|
||||
UnhandledThrowingTaskRule.self,
|
||||
UnneededBreakInSwitchRule.self,
|
||||
UnneededParenthesesInClosureArgumentRule.self,
|
||||
UnownedVariableCaptureRule.self,
|
||||
|
@ -216,4 +230,4 @@ public let primaryRuleList = RuleList(rules: [
|
|||
XCTFailMessageRule.self,
|
||||
XCTSpecificMatcherRule.self,
|
||||
YodaConditionRule.self
|
||||
] + extraRules())
|
||||
]
|
|
@ -23,7 +23,7 @@ enum ImportUsage {
|
|||
case .unused:
|
||||
return nil
|
||||
case .missing(let module):
|
||||
return "Missing import for referenced module '\(module)'."
|
||||
return "Missing import for referenced module '\(module)'"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct AnonymousArgumentInMultilineClosureRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "anonymous_argument_in_multiline_closure",
|
||||
name: "Anonymous Argument in Multiline Closure",
|
||||
description: "Use named arguments in multiline closures",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("closure { $0 }"),
|
||||
Example("closure { print($0) }"),
|
||||
Example("""
|
||||
closure { arg in
|
||||
print(arg)
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
closure { arg in
|
||||
nestedClosure { $0 + arg }
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
closure {
|
||||
print(↓$0)
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(locationConverter: file.locationConverter)
|
||||
}
|
||||
}
|
||||
|
||||
private extension AnonymousArgumentInMultilineClosureRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let locationConverter: SourceLocationConverter
|
||||
|
||||
init(locationConverter: SourceLocationConverter) {
|
||||
self.locationConverter = locationConverter
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
|
||||
let startLocation = locationConverter.location(for: node.leftBrace.positionAfterSkippingLeadingTrivia)
|
||||
let endLocation = locationConverter.location(for: node.rightBrace.endPositionBeforeTrailingTrivia)
|
||||
return startLocation.line == endLocation.line ? .skipChildren : .visitChildren
|
||||
}
|
||||
|
||||
override func visitPost(_ node: IdentifierExprSyntax) {
|
||||
if case .dollarIdentifier = node.identifier.tokenKind {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct BlockBasedKVORule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "block_based_kvo",
|
||||
name: "Block Based KVO",
|
||||
description: "Prefer the new block based KVO API with keypaths when using Swift 3.2 or later",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example(#"""
|
||||
let observer = foo.observe(\.value, options: [.new]) { (foo, change) in
|
||||
print(change.newValue)
|
||||
}
|
||||
"""#)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
class Foo: NSObject {
|
||||
override ↓func observeValue(forKeyPath keyPath: String?, of object: Any?,
|
||||
change: [NSKeyValueChangeKey : Any]?,
|
||||
context: UnsafeMutableRawPointer?) {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: NSObject {
|
||||
override ↓func observeValue(forKeyPath keyPath: String?, of object: Any?,
|
||||
change: Dictionary<NSKeyValueChangeKey, Any>?,
|
||||
context: UnsafeMutableRawPointer?) {}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension BlockBasedKVORule {
|
||||
private final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
guard node.modifiers.containsOverride,
|
||||
case let parameterList = node.signature.input.parameterList,
|
||||
parameterList.count == 4,
|
||||
node.identifier.text == "observeValue",
|
||||
parameterList.map(\.firstName.text) == ["forKeyPath", "of", "change", "context"]
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
let types = parameterList
|
||||
.map { $0.type.trimmedDescription.replacingOccurrences(of: " ", with: "") }
|
||||
let firstTypes = ["String?", "Any?", "[NSKeyValueChangeKey:Any]?", "UnsafeMutableRawPointer?"]
|
||||
let secondTypes = ["String?", "Any?", "Dictionary<NSKeyValueChangeKey,Any>?", "UnsafeMutableRawPointer?"]
|
||||
if types == firstTypes || types == secondTypes {
|
||||
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,232 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ConvenienceTypeRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "convenience_type",
|
||||
name: "Convenience Type",
|
||||
description: "Types used for hosting only static members should be implemented as a caseless enum " +
|
||||
"to avoid instantiation",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
enum Math { // enum
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
// class with inheritance
|
||||
class MathViewController: UIViewController {
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objc class Math: NSObject { // class visible to Obj-C
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct Math { // type with non-static declarations
|
||||
public static let pi = 3.14
|
||||
public let randomNumber = 2
|
||||
}
|
||||
"""),
|
||||
Example("class DummyClass {}"),
|
||||
Example("""
|
||||
class Foo: NSObject { // class with Obj-C class property
|
||||
class @objc let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: NSObject { // class with Obj-C static property
|
||||
static @objc let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo { // @objc class func can't exist on an enum
|
||||
@objc class func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo { // @objc static func can't exist on an enum
|
||||
@objc static func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers class Foo { // @objc static func can't exist on an enum
|
||||
static func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
final class Foo { // final class, but @objc class func can't exist on an enum
|
||||
@objc class func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
final class Foo { // final class, but @objc static func can't exist on an enum
|
||||
@objc static func foo() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@globalActor actor MyActor {
|
||||
static let shared = MyActor()
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
↓struct Math {
|
||||
public static let pi = 3.14
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓struct Math {
|
||||
public static let pi = 3.14
|
||||
@available(*, unavailable) init() {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
final ↓class Foo { // final class can't be inherited
|
||||
class let foo = 1
|
||||
}
|
||||
"""),
|
||||
|
||||
// Intentional false positives. Non-final classes could be
|
||||
// subclassed, but we figure it is probably rare enough that it is
|
||||
// more important to catch these cases, and manually disable the
|
||||
// rule if needed.
|
||||
|
||||
Example("""
|
||||
↓class Foo {
|
||||
class let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓class Foo {
|
||||
final class let foo = 1
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
↓class SomeClass {
|
||||
static func foo() {}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ConvenienceTypeRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ProtocolDeclSyntax.self] }
|
||||
|
||||
override func visitPost(_ node: StructDeclSyntax) {
|
||||
if hasViolation(
|
||||
inheritance: node.inheritanceClause,
|
||||
attributes: node.attributes,
|
||||
members: node.memberBlock
|
||||
) {
|
||||
violations.append(node.structKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ClassDeclSyntax) {
|
||||
if hasViolation(
|
||||
inheritance: node.inheritanceClause,
|
||||
attributes: node.attributes,
|
||||
members: node.memberBlock
|
||||
) {
|
||||
violations.append(node.classKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
private func hasViolation(inheritance: TypeInheritanceClauseSyntax?,
|
||||
attributes: AttributeListSyntax?,
|
||||
members: MemberDeclBlockSyntax) -> Bool {
|
||||
guard inheritance.isNilOrEmpty,
|
||||
!attributes.containsObjcMembers,
|
||||
!attributes.containsObjc,
|
||||
!members.members.isEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
return ConvenienceTypeCheckVisitor(viewMode: .sourceAccurate)
|
||||
.walk(tree: members, handler: \.canBeConvenienceType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class ConvenienceTypeCheckVisitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { .all }
|
||||
|
||||
private(set) var canBeConvenienceType = true
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
if node.isInstanceVariable {
|
||||
canBeConvenienceType = false
|
||||
} else if node.attributes.containsObjc {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
if node.modifiers.containsStaticOrClass {
|
||||
if node.attributes.containsObjc {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
} else {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: InitializerDeclSyntax) {
|
||||
if !node.attributes.hasUnavailableAttribute {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: SubscriptDeclSyntax) {
|
||||
if !node.modifiers.containsStaticOrClass {
|
||||
canBeConvenienceType = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TypeInheritanceClauseSyntax? {
|
||||
var isNilOrEmpty: Bool {
|
||||
self?.inheritedTypeCollection.isEmpty ?? true
|
||||
}
|
||||
}
|
||||
|
||||
private extension AttributeListSyntax? {
|
||||
var containsObjcMembers: Bool {
|
||||
contains(attributeNamed: "objcMembers")
|
||||
}
|
||||
|
||||
var containsObjc: Bool {
|
||||
contains(attributeNamed: "objc")
|
||||
}
|
||||
}
|
||||
|
||||
private extension AttributeListSyntax? {
|
||||
var hasUnavailableAttribute: Bool {
|
||||
guard let attrs = self else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attrs.contains { elem in
|
||||
guard let attr = elem.as(AttributeSyntax.self),
|
||||
let arguments = attr.argument?.as(AvailabilitySpecListSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attr.attributeNameText == "available" && arguments.contains { arg in
|
||||
arg.entry.as(TokenSyntax.self)?.tokenKind.isUnavailableKeyword == true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedAssertRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_assert",
|
||||
name: "Discouraged Assert",
|
||||
description: "Prefer `assertionFailure()` and/or `preconditionFailure()` over `assert(false)`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example(#"assert(true)"#),
|
||||
Example(#"assert(true, "foobar")"#),
|
||||
Example(#"assert(true, "foobar", file: "toto", line: 42)"#),
|
||||
Example(#"assert(false || true)"#),
|
||||
Example(#"XCTAssert(false)"#)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example(#"↓assert(false)"#),
|
||||
Example(#"↓assert(false, "foobar")"#),
|
||||
Example(#"↓assert(false, "foobar", file: "toto", line: 42)"#),
|
||||
Example(#"↓assert( false , "foobar")"#)
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedAssertRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard node.calledExpression.as(IdentifierExprSyntax.self)?.identifier.text == "assert",
|
||||
let firstArg = node.argumentList.first,
|
||||
firstArg.label == nil,
|
||||
let boolExpr = firstArg.expression.as(BooleanLiteralExprSyntax.self),
|
||||
boolExpr.booleanLiteral.tokenKind == .keyword(.false) else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,11 +1,13 @@
|
|||
import SourceKittenFramework
|
||||
import SwiftSyntax
|
||||
|
||||
public struct DiscouragedNoneNameRule: ASTRule, OptInRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
public static var description = RuleDescription(
|
||||
struct DiscouragedNoneNameRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static var description = RuleDescription(
|
||||
identifier: "discouraged_none_name",
|
||||
name: "Discouraged None Name",
|
||||
description: "Discourages name cases/static members `none`, which can conflict with `Optional<T>.none`.",
|
||||
description: "Enum cases and static members named `none` are discouraged as they can conflict with " +
|
||||
"`Optional<T>.none`.",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
// Should not trigger unless exactly matches "none"
|
||||
|
@ -175,43 +177,61 @@ public struct DiscouragedNoneNameRule: ASTRule, OptInRule, ConfigurationProvider
|
|||
]
|
||||
)
|
||||
|
||||
public func validate(
|
||||
file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary
|
||||
) -> [StyleViolation] {
|
||||
guard kind.isForValidating && dictionary.isNameInvalid, let offset = dictionary.offset else { return [] }
|
||||
return [
|
||||
StyleViolation(
|
||||
ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: offset),
|
||||
reason: kind.reason
|
||||
)
|
||||
]
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
public init() {}
|
||||
}
|
||||
|
||||
private extension SwiftDeclarationKind {
|
||||
var isForValidating: Bool { self == .enumelement || self == .varClass || self == .varStatic }
|
||||
|
||||
var reason: String {
|
||||
var reasonPrefix: String {
|
||||
switch self {
|
||||
case .enumelement: return "`case`"
|
||||
case .varClass: return "`class` member"
|
||||
case .varStatic: return "`static` member"
|
||||
default: return ""
|
||||
private extension DiscouragedNoneNameRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: EnumCaseElementSyntax) {
|
||||
let emptyParams = node.associatedValue?.parameterList.isEmpty ?? true
|
||||
if emptyParams, node.identifier.isNone {
|
||||
violations.append(ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: reason(type: "`case`")
|
||||
))
|
||||
}
|
||||
}
|
||||
let reason = "Avoid naming \(reasonPrefix) `none` as the compiler can think you mean `Optional<T>.none`."
|
||||
let recommendation = "Consider using an Optional value instead."
|
||||
return "\(reason) \(recommendation)"
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
let type: String? = {
|
||||
if node.modifiers.isClass {
|
||||
return "`class` member"
|
||||
} else if node.modifiers.isStatic {
|
||||
return "`static` member"
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}()
|
||||
|
||||
guard let type else {
|
||||
return
|
||||
}
|
||||
|
||||
for binding in node.bindings {
|
||||
guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self), pattern.identifier.isNone else {
|
||||
continue
|
||||
}
|
||||
|
||||
violations.append(ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: reason(type: type)
|
||||
))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func reason(type: String) -> String {
|
||||
let reason = "Avoid naming \(type) `none` as the compiler can think you mean `Optional<T>.none`"
|
||||
let recommendation = "consider using an Optional value instead"
|
||||
return "\(reason); \(recommendation)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension SourceKittenDictionary {
|
||||
var isNameInvalid: Bool { name == "none" }
|
||||
private extension TokenSyntax {
|
||||
var isNone: Bool {
|
||||
tokenKind == .identifier("none") || tokenKind == .identifier("`none`")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedObjectLiteralRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = DiscouragedObjectLiteralConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_object_literal",
|
||||
name: "Discouraged Object Literal",
|
||||
description: "Prefer initializers over object literals",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("let image = UIImage(named: aVariable)"),
|
||||
Example("let image = UIImage(named: \"interpolated \\(variable)\")"),
|
||||
Example("let color = UIColor(red: value, green: value, blue: value, alpha: 1)"),
|
||||
Example("let image = NSImage(named: aVariable)"),
|
||||
Example("let image = NSImage(named: \"interpolated \\(variable)\")"),
|
||||
Example("let color = NSColor(red: value, green: value, blue: value, alpha: 1)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let image = ↓#imageLiteral(resourceName: \"image.jpg\")"),
|
||||
Example("let color = ↓#colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedObjectLiteralRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let configuration: ConfigurationType
|
||||
|
||||
init(configuration: ConfigurationType) {
|
||||
self.configuration = configuration
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: MacroExpansionExprSyntax) {
|
||||
guard
|
||||
case let .identifier(identifierText) = node.macro.tokenKind,
|
||||
["colorLiteral", "imageLiteral"].contains(identifierText)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
if !configuration.imageLiteral && identifierText == "imageLiteral" {
|
||||
return
|
||||
}
|
||||
|
||||
if !configuration.colorLiteral && identifierText == "colorLiteral" {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct DiscouragedOptionalBooleanRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_optional_boolean",
|
||||
name: "Discouraged Optional Boolean",
|
||||
description: "Prefer non-optional booleans over optional booleans",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: DiscouragedOptionalBooleanRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: DiscouragedOptionalBooleanRuleExamples.triggeringExamples
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension DiscouragedOptionalBooleanRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: OptionalTypeSyntax) {
|
||||
if node.wrappedType.as(SimpleTypeIdentifierSyntax.self)?.typeName == "Bool" {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: OptionalChainingExprSyntax) {
|
||||
if node.expression.as(IdentifierExprSyntax.self)?.identifier.text == "Bool" {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard
|
||||
let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
let singleArgument = node.argumentList.onlyElement,
|
||||
singleArgument.expression.is(BooleanLiteralExprSyntax.self),
|
||||
let base = calledExpression.base?.as(IdentifierExprSyntax.self),
|
||||
base.identifier.text == "Optional",
|
||||
calledExpression.name.text == "some"
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -154,7 +154,10 @@ internal struct DiscouragedOptionalBooleanRuleExamples {
|
|||
wrapExample("enum", "func foo(input: [↓Bool?]) {}"),
|
||||
wrapExample("enum", "static func foo(input: ↓Bool?) {}"),
|
||||
wrapExample("enum", "static func foo(input: [String: ↓Bool?]) {}"),
|
||||
wrapExample("enum", "static func foo(input: [↓Bool?]) {}")
|
||||
wrapExample("enum", "static func foo(input: [↓Bool?]) {}"),
|
||||
|
||||
// Optional chaining
|
||||
Example("_ = ↓Bool?.values()")
|
||||
]
|
||||
}
|
||||
|
|
@ -1,23 +1,21 @@
|
|||
import SourceKittenFramework
|
||||
|
||||
public struct DiscouragedOptionalCollectionRule: ASTRule, OptInRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct DiscouragedOptionalCollectionRule: ASTRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "discouraged_optional_collection",
|
||||
name: "Discouraged Optional Collection",
|
||||
description: "Prefer empty collection over optional collection.",
|
||||
description: "Prefer empty collection over optional collection",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: DiscouragedOptionalCollectionExamples.nonTriggeringExamples,
|
||||
triggeringExamples: DiscouragedOptionalCollectionExamples.triggeringExamples
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
let offsets = variableViolations(file: file, kind: kind, dictionary: dictionary) +
|
||||
func validate(file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
let offsets = variableViolations(kind: kind, dictionary: dictionary) +
|
||||
functionViolations(file: file, kind: kind, dictionary: dictionary)
|
||||
|
||||
return offsets.map {
|
||||
|
@ -29,9 +27,7 @@ public struct DiscouragedOptionalCollectionRule: ASTRule, OptInRule, Configurati
|
|||
|
||||
// MARK: - Private
|
||||
|
||||
private func variableViolations(file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [ByteCount] {
|
||||
private func variableViolations(kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [ByteCount] {
|
||||
guard
|
||||
SwiftDeclarationKind.variableKinds.contains(kind),
|
||||
let offset = dictionary.offset,
|
|
@ -1,8 +1,8 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
public struct DuplicateImportsRule: ConfigurationProviderRule, CorrectableRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct DuplicateImportsRule: ConfigurationProviderRule, CorrectableRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
// List of all possible import kinds
|
||||
static let importKinds = [
|
||||
|
@ -11,12 +11,10 @@ public struct DuplicateImportsRule: ConfigurationProviderRule, CorrectableRule {
|
|||
"var", "func"
|
||||
]
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "duplicate_imports",
|
||||
name: "Duplicate Imports",
|
||||
description: "Imports should be unique.",
|
||||
description: "Imports should be unique",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: DuplicateImportsRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: DuplicateImportsRuleExamples.triggeringExamples,
|
||||
|
@ -132,7 +130,7 @@ public struct DuplicateImportsRule: ConfigurationProviderRule, CorrectableRule {
|
|||
})
|
||||
}
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
return duplicateImports(file: file).map { duplicateImport in
|
||||
StyleViolation(
|
||||
ruleDescription: Self.description,
|
||||
|
@ -142,7 +140,7 @@ public struct DuplicateImportsRule: ConfigurationProviderRule, CorrectableRule {
|
|||
}
|
||||
}
|
||||
|
||||
public func correct(file: SwiftLintFile) -> [Correction] {
|
||||
func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let duplicateImports = duplicateImports(file: file).reversed().filter {
|
||||
file.ruleEnabled(violatingRange: $0.range, for: self) != nil
|
||||
}
|
||||
|
@ -194,7 +192,7 @@ private extension Line {
|
|||
|
||||
/// For "import A.B.C" returns slices [["A", "B", "C"], ["A", "B"], ["A"]]
|
||||
var importSlices: [ImportSlice] {
|
||||
guard let importIdentifier = importIdentifier else { return [] }
|
||||
guard let importIdentifier else { return [] }
|
||||
|
||||
let importedSubpathParts = importIdentifier.split(separator: ".").map { String($0) }
|
||||
guard !importedSubpathParts.isEmpty else { return [] }
|
|
@ -1,4 +1,3 @@
|
|||
// swiftlint:disable type_body_length
|
||||
internal struct DuplicateImportsRuleExamples {
|
||||
static let nonTriggeringExamples = [
|
||||
Example("""
|
||||
|
@ -36,7 +35,7 @@ internal struct DuplicateImportsRuleExamples {
|
|||
""")
|
||||
]
|
||||
|
||||
static let triggeringExamples = Array(corrections.keys)
|
||||
static let triggeringExamples = Array(corrections.keys.sorted())
|
||||
|
||||
static let corrections: [Example: Example] = {
|
||||
var corrections = [
|
|
@ -3,15 +3,13 @@ import SourceKittenFramework
|
|||
|
||||
private typealias SourceKittenElement = SourceKittenDictionary
|
||||
|
||||
public struct ExplicitACLRule: OptInRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct ExplicitACLRule: OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_acl",
|
||||
name: "Explicit ACL",
|
||||
description: "All declarations should specify Access Control Level keywords explicitly.",
|
||||
description: "All declarations should specify Access Control Level keywords explicitly",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("internal enum A {}\n"),
|
||||
|
@ -122,7 +120,7 @@ public struct ExplicitACLRule: OptInRule, ConfigurationProviderRule {
|
|||
}
|
||||
}
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let implicitAndExplicitInternalElements = internalTypeElements(in: file.structureDictionary)
|
||||
|
||||
guard implicitAndExplicitInternalElements.isNotEmpty else {
|
||||
|
@ -188,7 +186,7 @@ private extension SwiftDeclarationKind {
|
|||
.functionMethodInstance, .functionMethodStatic, .functionOperator, .functionOperatorInfix,
|
||||
.functionOperatorPostfix, .functionOperatorPrefix, .functionSubscript, .protocol, .opaqueType:
|
||||
return true
|
||||
case .class, .enum, .extension, .extensionClass, .extensionEnum,
|
||||
case .actor, .class, .enum, .extension, .extensionClass, .extensionEnum,
|
||||
.extensionProtocol, .extensionStruct, .struct:
|
||||
return false
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ExplicitEnumRawValueRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_enum_raw_value",
|
||||
name: "Explicit Enum Raw Value",
|
||||
description: "Enums should be explicitly assigned their raw values",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
enum Numbers {
|
||||
case int(Int)
|
||||
case short(Int16)
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Int {
|
||||
case one = 1
|
||||
case two = 2
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Double {
|
||||
case one = 1.1
|
||||
case two = 2.2
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one = "one"
|
||||
case two = "two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
protocol Algebra {}
|
||||
enum Numbers: Algebra {
|
||||
case one
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
enum Numbers: Int {
|
||||
case one = 10, ↓two, three = 30
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: NSInteger {
|
||||
case ↓one
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case ↓one
|
||||
case ↓two
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case ↓one, two = "two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Decimal {
|
||||
case ↓one, ↓two
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Outer {
|
||||
enum Numbers: Decimal {
|
||||
case ↓one, ↓two
|
||||
}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExplicitEnumRawValueRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ProtocolDeclSyntax.self] }
|
||||
|
||||
override func visitPost(_ node: EnumCaseElementSyntax) {
|
||||
if node.rawValue == nil, node.enclosingEnum()?.supportsRawValues == true {
|
||||
violations.append(node.identifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension SyntaxProtocol {
|
||||
func enclosingEnum() -> EnumDeclSyntax? {
|
||||
if let node = self.as(EnumDeclSyntax.self) {
|
||||
return node
|
||||
}
|
||||
|
||||
return parent?.enclosingEnum()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,254 @@
|
|||
import SwiftSyntax
|
||||
import SwiftSyntaxBuilder
|
||||
|
||||
struct ExplicitInitRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_init",
|
||||
name: "Explicit Init",
|
||||
description: "Explicitly calling .init() should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
import Foundation
|
||||
class C: NSObject {
|
||||
override init() {
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
"""), // super
|
||||
Example("""
|
||||
struct S {
|
||||
let n: Int
|
||||
}
|
||||
extension S {
|
||||
init() {
|
||||
self.init(n: 1)
|
||||
}
|
||||
}
|
||||
"""), // self
|
||||
Example("""
|
||||
[1].flatMap(String.init)
|
||||
"""), // pass init as closure
|
||||
Example("""
|
||||
[String.self].map { $0.init(1) }
|
||||
"""), // initialize from a metatype value
|
||||
Example("""
|
||||
[String.self].map { type in type.init(1) }
|
||||
"""), // initialize from a metatype value
|
||||
Example("""
|
||||
Observable.zip(obs1, obs2, resultSelector: MyType.init).asMaybe()
|
||||
"""),
|
||||
Example("_ = GleanMetrics.Tabs.someType.init()"),
|
||||
Example("""
|
||||
Observable.zip(
|
||||
obs1,
|
||||
obs2,
|
||||
resultSelector: MyType.init
|
||||
).asMaybe()
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
[1].flatMap{String↓.init($0)}
|
||||
"""),
|
||||
Example("""
|
||||
[String.self].map { Type in Type↓.init(1) }
|
||||
"""), // Starting with capital letter assumes a type
|
||||
Example("""
|
||||
func foo() -> [String] {
|
||||
return [1].flatMap { String↓.init($0) }
|
||||
}
|
||||
"""),
|
||||
Example("_ = GleanMetrics.Tabs.GroupedTabExtra↓.init()"),
|
||||
Example("_ = Set<KsApi.Category>↓.init()"),
|
||||
Example("""
|
||||
Observable.zip(
|
||||
obs1,
|
||||
obs2,
|
||||
resultSelector: { MyType↓.init($0, $1) }
|
||||
).asMaybe()
|
||||
"""),
|
||||
Example("""
|
||||
let int = In🤓t↓
|
||||
.init(1.0)
|
||||
""", excludeFromDocumentation: true),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
""", excludeFromDocumentation: true),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
""", excludeFromDocumentation: true)
|
||||
],
|
||||
corrections: [
|
||||
Example("""
|
||||
[1].flatMap{String↓.init($0)}
|
||||
"""):
|
||||
Example("""
|
||||
[1].flatMap{String($0)}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() -> [String] {
|
||||
return [1].flatMap { String↓.init($0) }
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
func foo() -> [String] {
|
||||
return [1].flatMap { String($0) }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class C {
|
||||
#if true
|
||||
func f() {
|
||||
[1].flatMap{String↓.init($0)}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
class C {
|
||||
#if true
|
||||
func f() {
|
||||
[1].flatMap{String($0)}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
.init(1.0)
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
"""),
|
||||
Example("""
|
||||
let int = Int↓
|
||||
|
||||
|
||||
.init(1.0)
|
||||
|
||||
|
||||
|
||||
"""):
|
||||
Example("""
|
||||
let int = Int(1.0)
|
||||
|
||||
|
||||
|
||||
"""),
|
||||
Example("_ = GleanMetrics.Tabs.GroupedTabExtra↓.init()"):
|
||||
Example("_ = GleanMetrics.Tabs.GroupedTabExtra()"),
|
||||
Example("_ = Set<KsApi.Category>↓.init()"):
|
||||
Example("_ = Set<KsApi.Category>()")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExplicitInitRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard
|
||||
let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
let violationPosition = calledExpression.explicitInitPosition
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(violationPosition)
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
let calledExpression = node.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
let violationPosition = calledExpression.explicitInitPosition,
|
||||
let calledBase = calledExpression.base,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(violationPosition)
|
||||
let newNode = node.with(\.calledExpression, calledBase.trimmed)
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension MemberAccessExprSyntax {
|
||||
var explicitInitPosition: AbsolutePosition? {
|
||||
if let base, base.isTypeReferenceLike, name.text == "init" {
|
||||
return base.endPositionBeforeTrailingTrivia
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExprSyntax {
|
||||
/// `String` or `Nested.Type`.
|
||||
var isTypeReferenceLike: Bool {
|
||||
if let expr = self.as(IdentifierExprSyntax.self), expr.identifier.text.startsWithUppercase {
|
||||
return true
|
||||
} else if let expr = self.as(MemberAccessExprSyntax.self),
|
||||
expr.description.split(separator: ".").allSatisfy(\.startsWithUppercase) {
|
||||
return true
|
||||
} else if let expr = self.as(SpecializeExprSyntax.self)?.expression.as(IdentifierExprSyntax.self),
|
||||
expr.identifier.text.startsWithUppercase {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension StringProtocol {
|
||||
var startsWithUppercase: Bool { first?.isUppercase == true }
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ExplicitTopLevelACLRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_top_level_acl",
|
||||
name: "Explicit Top Level ACL",
|
||||
description: "Top-level declarations should specify Access Control Level keywords explicitly",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("internal enum A {}\n"),
|
||||
Example("public final class B {}\n"),
|
||||
Example("private struct C {}\n"),
|
||||
Example("internal enum A {\n enum B {}\n}"),
|
||||
Example("internal final class Foo {}"),
|
||||
Example("internal\nclass Foo {}"),
|
||||
Example("internal func a() {}\n"),
|
||||
Example("extension A: Equatable {}"),
|
||||
Example("extension A {}")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓enum A {}\n"),
|
||||
Example("final ↓class B {}\n"),
|
||||
Example("↓struct C {}\n"),
|
||||
Example("↓func a() {}\n"),
|
||||
Example("internal let a = 0\n↓func b() {}\n")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExplicitTopLevelACLRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { .all }
|
||||
|
||||
override func visitPost(_ node: ClassDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.classKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: StructDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.structKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: EnumDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.enumKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ProtocolDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.protocolKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ActorDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.actorKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: TypealiasDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.typealiasKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
if hasViolation(modifiers: node.modifiers) {
|
||||
violations.append(node.bindingKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visit(_ node: CodeBlockSyntax) -> SyntaxVisitorContinueKind {
|
||||
.skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
|
||||
.skipChildren
|
||||
}
|
||||
|
||||
private func hasViolation(modifiers: ModifierListSyntax?) -> Bool {
|
||||
guard let modifiers else {
|
||||
return true
|
||||
}
|
||||
|
||||
return !modifiers.contains(where: \.isACLModifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension DeclModifierSyntax {
|
||||
var isACLModifier: Bool {
|
||||
let aclModifiers: Set<TokenKind> = [
|
||||
.keyword(.private),
|
||||
.keyword(.fileprivate),
|
||||
.keyword(.internal),
|
||||
.keyword(.public),
|
||||
.keyword(.open)
|
||||
]
|
||||
|
||||
return detail == nil && aclModifiers.contains(name.tokenKind)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,142 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ExplicitTypeInterfaceRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = ExplicitTypeInterfaceConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "explicit_type_interface",
|
||||
name: "Explicit Type Interface",
|
||||
description: "Properties should have a type interface",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
class Foo {
|
||||
var myVar: Int? = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let myVar: Int? = 0, s: String = ""
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
static var myVar: Int? = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
class var myVar: Int? = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func f() {
|
||||
if case .failure(let error) = errorCompletion {}
|
||||
}
|
||||
""", excludeFromDocumentation: true)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
class Foo {
|
||||
var ↓myVar = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let ↓mylet = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
static var ↓myStaticVar = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
class var ↓myClassVar = 0
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let ↓myVar = Int(0), ↓s = ""
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo {
|
||||
let ↓myVar = Set<Int>(0)
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
private class Visitor: ViolationsSyntaxVisitor {
|
||||
let configuration: ExplicitTypeInterfaceConfiguration
|
||||
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ProtocolDeclSyntax.self] }
|
||||
|
||||
init(configuration: ExplicitTypeInterfaceConfiguration) {
|
||||
self.configuration = configuration
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
if node.modifiers.isClass {
|
||||
if configuration.allowedKinds.contains(.class) {
|
||||
checkViolation(node)
|
||||
}
|
||||
} else if node.modifiers.isStatic {
|
||||
if configuration.allowedKinds.contains(.static) {
|
||||
checkViolation(node)
|
||||
}
|
||||
} else if node.parent?.is(MemberDeclListItemSyntax.self) == true {
|
||||
if configuration.allowedKinds.contains(.instance) {
|
||||
checkViolation(node)
|
||||
}
|
||||
} else if node.parent?.is(CodeBlockItemSyntax.self) == true {
|
||||
if configuration.allowedKinds.contains(.local) {
|
||||
checkViolation(node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func checkViolation(_ node: VariableDeclSyntax) {
|
||||
for binding in node.bindings {
|
||||
if configuration.allowRedundancy, let initializer = binding.initializer,
|
||||
initializer.isTypeConstructor || initializer.isTypeReference {
|
||||
continue
|
||||
}
|
||||
if binding.typeAnnotation == nil {
|
||||
violations.append(binding.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension InitializerClauseSyntax {
|
||||
var isTypeConstructor: Bool {
|
||||
if value.as(FunctionCallExprSyntax.self)?.callsPotentialType == true {
|
||||
return true
|
||||
}
|
||||
if let tryExpr = value.as(TryExprSyntax.self),
|
||||
tryExpr.expression.as(FunctionCallExprSyntax.self)?.callsPotentialType == true {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var isTypeReference: Bool {
|
||||
value.as(MemberAccessExprSyntax.self)?.name.tokenKind == .keyword(.self)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var callsPotentialType: Bool {
|
||||
let name = calledExpression.debugDescription
|
||||
return name.first?.isUppercase == true || (name.first == "[" && name.last == "]")
|
||||
}
|
||||
}
|
|
@ -1,12 +1,10 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
public struct ExtensionAccessModifierRule: ASTRule, ConfigurationProviderRule, OptInRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct ExtensionAccessModifierRule: ASTRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "extension_access_modifier",
|
||||
name: "Extension Access Modifier",
|
||||
description: "Prefer to use extension access modifiers",
|
||||
|
@ -92,8 +90,8 @@ public struct ExtensionAccessModifierRule: ASTRule, ConfigurationProviderRule, O
|
|||
]
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
guard kind == .extension, let offset = dictionary.offset,
|
||||
dictionary.inheritedTypes.isEmpty
|
||||
else {
|
||||
|
@ -157,9 +155,7 @@ public struct ExtensionAccessModifierRule: ASTRule, ConfigurationProviderRule, O
|
|||
// attributeBuiltin (`final` for example) tokens between them
|
||||
let length = typeOffset - previousInternalByteRange.location
|
||||
let range = ByteRange(location: previousInternalByteRange.location, length: length)
|
||||
let internalBelongsToType = Set(file.syntaxMap.kinds(inByteRange: range)) == [.attributeBuiltin]
|
||||
|
||||
return internalBelongsToType
|
||||
return Set(file.syntaxMap.kinds(inByteRange: range)) == [.attributeBuiltin]
|
||||
}
|
||||
|
||||
return violationOffsets.map {
|
|
@ -0,0 +1,42 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FallthroughRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "fallthrough",
|
||||
name: "Fallthrough",
|
||||
description: "Fallthrough should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
switch foo {
|
||||
case .bar, .bar2, .bar3:
|
||||
something()
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
switch foo {
|
||||
case .bar:
|
||||
↓fallthrough
|
||||
case .bar2:
|
||||
something()
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FallthroughRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FallthroughStmtSyntax) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FatalErrorMessageRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "fatal_error_message",
|
||||
name: "Fatal Error Message",
|
||||
description: "A fatalError call should have a message",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
func foo() {
|
||||
fatalError("Foo")
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() {
|
||||
fatalError(x)
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
func foo() {
|
||||
↓fatalError("")
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() {
|
||||
↓fatalError()
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FatalErrorMessageRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard let expression = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
expression.identifier.text == "fatalError",
|
||||
node.argumentList.isEmptyOrEmptyString else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TupleExprElementListSyntax {
|
||||
var isEmptyOrEmptyString: Bool {
|
||||
if isEmpty {
|
||||
return true
|
||||
}
|
||||
return count == 1 && first?.expression.as(StringLiteralExprSyntax.self)?.isEmptyString == true
|
||||
}
|
||||
}
|
|
@ -1,22 +1,17 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
public struct FileNameNoSpaceRule: ConfigurationProviderRule, OptInRule {
|
||||
public var configuration = FileNameNoSpaceConfiguration(
|
||||
severity: .warning,
|
||||
excluded: []
|
||||
)
|
||||
struct FileNameNoSpaceRule: ConfigurationProviderRule, OptInRule, SourceKitFreeRule {
|
||||
var configuration = FileNameNoSpaceConfiguration()
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "file_name_no_space",
|
||||
name: "File Name No Space",
|
||||
description: "File name should not contain any whitespace.",
|
||||
name: "File Name no Space",
|
||||
description: "File name should not contain any whitespace",
|
||||
kind: .idiomatic
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
guard let filePath = file.path,
|
||||
case let fileName = filePath.bridge().lastPathComponent,
|
||||
!configuration.excluded.contains(fileName),
|
||||
|
@ -25,7 +20,7 @@ public struct FileNameNoSpaceRule: ConfigurationProviderRule, OptInRule {
|
|||
}
|
||||
|
||||
return [StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity.severity,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: filePath, line: 1))]
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FileNameRule: ConfigurationProviderRule, OptInRule, SourceKitFreeRule {
|
||||
var configuration = FileNameConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "file_name",
|
||||
name: "File Name",
|
||||
description: "File name should match a type or extension declared in the file (if any)",
|
||||
kind: .idiomatic
|
||||
)
|
||||
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
guard let filePath = file.path,
|
||||
case let fileName = filePath.bridge().lastPathComponent,
|
||||
!configuration.excluded.contains(fileName) else {
|
||||
return []
|
||||
}
|
||||
|
||||
let prefixRegex = regex("\\A(?:\(configuration.prefixPattern))")
|
||||
let suffixRegex = regex("(?:\(configuration.suffixPattern))\\z")
|
||||
|
||||
var typeInFileName = fileName.bridge().deletingPathExtension
|
||||
|
||||
// Process prefix
|
||||
if let match = prefixRegex.firstMatch(in: typeInFileName, options: [], range: typeInFileName.fullNSRange),
|
||||
let range = typeInFileName.nsrangeToIndexRange(match.range) {
|
||||
typeInFileName.removeSubrange(range)
|
||||
}
|
||||
|
||||
// Process suffix
|
||||
if let match = suffixRegex.firstMatch(in: typeInFileName, options: [], range: typeInFileName.fullNSRange),
|
||||
let range = typeInFileName.nsrangeToIndexRange(match.range) {
|
||||
typeInFileName.removeSubrange(range)
|
||||
}
|
||||
|
||||
// Process nested type separator
|
||||
let allDeclaredTypeNames = TypeNameCollectingVisitor(viewMode: .sourceAccurate)
|
||||
.walk(tree: file.syntaxTree, handler: \.names)
|
||||
.map {
|
||||
$0.replacingOccurrences(of: ".", with: configuration.nestedTypeSeparator)
|
||||
}
|
||||
|
||||
guard allDeclaredTypeNames.isNotEmpty, !allDeclaredTypeNames.contains(typeInFileName) else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: filePath, line: 1))]
|
||||
}
|
||||
}
|
||||
|
||||
private class TypeNameCollectingVisitor: SyntaxVisitor {
|
||||
private(set) var names: Set<String> = []
|
||||
|
||||
override func visitPost(_ node: ClassDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ActorDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: StructDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: TypealiasDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: EnumDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ProtocolDeclSyntax) {
|
||||
names.insert(node.identifier.text)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ExtensionDeclSyntax) {
|
||||
names.insert(node.extendedType.trimmedDescription)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,189 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForWhereRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = ForWhereConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "for_where",
|
||||
name: "Prefer For-Where",
|
||||
description: "`where` clauses are preferred over a single `if` inside a `for`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
for user in users where user.id == 1 { }
|
||||
"""),
|
||||
// if let
|
||||
Example("""
|
||||
for user in users {
|
||||
if let id = user.id { }
|
||||
}
|
||||
"""),
|
||||
// if var
|
||||
Example("""
|
||||
for user in users {
|
||||
if var id = user.id { }
|
||||
}
|
||||
"""),
|
||||
// if with else
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { } else { }
|
||||
}
|
||||
"""),
|
||||
// if with else if
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 {
|
||||
} else if user.id == 2 { }
|
||||
}
|
||||
"""),
|
||||
// if is not the only expression inside for
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { }
|
||||
print(user)
|
||||
}
|
||||
"""),
|
||||
// if a variable is used
|
||||
Example("""
|
||||
for user in users {
|
||||
let id = user.id
|
||||
if id == 1 { }
|
||||
}
|
||||
"""),
|
||||
// if something is after if
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { }
|
||||
return true
|
||||
}
|
||||
"""),
|
||||
// condition with multiple clauses
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 && user.age > 18 { }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1, user.age > 18 { }
|
||||
}
|
||||
"""),
|
||||
// if case
|
||||
Example("""
|
||||
for (index, value) in array.enumerated() {
|
||||
if case .valueB(_) = value {
|
||||
return index
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 { return true }
|
||||
}
|
||||
""", configuration: ["allow_for_as_filter": true]),
|
||||
Example("""
|
||||
for user in users {
|
||||
if user.id == 1 {
|
||||
let derivedValue = calculateValue(from: user)
|
||||
return derivedValue != 0
|
||||
}
|
||||
}
|
||||
""", configuration: ["allow_for_as_filter": true])
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
for user in users {
|
||||
↓if user.id == 1 { return true }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for subview in subviews {
|
||||
↓if !(subview is UIStackView) {
|
||||
subview.removeConstraints(subview.constraints)
|
||||
subview.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
for subview in subviews {
|
||||
↓if !(subview is UIStackView) {
|
||||
subview.removeConstraints(subview.constraints)
|
||||
subview.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
""", configuration: ["allow_for_as_filter": true])
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(allowForAsFilter: configuration.allowForAsFilter)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ForWhereRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let allowForAsFilter: Bool
|
||||
|
||||
init(allowForAsFilter: Bool) {
|
||||
self.allowForAsFilter = allowForAsFilter
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ForInStmtSyntax) {
|
||||
guard node.whereClause == nil,
|
||||
let onlyExprStmt = node.body.statements.onlyElement?.item.as(ExpressionStmtSyntax.self),
|
||||
let ifExpr = onlyExprStmt.expression.as(IfExprSyntax.self),
|
||||
ifExpr.elseBody == nil,
|
||||
!ifExpr.containsOptionalBinding,
|
||||
!ifExpr.containsPatternCondition,
|
||||
let condition = ifExpr.conditions.onlyElement,
|
||||
!condition.containsMultipleConditions else {
|
||||
return
|
||||
}
|
||||
|
||||
if allowForAsFilter, ifExpr.containsReturnStatement {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(ifExpr.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension IfExprSyntax {
|
||||
var containsOptionalBinding: Bool {
|
||||
conditions.contains { element in
|
||||
element.condition.is(OptionalBindingConditionSyntax.self)
|
||||
}
|
||||
}
|
||||
|
||||
var containsPatternCondition: Bool {
|
||||
conditions.contains { element in
|
||||
element.condition.is(MatchingPatternConditionSyntax.self)
|
||||
}
|
||||
}
|
||||
|
||||
var containsReturnStatement: Bool {
|
||||
body.statements.contains { element in
|
||||
element.item.is(ReturnStmtSyntax.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ConditionElementSyntax {
|
||||
var containsMultipleConditions: Bool {
|
||||
guard let condition = condition.as(SequenceExprSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return condition.elements.contains { expr in
|
||||
guard let binaryExpr = expr.as(BinaryOperatorExprSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
let operators: Set = ["&&", "||"]
|
||||
return operators.contains(binaryExpr.operatorToken.text)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForceCastRule: ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.error)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "force_cast",
|
||||
name: "Force Cast",
|
||||
description: "Force casts should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("NSNumber() as? Int\n")
|
||||
],
|
||||
triggeringExamples: [ Example("NSNumber() ↓as! Int\n") ]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
ForceCastRuleVisitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ForceCastRuleVisitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: AsExprSyntax) {
|
||||
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
||||
violations.append(node.asTok.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: UnresolvedAsExprSyntax) {
|
||||
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
||||
violations.append(node.asTok.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForceTryRule: ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.error)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "force_try",
|
||||
name: "Force Try",
|
||||
description: "Force tries should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
func a() throws {}
|
||||
do {
|
||||
try a()
|
||||
} catch {}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
func a() throws {}
|
||||
↓try! a()
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ForceTryRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: TryExprSyntax) {
|
||||
if node.questionOrExclamationMark?.tokenKind == .exclamationMark {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ForceUnwrappingRule: OptInRule, SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "force_unwrapping",
|
||||
name: "Force Unwrapping",
|
||||
description: "Force unwrapping should be avoided",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("if let url = NSURL(string: query)"),
|
||||
Example("navigationController?.pushViewController(viewController, animated: true)"),
|
||||
Example("let s as! Test"),
|
||||
Example("try! canThrowErrors()"),
|
||||
Example("let object: Any!"),
|
||||
Example("@IBOutlet var constraints: [NSLayoutConstraint]!"),
|
||||
Example("setEditing(!editing, animated: true)"),
|
||||
Example("navigationController.setNavigationBarHidden(!navigationController." +
|
||||
"navigationBarHidden, animated: true)"),
|
||||
Example("if addedToPlaylist && (!self.selectedFilters.isEmpty || " +
|
||||
"self.searchBar?.text?.isEmpty == false) {}"),
|
||||
Example("print(\"\\(xVar)!\")"),
|
||||
Example("var test = (!bar)"),
|
||||
Example("var a: [Int]!"),
|
||||
Example("private var myProperty: (Void -> Void)!"),
|
||||
Example("func foo(_ options: [AnyHashable: Any]!) {"),
|
||||
Example("func foo() -> [Int]!"),
|
||||
Example("func foo() -> [AnyHashable: Any]!"),
|
||||
Example("func foo() -> [Int]! { return [] }"),
|
||||
Example("return self")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let url = NSURL(string: query)↓!"),
|
||||
Example("navigationController↓!.pushViewController(viewController, animated: true)"),
|
||||
Example("let unwrapped = optional↓!"),
|
||||
Example("return cell↓!"),
|
||||
Example("let url = NSURL(string: \"http://www.google.com\")↓!"),
|
||||
Example("""
|
||||
let dict = ["Boooo": "👻"]
|
||||
func bla() -> String {
|
||||
return dict["Boooo"]↓!
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
let dict = ["Boooo": "👻"]
|
||||
func bla() -> String {
|
||||
return dict["Boooo"]↓!.contains("B")
|
||||
}
|
||||
"""),
|
||||
Example("let a = dict[\"abc\"]↓!.contains(\"B\")"),
|
||||
Example("dict[\"abc\"]↓!.bar(\"B\")"),
|
||||
Example("if dict[\"a\"]↓!↓!↓!↓! {}"),
|
||||
Example("var foo: [Bool]! = dict[\"abc\"]↓!"),
|
||||
Example("realm.objects(SwiftUTF8Object.self).filter(\"%K == %@\", \"柱нǢкƱаم👍\", utf8TestString).first↓!"),
|
||||
Example("""
|
||||
context("abc") {
|
||||
var foo: [Bool]! = dict["abc"]↓!
|
||||
}
|
||||
"""),
|
||||
Example("open var computed: String { return foo.bar↓! }"),
|
||||
Example("return self↓!"),
|
||||
Example("[1, 3, 5, 6].first { $0.isMultiple(of: 2) }↓!"),
|
||||
Example("map[\"a\"]↓!↓!")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
ForceUnwrappingVisitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ForceUnwrappingVisitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: ForcedValueExprSyntax) {
|
||||
violations.append(node.exclamationMark.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,132 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct FunctionDefaultParameterAtEndRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "function_default_parameter_at_end",
|
||||
name: "Function Default Parameter at End",
|
||||
description: "Prefer to locate parameters with defaults toward the end of the parameter list",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("func foo(baz: String, bar: Int = 0) {}"),
|
||||
Example("func foo(x: String, y: Int = 0, z: CGFloat = 0) {}"),
|
||||
Example("func foo(bar: String, baz: Int = 0, z: () -> Void) {}"),
|
||||
Example("func foo(bar: String, z: () -> Void, baz: Int = 0) {}"),
|
||||
Example("func foo(bar: Int = 0) {}"),
|
||||
Example("func foo() {}"),
|
||||
Example("""
|
||||
class A: B {
|
||||
override func foo(bar: Int = 0, baz: String) {}
|
||||
"""),
|
||||
Example("func foo(bar: Int = 0, completion: @escaping CompletionHandler) {}"),
|
||||
Example("""
|
||||
func foo(a: Int, b: CGFloat = 0) {
|
||||
let block = { (error: Error?) in }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo(a: String, b: String? = nil,
|
||||
c: String? = nil, d: @escaping AlertActionHandler = { _ in }) {}
|
||||
"""),
|
||||
Example("override init?(for date: Date = Date(), coordinate: CLLocationCoordinate2D) {}"),
|
||||
Example("""
|
||||
func handleNotification(_ userInfo: NSDictionary,
|
||||
userInteraction: Bool = false,
|
||||
completionHandler: ((UIBackgroundFetchResult) -> Void)?) {}
|
||||
"""),
|
||||
Example("""
|
||||
func write(withoutNotifying tokens: [NotificationToken] = {}, _ block: (() throws -> Int)) {}
|
||||
"""),
|
||||
Example("""
|
||||
func expect<T>(file: String = #file, _ expression: @autoclosure () -> (() throws -> T)) -> Expectation<T> {}
|
||||
""", excludeFromDocumentation: true)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓func foo(bar: Int = 0, baz: String) {}"),
|
||||
Example("private ↓func foo(bar: Int = 0, baz: String) {}"),
|
||||
Example("public ↓init?(for date: Date = Date(), coordinate: CLLocationCoordinate2D) {}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionDefaultParameterAtEndRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionDeclSyntax) {
|
||||
guard !node.modifiers.containsOverride, node.signature.containsViolation else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: InitializerDeclSyntax) {
|
||||
guard !node.modifiers.containsOverride, node.signature.containsViolation else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.initKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionSignatureSyntax {
|
||||
var containsViolation: Bool {
|
||||
let params = input.parameterList.filter { param in
|
||||
!param.isClosure
|
||||
}
|
||||
|
||||
guard params.isNotEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let defaultParams = params.filter { param in
|
||||
param.defaultArgument != nil
|
||||
}
|
||||
guard defaultParams.isNotEmpty else {
|
||||
return false
|
||||
}
|
||||
|
||||
let lastParameters = params.suffix(defaultParams.count)
|
||||
let lastParametersWithDefaultValue = lastParameters.filter { param in
|
||||
param.defaultArgument != nil
|
||||
}
|
||||
|
||||
return lastParameters.count != lastParametersWithDefaultValue.count
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionParameterSyntax {
|
||||
var isClosure: Bool {
|
||||
if isEscaping || type.is(FunctionTypeSyntax.self) {
|
||||
return true
|
||||
}
|
||||
|
||||
if let optionalType = type.as(OptionalTypeSyntax.self),
|
||||
let tuple = optionalType.wrappedType.as(TupleTypeSyntax.self) {
|
||||
return tuple.elements.onlyElement?.type.as(FunctionTypeSyntax.self) != nil
|
||||
}
|
||||
|
||||
if let tuple = type.as(TupleTypeSyntax.self) {
|
||||
return tuple.elements.onlyElement?.type.as(FunctionTypeSyntax.self) != nil
|
||||
}
|
||||
|
||||
if let attrType = type.as(AttributedTypeSyntax.self) {
|
||||
return attrType.baseType.is(FunctionTypeSyntax.self)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var isEscaping: Bool {
|
||||
guard let attrType = type.as(AttributedTypeSyntax.self) else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attrType.attributes.contains(attributeNamed: "escaping")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
import Foundation
|
||||
import SwiftSyntax
|
||||
|
||||
struct GenericTypeNameRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = NameConfiguration<Self>(minLengthWarning: 1,
|
||||
minLengthError: 0,
|
||||
maxLengthWarning: 20,
|
||||
maxLengthError: 1000)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "generic_type_name",
|
||||
name: "Generic Type Name",
|
||||
description: "Generic type name should only contain alphanumeric characters, start with an " +
|
||||
"uppercase character and span between 1 and 20 characters in length.",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("func foo<T>() {}\n"),
|
||||
Example("func foo<T>() -> T {}\n"),
|
||||
Example("func foo<T, U>(param: U) -> T {}\n"),
|
||||
Example("func foo<T: Hashable, U: Rule>(param: U) -> T {}\n"),
|
||||
Example("struct Foo<T> {}\n"),
|
||||
Example("class Foo<T> {}\n"),
|
||||
Example("enum Foo<T> {}\n"),
|
||||
Example("func run(_ options: NoOptions<CommandantError<()>>) {}\n"),
|
||||
Example("func foo(_ options: Set<type>) {}\n"),
|
||||
Example("func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool\n"),
|
||||
Example("func configureWith(data: Either<MessageThread, (project: Project, backing: Backing)>)\n"),
|
||||
Example("typealias StringDictionary<T> = Dictionary<String, T>\n"),
|
||||
Example("typealias BackwardTriple<T1, T2, T3> = (T3, T2, T1)\n"),
|
||||
Example("typealias DictionaryOfStrings<T : Hashable> = Dictionary<T, String>\n")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("func foo<↓T_Foo>() {}\n"),
|
||||
Example("func foo<T, ↓U_Foo>(param: U_Foo) -> T {}\n"),
|
||||
Example("func foo<↓\(String(repeating: "T", count: 21))>() {}\n"),
|
||||
Example("func foo<↓type>() {}\n"),
|
||||
Example("typealias StringDictionary<↓T_Foo> = Dictionary<String, T_Foo>\n"),
|
||||
Example("typealias BackwardTriple<T1, ↓T2_Bar, T3> = (T3, T2_Bar, T1)\n"),
|
||||
Example("typealias DictionaryOfStrings<↓T_Foo: Hashable> = Dictionary<T_Foo, String>\n")
|
||||
] + ["class", "struct", "enum"].flatMap { type -> [Example] in
|
||||
return [
|
||||
Example("\(type) Foo<↓T_Foo> {}\n"),
|
||||
Example("\(type) Foo<T, ↓U_Foo> {}\n"),
|
||||
Example("\(type) Foo<↓T_Foo, ↓U_Foo> {}\n"),
|
||||
Example("\(type) Foo<↓\(String(repeating: "T", count: 21))> {}\n"),
|
||||
Example("\(type) Foo<↓type> {}\n")
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
private extension GenericTypeNameRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let configuration: ConfigurationType
|
||||
|
||||
init(configuration: ConfigurationType) {
|
||||
self.configuration = configuration
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: GenericParameterSyntax) {
|
||||
let name = node.name.text
|
||||
guard !name.isEmpty, !configuration.shouldExclude(name: name) else { return }
|
||||
|
||||
if !configuration.allowedSymbolsAndAlphanumerics.isSuperset(of: CharacterSet(charactersIn: name)) {
|
||||
violations.append(
|
||||
ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: """
|
||||
Generic type name '\(name)' should only contain alphanumeric and other allowed characters
|
||||
""",
|
||||
severity: .error
|
||||
)
|
||||
)
|
||||
} else if let caseCheckSeverity = configuration.validatesStartWithLowercase.severity,
|
||||
!String(name[name.startIndex]).isUppercase() {
|
||||
violations.append(
|
||||
ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: "Generic type name '\(name)' should start with an uppercase character",
|
||||
severity: caseCheckSeverity
|
||||
)
|
||||
)
|
||||
} else if let severity = configuration.severity(forLength: name.count) {
|
||||
let reason = "Generic type name '\(name)' should be between \(configuration.minLengthThreshold) and " +
|
||||
"\(configuration.maxLengthThreshold) characters long"
|
||||
violations.append(
|
||||
ReasonedRuleViolation(
|
||||
position: node.positionAfterSkippingLeadingTrivia,
|
||||
reason: reason,
|
||||
severity: severity
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ImplicitlyUnwrappedOptionalRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = ImplicitlyUnwrappedOptionalConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "implicitly_unwrapped_optional",
|
||||
name: "Implicitly Unwrapped Optional",
|
||||
description: "Implicitly unwrapped optionals should be avoided when possible",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("@IBOutlet private var label: UILabel!"),
|
||||
Example("@IBOutlet var label: UILabel!"),
|
||||
Example("@IBOutlet var label: [UILabel!]"),
|
||||
Example("if !boolean {}"),
|
||||
Example("let int: Int? = 42"),
|
||||
Example("let int: Int? = nil"),
|
||||
Example("""
|
||||
class MyClass {
|
||||
@IBOutlet
|
||||
weak var bar: SomeObject!
|
||||
}
|
||||
""", configuration: ["mode": "all_except_iboutlets"], excludeFromDocumentation: true)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let label: ↓UILabel!"),
|
||||
Example("let IBOutlet: ↓UILabel!"),
|
||||
Example("let labels: [↓UILabel!]"),
|
||||
Example("var ints: [↓Int!] = [42, nil, 42]"),
|
||||
Example("let label: ↓IBOutlet!"),
|
||||
Example("let int: ↓Int! = 42"),
|
||||
Example("let int: ↓Int! = nil"),
|
||||
Example("var int: ↓Int! = 42"),
|
||||
Example("let collection: AnyCollection<↓Int!>"),
|
||||
Example("func foo(int: ↓Int!) {}"),
|
||||
Example("""
|
||||
class MyClass {
|
||||
weak var bar: ↓SomeObject!
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(mode: configuration.mode)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ImplicitlyUnwrappedOptionalRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let mode: ConfigurationType.ImplicitlyUnwrappedOptionalModeConfiguration
|
||||
|
||||
init(mode: ConfigurationType.ImplicitlyUnwrappedOptionalModeConfiguration) {
|
||||
self.mode = mode
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: ImplicitlyUnwrappedOptionalTypeSyntax) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
|
||||
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
switch mode {
|
||||
case .all:
|
||||
return .visitChildren
|
||||
case .allExceptIBOutlets:
|
||||
return node.isIBOutlet ? .skipChildren : .visitChildren
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct IsDisjointRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "is_disjoint",
|
||||
name: "Is Disjoint",
|
||||
description: "Prefer using `Set.isDisjoint(with:)` over `Set.intersection(_:).isEmpty`",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("_ = Set(syntaxKinds).isDisjoint(with: commentAndStringKindsSet)"),
|
||||
Example("let isObjc = !objcAttributes.isDisjoint(with: dictionary.enclosedSwiftAttributes)"),
|
||||
Example("_ = Set(syntaxKinds).intersection(commentAndStringKindsSet)"),
|
||||
Example("_ = !objcAttributes.intersection(dictionary.enclosedSwiftAttributes)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("_ = Set(syntaxKinds).↓intersection(commentAndStringKindsSet).isEmpty"),
|
||||
Example("let isObjc = !objcAttributes.↓intersection(dictionary.enclosedSwiftAttributes).isEmpty")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension IsDisjointRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: MemberAccessExprSyntax) {
|
||||
guard
|
||||
node.name.text == "isEmpty",
|
||||
let firstBase = node.base?.asFunctionCall,
|
||||
let firstBaseCalledExpression = firstBase.calledExpression.as(MemberAccessExprSyntax.self),
|
||||
firstBaseCalledExpression.name.text == "intersection"
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(firstBaseCalledExpression.name.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct JoinedDefaultParameterRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "joined_default_parameter",
|
||||
name: "Joined Default Parameter",
|
||||
description: "Discouraged explicit usage of the default separator",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("let foo = bar.joined()"),
|
||||
Example("let foo = bar.joined(separator: \",\")"),
|
||||
Example("let foo = bar.joined(separator: toto)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("let foo = bar.joined(↓separator: \"\")"),
|
||||
Example("""
|
||||
let foo = bar.filter(toto)
|
||||
.joined(↓separator: ""),
|
||||
"""),
|
||||
Example("""
|
||||
func foo() -> String {
|
||||
return ["1", "2"].joined(↓separator: "")
|
||||
}
|
||||
""")
|
||||
],
|
||||
corrections: [
|
||||
Example("let foo = bar.joined(↓separator: \"\")"): Example("let foo = bar.joined()"),
|
||||
Example("let foo = bar.filter(toto)\n.joined(↓separator: \"\")"):
|
||||
Example("let foo = bar.filter(toto)\n.joined()"),
|
||||
Example("func foo() -> String {\n return [\"1\", \"2\"].joined(↓separator: \"\")\n}"):
|
||||
Example("func foo() -> String {\n return [\"1\", \"2\"].joined()\n}"),
|
||||
Example("class C {\n#if true\nlet foo = bar.joined(↓separator: \"\")\n#endif\n}"):
|
||||
Example("class C {\n#if true\nlet foo = bar.joined()\n#endif\n}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension JoinedDefaultParameterRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let violationPosition = node.violationPosition {
|
||||
violations.append(violationPosition)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
private let locationConverter: SourceLocationConverter
|
||||
private let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard let violationPosition = node.violationPosition,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(violationPosition)
|
||||
let newNode = node.with(\.argumentList, [])
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var violationPosition: AbsolutePosition? {
|
||||
guard let argument = argumentList.first,
|
||||
let memberExp = calledExpression.as(MemberAccessExprSyntax.self),
|
||||
memberExp.name.text == "joined",
|
||||
argument.label?.text == "separator",
|
||||
let strLiteral = argument.expression.as(StringLiteralExprSyntax.self),
|
||||
strLiteral.isEmptyString else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return argument.positionAfterSkippingLeadingTrivia
|
||||
}
|
||||
}
|
|
@ -1,12 +1,7 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
struct LegacyCGGeometryFunctionsRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public struct LegacyCGGeometryFunctionsRule: CorrectableRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_cggeometry_functions",
|
||||
name: "Legacy CGGeometry Functions",
|
||||
description: "Struct extension properties and methods are preferred over legacy functions",
|
||||
|
@ -73,7 +68,7 @@ public struct LegacyCGGeometryFunctionsRule: CorrectableRule, ConfigurationProvi
|
|||
Example("↓CGRectInset(rect, 5.0, -7.0)\n"): Example("rect.insetBy(dx: 5.0, dy: -7.0)\n"),
|
||||
Example("↓CGRectOffset(rect, -2, 8.3)\n"): Example("rect.offsetBy(dx: -2, dy: 8.3)\n"),
|
||||
Example("↓CGRectUnion(rect1, rect2)\n"): Example("rect1.union(rect2)\n"),
|
||||
Example("↓CGRectIntersection( rect1 ,rect2)\n"): Example("rect1.intersect(rect2)\n"),
|
||||
Example("↓CGRectIntersection( rect1 ,rect2)\n"): Example("rect1.intersection(rect2)\n"),
|
||||
Example("↓CGRectContainsRect( rect1,rect2 )\n"): Example("rect1.contains(rect2)\n"),
|
||||
Example("↓CGRectContainsPoint(rect ,point)\n"): Example("rect.contains(point)\n"),
|
||||
Example("↓CGRectIntersectsRect( rect1,rect2 )\n"): Example("rect1.intersects(rect2)\n"),
|
||||
|
@ -82,49 +77,38 @@ public struct LegacyCGGeometryFunctionsRule: CorrectableRule, ConfigurationProvi
|
|||
]
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let functions = ["CGRectGetWidth", "CGRectGetHeight", "CGRectGetMinX", "CGRectGetMidX",
|
||||
"CGRectGetMaxX", "CGRectGetMinY", "CGRectGetMidY", "CGRectGetMaxY",
|
||||
"CGRectIsNull", "CGRectIsEmpty", "CGRectIsInfinite", "CGRectStandardize",
|
||||
"CGRectIntegral", "CGRectInset", "CGRectOffset", "CGRectUnion",
|
||||
"CGRectIntersection", "CGRectContainsRect", "CGRectContainsPoint",
|
||||
"CGRectIntersectsRect"]
|
||||
private static let legacyFunctions: [String: LegacyFunctionRuleHelper.RewriteStrategy] = [
|
||||
"CGRectGetWidth": .property(name: "width"),
|
||||
"CGRectGetHeight": .property(name: "height"),
|
||||
"CGRectGetMinX": .property(name: "minX"),
|
||||
"CGRectGetMidX": .property(name: "midX"),
|
||||
"CGRectGetMaxX": .property(name: "maxX"),
|
||||
"CGRectGetMinY": .property(name: "minY"),
|
||||
"CGRectGetMidY": .property(name: "midY"),
|
||||
"CGRectGetMaxY": .property(name: "maxY"),
|
||||
"CGRectIsNull": .property(name: "isNull"),
|
||||
"CGRectIsEmpty": .property(name: "isEmpty"),
|
||||
"CGRectIsInfinite": .property(name: "isInfinite"),
|
||||
"CGRectStandardize": .property(name: "standardized"),
|
||||
"CGRectIntegral": .property(name: "integral"),
|
||||
"CGRectInset": .function(name: "insetBy", argumentLabels: ["dx", "dy"]),
|
||||
"CGRectOffset": .function(name: "offsetBy", argumentLabels: ["dx", "dy"]),
|
||||
"CGRectUnion": .function(name: "union", argumentLabels: [""]),
|
||||
"CGRectContainsRect": .function(name: "contains", argumentLabels: [""]),
|
||||
"CGRectContainsPoint": .function(name: "contains", argumentLabels: [""]),
|
||||
"CGRectIntersectsRect": .function(name: "intersects", argumentLabels: [""]),
|
||||
"CGRectIntersection": .function(name: "intersection", argumentLabels: [""])
|
||||
]
|
||||
|
||||
let pattern = "\\b(" + functions.joined(separator: "|") + ")\\b"
|
||||
|
||||
return file.match(pattern: pattern, with: [.identifier]).map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, characterOffset: $0.location))
|
||||
}
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
LegacyFunctionRuleHelper.Visitor(legacyFunctions: Self.legacyFunctions)
|
||||
}
|
||||
|
||||
public func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let varName = RegexHelpers.varNameGroup
|
||||
let twoVars = RegexHelpers.twoVars
|
||||
let twoVariableOrNumber = RegexHelpers.twoVariableOrNumber
|
||||
let patterns: [String: String] = [
|
||||
"CGRectGetWidth\\(\(varName)\\)": "$1.width",
|
||||
"CGRectGetHeight\\(\(varName)\\)": "$1.height",
|
||||
"CGRectGetMinX\\(\(varName)\\)": "$1.minX",
|
||||
"CGRectGetMidX\\(\(varName)\\)": "$1.midX",
|
||||
"CGRectGetMaxX\\(\(varName)\\)": "$1.maxX",
|
||||
"CGRectGetMinY\\(\(varName)\\)": "$1.minY",
|
||||
"CGRectGetMidY\\(\(varName)\\)": "$1.midY",
|
||||
"CGRectGetMaxY\\(\(varName)\\)": "$1.maxY",
|
||||
"CGRectIsNull\\(\(varName)\\)": "$1.isNull",
|
||||
"CGRectIsEmpty\\(\(varName)\\)": "$1.isEmpty",
|
||||
"CGRectIsInfinite\\(\(varName)\\)": "$1.isInfinite",
|
||||
"CGRectStandardize\\(\(varName)\\)": "$1.standardized",
|
||||
"CGRectIntegral\\(\(varName)\\)": "$1.integral",
|
||||
"CGRectInset\\(\(varName),\(twoVariableOrNumber)\\)": "$1.insetBy(dx: $2, dy: $3)",
|
||||
"CGRectOffset\\(\(varName),\(twoVariableOrNumber)\\)": "$1.offsetBy(dx: $2, dy: $3)",
|
||||
"CGRectUnion\\(\(twoVars)\\)": "$1.union($2)",
|
||||
"CGRectIntersection\\(\(twoVars)\\)": "$1.intersect($2)",
|
||||
"CGRectContainsRect\\(\(twoVars)\\)": "$1.contains($2)",
|
||||
"CGRectContainsPoint\\(\(twoVars)\\)": "$1.contains($2)",
|
||||
"CGRectIntersectsRect\\(\(twoVars)\\)": "$1.intersects($2)"
|
||||
]
|
||||
return file.correct(legacyRule: self, patterns: patterns)
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
LegacyFunctionRuleHelper.Rewriter(
|
||||
legacyFunctions: Self.legacyFunctions,
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
import SwiftSyntax
|
||||
import SwiftSyntaxBuilder
|
||||
|
||||
struct LegacyConstantRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_constant",
|
||||
name: "Legacy Constant",
|
||||
description: "Struct-scoped constants are preferred over legacy global constants",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: LegacyConstantRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: LegacyConstantRuleExamples.triggeringExamples,
|
||||
corrections: LegacyConstantRuleExamples.corrections
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyConstantRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: IdentifierExprSyntax) {
|
||||
if LegacyConstantRuleExamples.patterns.keys.contains(node.identifier.text) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if node.isLegacyPiExpression {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: IdentifierExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
let correction = LegacyConstantRuleExamples.patterns[node.identifier.text],
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
return ("\(raw: correction)" as ExprSyntax)
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard
|
||||
node.isLegacyPiExpression,
|
||||
let calledExpression = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
return ("\(raw: calledExpression.identifier.text).pi" as ExprSyntax)
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var isLegacyPiExpression: Bool {
|
||||
guard
|
||||
let calledExpression = calledExpression.as(IdentifierExprSyntax.self),
|
||||
calledExpression.identifier.text == "CGFloat" || calledExpression.identifier.text == "Float",
|
||||
let argument = argumentList.onlyElement?.expression.as(IdentifierExprSyntax.self),
|
||||
argument.identifier.text == "M_PI"
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
|
@ -48,8 +48,6 @@ internal struct LegacyConstantRuleExamples {
|
|||
"NSZeroPoint": "NSPoint.zero",
|
||||
"NSZeroRect": "NSRect.zero",
|
||||
"NSZeroSize": "NSSize.zero",
|
||||
"CGRectNull": "CGRect.null",
|
||||
"CGFloat\\(M_PI\\)": "CGFloat.pi",
|
||||
"Float\\(M_PI\\)": "Float.pi"
|
||||
"CGRectNull": "CGRect.null"
|
||||
]
|
||||
}
|
|
@ -1,15 +1,12 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
import SwiftSyntax
|
||||
|
||||
public struct LegacyConstructorRule: ASTRule, CorrectableRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct LegacyConstructorRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_constructor",
|
||||
name: "Legacy Constructor",
|
||||
description: "Swift constructors are preferred over legacy convenience functions.",
|
||||
description: "Swift constructors are preferred over legacy convenience functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("CGPoint(x: 10, y: 10)"),
|
||||
|
@ -62,22 +59,22 @@ public struct LegacyConstructorRule: ASTRule, CorrectableRule, ConfigurationProv
|
|||
Example("↓UIOffsetMake(horizontal, vertical)")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓CGPointMake(10, 10 )\n"): Example("CGPoint(x: 10, y: 10)\n"),
|
||||
Example("↓CGPointMake(xPos, yPos )\n"): Example("CGPoint(x: xPos, y: yPos)\n"),
|
||||
Example("↓CGPointMake(10, 10)\n"): Example("CGPoint(x: 10, y: 10)\n"),
|
||||
Example("↓CGPointMake(xPos, yPos)\n"): Example("CGPoint(x: xPos, y: yPos)\n"),
|
||||
Example("↓CGSizeMake(10, 10)\n"): Example("CGSize(width: 10, height: 10)\n"),
|
||||
Example("↓CGSizeMake( aWidth, aHeight )\n"): Example("CGSize(width: aWidth, height: aHeight)\n"),
|
||||
Example("↓CGSizeMake( aWidth, aHeight )\n"): Example("CGSize( width: aWidth, height: aHeight )\n"),
|
||||
Example("↓CGRectMake(0, 0, 10, 10)\n"): Example("CGRect(x: 0, y: 0, width: 10, height: 10)\n"),
|
||||
Example("↓CGRectMake(xPos, yPos , width, height)\n"):
|
||||
Example("CGRect(x: xPos, y: yPos, width: width, height: height)\n"),
|
||||
Example("CGRect(x: xPos, y: yPos , width: width, height: height)\n"),
|
||||
Example("↓CGVectorMake(10, 10)\n"): Example("CGVector(dx: 10, dy: 10)\n"),
|
||||
Example("↓CGVectorMake(deltaX, deltaY)\n"): Example("CGVector(dx: deltaX, dy: deltaY)\n"),
|
||||
Example("↓NSMakePoint(10, 10 )\n"): Example("NSPoint(x: 10, y: 10)\n"),
|
||||
Example("↓NSMakePoint(xPos, yPos )\n"): Example("NSPoint(x: xPos, y: yPos)\n"),
|
||||
Example("↓NSMakePoint(10, 10 )\n"): Example("NSPoint(x: 10, y: 10 )\n"),
|
||||
Example("↓NSMakePoint(xPos, yPos )\n"): Example("NSPoint(x: xPos, y: yPos )\n"),
|
||||
Example("↓NSMakeSize(10, 10)\n"): Example("NSSize(width: 10, height: 10)\n"),
|
||||
Example("↓NSMakeSize( aWidth, aHeight )\n"): Example("NSSize(width: aWidth, height: aHeight)\n"),
|
||||
Example("↓NSMakeSize( aWidth, aHeight )\n"): Example("NSSize( width: aWidth, height: aHeight )\n"),
|
||||
Example("↓NSMakeRect(0, 0, 10, 10)\n"): Example("NSRect(x: 0, y: 0, width: 10, height: 10)\n"),
|
||||
Example("↓NSMakeRect(xPos, yPos , width, height)\n"):
|
||||
Example("NSRect(x: xPos, y: yPos, width: width, height: height)\n"),
|
||||
Example("NSRect(x: xPos, y: yPos , width: width, height: height)\n"),
|
||||
Example("↓NSMakeRange(10, 1)\n"): Example("NSRange(location: 10, length: 1)\n"),
|
||||
Example("↓NSMakeRange(loc, len)\n"): Example("NSRange(location: loc, length: len)\n"),
|
||||
Example("↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)\n"):
|
||||
|
@ -125,99 +122,66 @@ public struct LegacyConstructorRule: ASTRule, CorrectableRule, ConfigurationProv
|
|||
"NSEdgeInsetsMake": "NSEdgeInsets",
|
||||
"UIOffsetMake": "UIOffset"]
|
||||
|
||||
public func validate(file: SwiftLintFile, kind: SwiftExpressionKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
guard containsViolation(kind: kind, dictionary: dictionary),
|
||||
let offset = dictionary.offset else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: offset))
|
||||
]
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
private func violations(in file: SwiftLintFile, kind: SwiftExpressionKind,
|
||||
dictionary: SourceKittenDictionary) -> [SourceKittenDictionary] {
|
||||
guard containsViolation(kind: kind, dictionary: dictionary) else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [dictionary]
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func containsViolation(kind: SwiftExpressionKind,
|
||||
dictionary: SourceKittenDictionary) -> Bool {
|
||||
guard kind == .call,
|
||||
let name = dictionary.name,
|
||||
dictionary.offset != nil,
|
||||
let expectedArguments = Self.constructorsToArguments[name],
|
||||
dictionary.enclosedArguments.count == expectedArguments.count else {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private func violations(in file: SwiftLintFile,
|
||||
dictionary: SourceKittenDictionary) -> [SourceKittenDictionary] {
|
||||
return dictionary.traverseDepthFirst { subDict in
|
||||
guard let kind = subDict.expressionKind else { return nil }
|
||||
return violations(in: file, kind: kind, dictionary: subDict)
|
||||
}
|
||||
}
|
||||
|
||||
private func violations(in file: SwiftLintFile) -> [SourceKittenDictionary] {
|
||||
return violations(in: file, dictionary: file.structureDictionary).sorted { lhs, rhs in
|
||||
(lhs.offset ?? 0) < (rhs.offset ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
public func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let violatingDictionaries = violations(in: file)
|
||||
var correctedContents = file.contents
|
||||
var adjustedLocations = [Int]()
|
||||
|
||||
for dictionary in violatingDictionaries.reversed() {
|
||||
guard let byteRange = dictionary.byteRange,
|
||||
let range = file.stringView.byteRangeToNSRange(byteRange),
|
||||
let name = dictionary.name,
|
||||
let correctedName = Self.constructorsToCorrectedNames[name],
|
||||
file.ruleEnabled(violatingRanges: [range], for: self) == [range],
|
||||
case let arguments = argumentsContents(file: file, arguments: dictionary.enclosedArguments),
|
||||
let expectedArguments = Self.constructorsToArguments[name],
|
||||
arguments.count == expectedArguments.count else {
|
||||
continue
|
||||
}
|
||||
|
||||
if let indexRange = correctedContents.nsrangeToIndexRange(range) {
|
||||
let joinedArguments = zip(expectedArguments, arguments).map { "\($0): \($1)" }.joined(separator: ", ")
|
||||
let replacement = correctedName + "(" + joinedArguments + ")"
|
||||
correctedContents = correctedContents.replacingCharacters(in: indexRange, with: replacement)
|
||||
adjustedLocations.insert(range.location, at: 0)
|
||||
private extension LegacyConstructorRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let identifierExpr = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
constructorsToCorrectedNames[identifierExpr.identifier.text] != nil {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
let corrections = adjustedLocations.map {
|
||||
Correction(ruleDescription: Self.description,
|
||||
location: Location(file: file, characterOffset: $0))
|
||||
}
|
||||
|
||||
file.write(correctedContents)
|
||||
|
||||
return corrections
|
||||
}
|
||||
|
||||
private func argumentsContents(file: SwiftLintFile, arguments: [SourceKittenDictionary]) -> [String] {
|
||||
let contents = file.stringView
|
||||
return arguments.compactMap { argument -> String? in
|
||||
guard argument.name == nil, let byteRange = argument.byteRange else {
|
||||
return nil
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard let identifierExpr = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
case let identifier = identifierExpr.identifier.text,
|
||||
let correctedName = constructorsToCorrectedNames[identifier],
|
||||
let args = constructorsToArguments[identifier],
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
return contents.substringWithByteRange(byteRange)
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
|
||||
let arguments = TupleExprElementListSyntax(node.argumentList.enumerated().map { index, elem in
|
||||
elem
|
||||
.with(\.label, .identifier(args[index]))
|
||||
.with(\.colon, .colonToken(trailingTrivia: .space))
|
||||
})
|
||||
let newExpression = identifierExpr.with(
|
||||
\.identifier,
|
||||
.identifier(
|
||||
correctedName,
|
||||
leadingTrivia: identifierExpr.identifier.leadingTrivia,
|
||||
trailingTrivia: identifierExpr.identifier.trailingTrivia
|
||||
)
|
||||
)
|
||||
let newNode = node
|
||||
.with(\.calledExpression, ExprSyntax(newExpression))
|
||||
.with(\.argumentList, arguments)
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,11 +1,9 @@
|
|||
import SourceKittenFramework
|
||||
import SwiftSyntax
|
||||
|
||||
public struct LegacyHashingRule: ASTRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct LegacyHashingRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_hashing",
|
||||
name: "Legacy Hashing",
|
||||
description: "Prefer using the `hash(into:)` function instead of overriding `hashValue`",
|
||||
|
@ -75,21 +73,27 @@ public struct LegacyHashingRule: ASTRule, ConfigurationProviderRule {
|
|||
]
|
||||
)
|
||||
|
||||
// MARK: - ASTRule
|
||||
|
||||
public func validate(file: SwiftLintFile,
|
||||
kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
guard kind == .varInstance,
|
||||
dictionary.setterAccessibility == nil,
|
||||
dictionary.typeName == "Int",
|
||||
dictionary.name == "hashValue",
|
||||
let offset = dictionary.offset else {
|
||||
return []
|
||||
}
|
||||
|
||||
return [StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, byteOffset: offset))]
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
extension LegacyHashingRule {
|
||||
private final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
guard
|
||||
node.parent?.is(MemberDeclListItemSyntax.self) == true,
|
||||
node.bindingKeyword.tokenKind == .keyword(.var),
|
||||
let binding = node.bindings.onlyElement,
|
||||
let identifier = binding.pattern.as(IdentifierPatternSyntax.self),
|
||||
identifier.identifier.text == "hashValue",
|
||||
let returnType = binding.typeAnnotation?.type.as(SimpleTypeIdentifierSyntax.self),
|
||||
returnType.name.text == "Int"
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.bindingKeyword.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct LegacyMultipleRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_multiple",
|
||||
name: "Legacy Multiple",
|
||||
description: "Prefer using the `isMultiple(of:)` function instead of using the remainder operator (`%`)",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("cell.contentView.backgroundColor = indexPath.row.isMultiple(of: 2) ? .gray : .white"),
|
||||
Example("guard count.isMultiple(of: 2) else { throw DecodingError.dataCorrupted(...) }"),
|
||||
Example("sanityCheck(bytes > 0 && bytes.isMultiple(of: 4), \"capacity must be multiple of 4 bytes\")"),
|
||||
Example("guard let i = reversedNumbers.firstIndex(where: { $0.isMultiple(of: 2) }) else { return }"),
|
||||
Example("""
|
||||
let constant = 56
|
||||
let isMultiple = value.isMultiple(of: constant)
|
||||
"""),
|
||||
Example("""
|
||||
let constant = 56
|
||||
let secret = value % constant == 5
|
||||
"""),
|
||||
Example("let secretValue = (value % 3) + 2")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("cell.contentView.backgroundColor = indexPath.row ↓% 2 == 0 ? .gray : .white"),
|
||||
Example("cell.contentView.backgroundColor = 0 == indexPath.row ↓% 2 ? .gray : .white"),
|
||||
Example("cell.contentView.backgroundColor = indexPath.row ↓% 2 != 0 ? .gray : .white"),
|
||||
Example("guard count ↓% 2 == 0 else { throw DecodingError.dataCorrupted(...) }"),
|
||||
Example("sanityCheck(bytes > 0 && bytes ↓% 4 == 0, \"capacity must be multiple of 4 bytes\")"),
|
||||
Example("guard let i = reversedNumbers.firstIndex(where: { $0 ↓% 2 == 0 }) else { return }"),
|
||||
Example("""
|
||||
let constant = 56
|
||||
let isMultiple = value ↓% constant == 0
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func preprocess(file: SwiftLintFile) -> SourceFileSyntax? {
|
||||
file.foldedSyntaxTree
|
||||
}
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyMultipleRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: InfixOperatorExprSyntax) {
|
||||
guard let operatorNode = node.operatorOperand.as(BinaryOperatorExprSyntax.self),
|
||||
operatorNode.operatorToken.tokenKind == .binaryOperator("%"),
|
||||
let parent = node.parent?.as(InfixOperatorExprSyntax.self),
|
||||
let parentOperatorNode = parent.operatorOperand.as(BinaryOperatorExprSyntax.self),
|
||||
parentOperatorNode.isEqualityOrInequalityOperator else {
|
||||
return
|
||||
}
|
||||
|
||||
let isExprEqualTo0 = {
|
||||
parent.leftOperand.as(InfixOperatorExprSyntax.self) == node &&
|
||||
parent.rightOperand.as(IntegerLiteralExprSyntax.self)?.isZero == true
|
||||
}
|
||||
|
||||
let is0EqualToExpr = {
|
||||
parent.leftOperand.as(IntegerLiteralExprSyntax.self)?.isZero == true &&
|
||||
parent.rightOperand.as(InfixOperatorExprSyntax.self) == node
|
||||
}
|
||||
|
||||
guard isExprEqualTo0() || is0EqualToExpr() else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.operatorOperand.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension BinaryOperatorExprSyntax {
|
||||
var isEqualityOrInequalityOperator: Bool {
|
||||
operatorToken.tokenKind == .binaryOperator("==") ||
|
||||
operatorToken.tokenKind == .binaryOperator("!=")
|
||||
}
|
||||
}
|
|
@ -1,12 +1,7 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
struct LegacyNSGeometryFunctionsRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public struct LegacyNSGeometryFunctionsRule: CorrectableRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_nsgeometry_functions",
|
||||
name: "Legacy NSGeometry Functions",
|
||||
description: "Struct extension properties and methods are preferred over legacy functions",
|
||||
|
@ -25,7 +20,7 @@ public struct LegacyNSGeometryFunctionsRule: CorrectableRule, ConfigurationProvi
|
|||
Example("rect.insetBy(dx: 5.0, dy: -7.0)"),
|
||||
Example("rect.offsetBy(dx: 5.0, dy: -7.0)"),
|
||||
Example("rect1.union(rect2)"),
|
||||
Example("rect1.intersect(rect2)"),
|
||||
Example("rect1.intersection(rect2)"),
|
||||
// "rect.divide(atDistance: 10.2, fromEdge: edge)", No correction available for divide
|
||||
Example("rect1.contains(rect2)"),
|
||||
Example("rect.contains(point)"),
|
||||
|
@ -72,59 +67,48 @@ public struct LegacyNSGeometryFunctionsRule: CorrectableRule, ConfigurationProvi
|
|||
Example("↓NSInsetRect(rect, 5.0, -7.0)\n"): Example("rect.insetBy(dx: 5.0, dy: -7.0)\n"),
|
||||
Example("↓NSOffsetRect(rect, -2, 8.3)\n"): Example("rect.offsetBy(dx: -2, dy: 8.3)\n"),
|
||||
Example("↓NSUnionRect(rect1, rect2)\n"): Example("rect1.union(rect2)\n"),
|
||||
Example("↓NSIntersectionRect( rect1 ,rect2)\n"): Example("rect1.intersect(rect2)\n"),
|
||||
Example("↓NSContainsRect( rect1,rect2 )\n"): Example("rect1.contains(rect2)\n"),
|
||||
Example("↓NSPointInRect(point ,rect)\n"): Example("rect.contains(point)\n"), // note order of arguments
|
||||
Example("↓NSIntersectsRect( rect1,rect2 )\n"): Example("rect1.intersects(rect2)\n"),
|
||||
Example("↓NSIntersectsRect(rect1, rect2 )\n↓NSWidth(rect )\n"):
|
||||
Example("rect1.intersects(rect2)\nrect.width\n")
|
||||
Example("rect1.intersects(rect2)\nrect.width\n"),
|
||||
Example("↓NSIntersectionRect(rect1, rect2)"): Example("rect1.intersection(rect2)")
|
||||
]
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let functions = ["NSWidth", "NSHeight", "NSMinX", "NSMidX",
|
||||
"NSMaxX", "NSMinY", "NSMidY", "NSMaxY",
|
||||
"NSEqualRects", "NSEqualSizes", "NSEqualPoints", "NSEdgeInsetsEqual",
|
||||
"NSIsEmptyRect", "NSIntegralRect", "NSInsetRect",
|
||||
"NSOffsetRect", "NSUnionRect", "NSIntersectionRect",
|
||||
"NSContainsRect", "NSPointInRect", "NSIntersectsRect"]
|
||||
private static let legacyFunctions: [String: LegacyFunctionRuleHelper.RewriteStrategy] = [
|
||||
"NSHeight": .property(name: "height"),
|
||||
"NSIntegralRect": .property(name: "integral"),
|
||||
"NSIsEmptyRect": .property(name: "isEmpty"),
|
||||
"NSMaxX": .property(name: "maxX"),
|
||||
"NSMaxY": .property(name: "maxY"),
|
||||
"NSMidX": .property(name: "midX"),
|
||||
"NSMidY": .property(name: "midY"),
|
||||
"NSMinX": .property(name: "minX"),
|
||||
"NSMinY": .property(name: "minY"),
|
||||
"NSWidth": .property(name: "width"),
|
||||
"NSEqualPoints": .equal,
|
||||
"NSEqualSizes": .equal,
|
||||
"NSEqualRects": .equal,
|
||||
"NSEdgeInsetsEqual": .equal,
|
||||
"NSInsetRect": .function(name: "insetBy", argumentLabels: ["dx", "dy"]),
|
||||
"NSOffsetRect": .function(name: "offsetBy", argumentLabels: ["dx", "dy"]),
|
||||
"NSUnionRect": .function(name: "union", argumentLabels: [""]),
|
||||
"NSContainsRect": .function(name: "contains", argumentLabels: [""]),
|
||||
"NSIntersectsRect": .function(name: "intersects", argumentLabels: [""]),
|
||||
"NSIntersectionRect": .function(name: "intersection", argumentLabels: [""]),
|
||||
"NSPointInRect": .function(name: "contains", argumentLabels: [""], reversed: true)
|
||||
]
|
||||
|
||||
let pattern = "\\b(" + functions.joined(separator: "|") + ")\\b"
|
||||
|
||||
return file.match(pattern: pattern, with: [.identifier]).map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
location: Location(file: file, characterOffset: $0.location))
|
||||
}
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
LegacyFunctionRuleHelper.Visitor(legacyFunctions: Self.legacyFunctions)
|
||||
}
|
||||
|
||||
public func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let varName = RegexHelpers.varNameGroup
|
||||
let twoVars = RegexHelpers.twoVars
|
||||
let twoVariableOrNumber = RegexHelpers.twoVariableOrNumber
|
||||
let patterns: [String: String] = [
|
||||
"NSWidth\\(\(varName)\\)": "$1.width",
|
||||
"NSHeight\\(\(varName)\\)": "$1.height",
|
||||
"NSMinX\\(\(varName)\\)": "$1.minX",
|
||||
"NSMidX\\(\(varName)\\)": "$1.midX",
|
||||
"NSMaxX\\(\(varName)\\)": "$1.maxX",
|
||||
"NSMinY\\(\(varName)\\)": "$1.minY",
|
||||
"NSMidY\\(\(varName)\\)": "$1.midY",
|
||||
"NSMaxY\\(\(varName)\\)": "$1.maxY",
|
||||
"NSEqualRects\\(\(twoVars)\\)": "$1 == $2",
|
||||
"NSEqualSizes\\(\(twoVars)\\)": "$1 == $2",
|
||||
"NSEqualPoints\\(\(twoVars)\\)": "$1 == $2",
|
||||
"NSEdgeInsetsEqual\\(\(twoVars)\\)": "$1 == $2",
|
||||
"NSIsEmptyRect\\(\(varName)\\)": "$1.isEmpty",
|
||||
"NSIntegralRect\\(\(varName)\\)": "$1.integral",
|
||||
"NSInsetRect\\(\(varName),\(twoVariableOrNumber)\\)": "$1.insetBy(dx: $2, dy: $3)",
|
||||
"NSOffsetRect\\(\(varName),\(twoVariableOrNumber)\\)": "$1.offsetBy(dx: $2, dy: $3)",
|
||||
"NSUnionRect\\(\(twoVars)\\)": "$1.union($2)",
|
||||
"NSIntersectionRect\\(\(twoVars)\\)": "$1.intersect($2)",
|
||||
"NSContainsRect\\(\(twoVars)\\)": "$1.contains($2)",
|
||||
"NSPointInRect\\(\(twoVars)\\)": "$2.contains($1)", // note order of arguments
|
||||
"NSIntersectsRect\\(\(twoVars)\\)": "$1.intersects($2)"
|
||||
]
|
||||
return file.correct(legacyRule: self, patterns: patterns)
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
LegacyFunctionRuleHelper.Rewriter(
|
||||
legacyFunctions: Self.legacyFunctions,
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
import SwiftSyntax
|
||||
|
||||
private let legacyObjcTypes = [
|
||||
"NSAffineTransform",
|
||||
"NSArray",
|
||||
"NSCalendar",
|
||||
"NSCharacterSet",
|
||||
"NSData",
|
||||
"NSDateComponents",
|
||||
"NSDateInterval",
|
||||
"NSDate",
|
||||
"NSDecimalNumber",
|
||||
"NSDictionary",
|
||||
"NSIndexPath",
|
||||
"NSIndexSet",
|
||||
"NSLocale",
|
||||
"NSMeasurement",
|
||||
"NSNotification",
|
||||
"NSNumber",
|
||||
"NSPersonNameComponents",
|
||||
"NSSet",
|
||||
"NSString",
|
||||
"NSTimeZone",
|
||||
"NSURL",
|
||||
"NSURLComponents",
|
||||
"NSURLQueryItem",
|
||||
"NSURLRequest",
|
||||
"NSUUID"
|
||||
]
|
||||
|
||||
struct LegacyObjcTypeRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "legacy_objc_type",
|
||||
name: "Legacy Objective-C Reference Type",
|
||||
description: "Prefer Swift value types to bridged Objective-C reference types",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("var array = Array<Int>()\n"),
|
||||
Example("var calendar: Calendar? = nil"),
|
||||
Example("var formatter: NSDataDetector"),
|
||||
Example("var className: String = NSStringFromClass(MyClass.self)"),
|
||||
Example("_ = URLRequest.CachePolicy.reloadIgnoringLocalCacheData"),
|
||||
Example(#"_ = Notification.Name("com.apple.Music.playerInfo")"#)
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("var array = ↓NSArray()"),
|
||||
Example("var calendar: ↓NSCalendar? = nil"),
|
||||
Example("_ = ↓NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData"),
|
||||
Example(#"_ = ↓NSNotification.Name("com.apple.Music.playerInfo")"#),
|
||||
Example(#"""
|
||||
let keyValuePair: (Int) -> (↓NSString, ↓NSString) = {
|
||||
let n = "\($0)" as ↓NSString; return (n, n)
|
||||
}
|
||||
dictionary = [↓NSString: ↓NSString](uniqueKeysWithValues:
|
||||
(1...10_000).lazy.map(keyValuePair))
|
||||
"""#),
|
||||
Example("""
|
||||
extension Foundation.Notification.Name {
|
||||
static var reachabilityChanged: Foundation.↓NSNotification.Name {
|
||||
return Foundation.Notification.Name("org.wordpress.reachability.changed")
|
||||
}
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyObjcTypeRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: SimpleTypeIdentifierSyntax) {
|
||||
if let typeName = node.typeName, legacyObjcTypes.contains(typeName) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: IdentifierExprSyntax) {
|
||||
if legacyObjcTypes.contains(node.identifier.text) {
|
||||
violations.append(node.identifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: MemberTypeIdentifierSyntax) {
|
||||
guard node.baseType.as(SimpleTypeIdentifierSyntax.self)?.typeName == "Foundation",
|
||||
legacyObjcTypes.contains(node.name.text)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(node.name.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct LegacyRandomRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static var description = RuleDescription(
|
||||
identifier: "legacy_random",
|
||||
name: "Legacy Random",
|
||||
description: "Prefer using `type.random(in:)` over legacy functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("Int.random(in: 0..<10)\n"),
|
||||
Example("Double.random(in: 8.6...111.34)\n"),
|
||||
Example("Float.random(in: 0 ..< 1)\n")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓arc4random()\n"),
|
||||
Example("↓arc4random_uniform(83)\n"),
|
||||
Example("↓drand48()\n")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension LegacyRandomRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private static let legacyRandomFunctions: Set<String> = [
|
||||
"arc4random",
|
||||
"arc4random_uniform",
|
||||
"drand48"
|
||||
]
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let function = node.calledExpression.as(IdentifierExprSyntax.self)?.identifier.text,
|
||||
Self.legacyRandomFunctions.contains(function) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,15 +1,13 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
public struct NimbleOperatorRule: ConfigurationProviderRule, OptInRule, CorrectableRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct NimbleOperatorRule: ConfigurationProviderRule, OptInRule, CorrectableRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "nimble_operator",
|
||||
name: "Nimble Operator",
|
||||
description: "Prefer Nimble operator overloads over free matcher functions.",
|
||||
description: "Prefer Nimble operator overloads over free matcher functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("expect(seagull.squawk) != \"Hi!\"\n"),
|
||||
|
@ -98,7 +96,7 @@ public struct NimbleOperatorRule: ConfigurationProviderRule, OptInRule, Correcta
|
|||
"beNil": (to: "==", toNot: "!=", .nullary(analogueValue: "nil"))
|
||||
]
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let matches = violationMatchesRanges(in: file)
|
||||
return matches.map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
|
@ -114,12 +112,10 @@ public struct NimbleOperatorRule: ConfigurationProviderRule, OptInRule, Correcta
|
|||
return false
|
||||
}
|
||||
|
||||
let containsCall = file.structureDictionary.structures(forByteOffset: byteRange.upperBound - 1)
|
||||
return file.structureDictionary.structures(forByteOffset: byteRange.upperBound - 1)
|
||||
.contains(where: { dict -> Bool in
|
||||
return dict.expressionKind == .call && (dict.name ?? "").starts(with: "expect")
|
||||
})
|
||||
|
||||
return containsCall
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -144,7 +140,7 @@ public struct NimbleOperatorRule: ConfigurationProviderRule, OptInRule, Correcta
|
|||
.map { $0.0 }
|
||||
}
|
||||
|
||||
public func correct(file: SwiftLintFile) -> [Correction] {
|
||||
func correct(file: SwiftLintFile) -> [Correction] {
|
||||
let matches = violationMatchesRanges(in: file)
|
||||
.filter { file.ruleEnabled(violatingRanges: [$0], for: self).isNotEmpty }
|
||||
guard matches.isNotEmpty else { return [] }
|
|
@ -0,0 +1,39 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct NoExtensionAccessModifierRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.error)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "no_extension_access_modifier",
|
||||
name: "No Extension Access Modifier",
|
||||
description: "Prefer not to use extension access modifiers",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("extension String {}"),
|
||||
Example("\n\n extension String {}")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓private extension String {}"),
|
||||
Example("↓public \n extension String {}"),
|
||||
Example("↓open extension String {}"),
|
||||
Example("↓internal extension String {}"),
|
||||
Example("↓fileprivate extension String {}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension NoExtensionAccessModifierRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] { .all }
|
||||
|
||||
override func visitPost(_ node: ExtensionDeclSyntax) {
|
||||
if let modifiers = node.modifiers, modifiers.isNotEmpty {
|
||||
violations.append(modifiers.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct NoFallthroughOnlyRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "no_fallthrough_only",
|
||||
name: "No Fallthrough only",
|
||||
description: "Fallthroughs can only be used if the `case` contains at least one other statement",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: NoFallthroughOnlyRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: NoFallthroughOnlyRuleExamples.triggeringExamples
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension NoFallthroughOnlyRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: SwitchCaseListSyntax) {
|
||||
let cases = node.compactMap { $0.as(SwitchCaseSyntax.self) }
|
||||
|
||||
let localViolations = cases.enumerated()
|
||||
.compactMap { index, element -> AbsolutePosition? in
|
||||
if let fallthroughStmt = element.statements.onlyElement?.item.as(FallthroughStmtSyntax.self) {
|
||||
if case let nextCaseIndex = cases.index(after: index),
|
||||
nextCaseIndex < cases.endIndex,
|
||||
case let nextCase = cases[nextCaseIndex],
|
||||
nextCase.unknownAttr != nil {
|
||||
return nil
|
||||
}
|
||||
return fallthroughStmt.positionAfterSkippingLeadingTrivia
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
violations.append(contentsOf: localViolations)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,14 +1,12 @@
|
|||
import SourceKittenFramework
|
||||
|
||||
public struct NoGroupingExtensionRule: OptInRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct NoGroupingExtensionRule: OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "no_grouping_extension",
|
||||
name: "No Grouping Extension",
|
||||
description: "Extensions shouldn't be used to group code within the same source file.",
|
||||
description: "Extensions shouldn't be used to group code within the same source file",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("protocol Food {}\nextension Food {}\n"),
|
||||
|
@ -23,7 +21,7 @@ public struct NoGroupingExtensionRule: OptInRule, ConfigurationProviderRule {
|
|||
]
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
let collector = NamespaceCollector(dictionary: file.structureDictionary)
|
||||
let elements = collector.findAllElements(of: [.class, .enum, .struct, .extension])
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct NoMagicNumbersRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = NoMagicNumbersConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "no_magic_numbers",
|
||||
name: "No Magic Numbers",
|
||||
description: "Magic numbers should be replaced by named constants",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("var foo = 123"),
|
||||
Example("static let bar: Double = 0.123"),
|
||||
Example("let a = b + 1.0"),
|
||||
Example("array[0] + array[1] "),
|
||||
Example("let foo = 1_000.000_01"),
|
||||
Example("// array[1337]"),
|
||||
Example("baz(\"9999\")"),
|
||||
Example("""
|
||||
func foo() {
|
||||
let x: Int = 2
|
||||
let y = 3
|
||||
let vector = [x, y, -1]
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class A {
|
||||
var foo: Double = 132
|
||||
static let bar: Double = 0.98
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@available(iOS 13, *)
|
||||
func version() {
|
||||
if #available(iOS 13, OSX 10.10, *) {
|
||||
return
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Example: Int {
|
||||
case positive = 2
|
||||
case negative = -2
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class FooTests: XCTestCase {
|
||||
let array: [Int] = []
|
||||
let bar = array[42]
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class FooTests: XCTestCase {
|
||||
class Bar {
|
||||
let array: [Int] = []
|
||||
let bar = array[42]
|
||||
}
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("foo(↓321)"),
|
||||
Example("bar(↓1_000.005_01)"),
|
||||
Example("array[↓42]"),
|
||||
Example("let box = array[↓12 + ↓14]"),
|
||||
Example("let a = b + ↓2.0"),
|
||||
Example("Color.primary.opacity(isAnimate ? ↓0.1 : ↓1.5)")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate, testParentClasses: configuration.testParentClasses)
|
||||
}
|
||||
}
|
||||
|
||||
private extension NoMagicNumbersRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let testParentClasses: Set<String>
|
||||
|
||||
init(viewMode: SyntaxTreeViewMode, testParentClasses: Set<String>) {
|
||||
self.testParentClasses = testParentClasses
|
||||
super.init(viewMode: viewMode)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FloatLiteralExprSyntax) {
|
||||
if node.isMemberOfATestClass(testParentClasses) == false, node.floatingDigits.isMagicNumber {
|
||||
violations.append(node.floatingDigits.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
override func visitPost(_ node: IntegerLiteralExprSyntax) {
|
||||
if node.isMemberOfATestClass(testParentClasses) == false, node.digits.isMagicNumber {
|
||||
violations.append(node.digits.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TokenSyntax {
|
||||
var isMagicNumber: Bool {
|
||||
guard let number = Double(text.replacingOccurrences(of: "_", with: "")) else {
|
||||
return false
|
||||
}
|
||||
if [0, 1].contains(number) {
|
||||
return false
|
||||
}
|
||||
guard let grandparent = parent?.parent else {
|
||||
return true
|
||||
}
|
||||
return !grandparent.is(InitializerClauseSyntax.self)
|
||||
&& grandparent.as(PrefixOperatorExprSyntax.self)?.parent?.is(InitializerClauseSyntax.self) != true
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExprSyntaxProtocol {
|
||||
func isMemberOfATestClass(_ testParentClasses: Set<String>) -> Bool {
|
||||
var parent = parent
|
||||
while parent != nil {
|
||||
if
|
||||
let classDecl = parent?.as(ClassDeclSyntax.self),
|
||||
classDecl.isXCTestCase(testParentClasses)
|
||||
{
|
||||
return true
|
||||
}
|
||||
parent = parent?.parent
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct ObjectLiteralRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = ObjectLiteralConfiguration<Self>()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "object_literal",
|
||||
name: "Object Literal",
|
||||
description: "Prefer object literals over image and color inits",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("let image = #imageLiteral(resourceName: \"image.jpg\")"),
|
||||
Example("let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)"),
|
||||
Example("let image = UIImage(named: aVariable)"),
|
||||
Example("let image = UIImage(named: \"interpolated \\(variable)\")"),
|
||||
Example("let color = UIColor(red: value, green: value, blue: value, alpha: 1)"),
|
||||
Example("let image = NSImage(named: aVariable)"),
|
||||
Example("let image = NSImage(named: \"interpolated \\(variable)\")"),
|
||||
Example("let color = NSColor(red: value, green: value, blue: value, alpha: 1)")
|
||||
],
|
||||
triggeringExamples: ["", ".init"].flatMap { (method: String) -> [Example] in
|
||||
["UI", "NS"].flatMap { (prefix: String) -> [Example] in
|
||||
[
|
||||
Example("let image = ↓\(prefix)Image\(method)(named: \"foo\")"),
|
||||
Example("let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)"),
|
||||
// swiftlint:disable:next line_length
|
||||
Example("let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)"),
|
||||
Example("let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)")
|
||||
]
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(validateImageLiteral: configuration.imageLiteral, validateColorLiteral: configuration.colorLiteral)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ObjectLiteralRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let validateImageLiteral: Bool
|
||||
private let validateColorLiteral: Bool
|
||||
|
||||
init(validateImageLiteral: Bool, validateColorLiteral: Bool) {
|
||||
self.validateImageLiteral = validateImageLiteral
|
||||
self.validateColorLiteral = validateColorLiteral
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
guard validateColorLiteral || validateImageLiteral else {
|
||||
return
|
||||
}
|
||||
|
||||
let name = node.calledExpression.trimmedDescription
|
||||
if validateImageLiteral, isImageNamedInit(node: node, name: name) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
} else if validateColorLiteral, isColorInit(node: node, name: name) {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
private func isImageNamedInit(node: FunctionCallExprSyntax, name: String) -> Bool {
|
||||
guard inits(forClasses: ["UIImage", "NSImage"]).contains(name),
|
||||
node.argumentList.compactMap(\.label?.text) == ["named"],
|
||||
let argument = node.argumentList.first?.expression.as(StringLiteralExprSyntax.self),
|
||||
argument.isConstantString else {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private func isColorInit(node: FunctionCallExprSyntax, name: String) -> Bool {
|
||||
guard inits(forClasses: ["UIColor", "NSColor"]).contains(name),
|
||||
case let argumentsNames = node.argumentList.compactMap(\.label?.text),
|
||||
argumentsNames == ["red", "green", "blue", "alpha"] || argumentsNames == ["white", "alpha"] else {
|
||||
return false
|
||||
}
|
||||
|
||||
return node.argumentList.allSatisfy { elem in
|
||||
elem.expression.canBeExpressedAsColorLiteralParams
|
||||
}
|
||||
}
|
||||
|
||||
private func inits(forClasses names: [String]) -> [String] {
|
||||
return names.flatMap { name in
|
||||
[
|
||||
name,
|
||||
name + ".init"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension StringLiteralExprSyntax {
|
||||
var isConstantString: Bool {
|
||||
segments.allSatisfy { $0.is(StringSegmentSyntax.self) }
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExprSyntax {
|
||||
var canBeExpressedAsColorLiteralParams: Bool {
|
||||
if self.is(FloatLiteralExprSyntax.self) ||
|
||||
self.is(IntegerLiteralExprSyntax.self) ||
|
||||
self.is(BinaryOperatorExprSyntax.self) {
|
||||
return true
|
||||
}
|
||||
|
||||
if let expr = self.as(SequenceExprSyntax.self) {
|
||||
return expr.elements.allSatisfy(\.canBeExpressedAsColorLiteralParams)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct PatternMatchingKeywordsRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "pattern_matching_keywords",
|
||||
name: "Pattern Matching Keywords",
|
||||
description: "Combine multiple pattern matching bindings by moving keywords out of tuples",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("default"),
|
||||
Example("case 1"),
|
||||
Example("case bar"),
|
||||
Example("case let (x, y)"),
|
||||
Example("case .foo(let x)"),
|
||||
Example("case let .foo(x, y)"),
|
||||
Example("case .foo(let x), .bar(let x)"),
|
||||
Example("case .foo(let x, var y)"),
|
||||
Example("case var (x, y)"),
|
||||
Example("case .foo(var x)"),
|
||||
Example("case var .foo(x, y)")
|
||||
].map(wrapInSwitch),
|
||||
triggeringExamples: [
|
||||
Example("case (↓let x, ↓let y)"),
|
||||
Example("case (↓let x, ↓let y, .foo)"),
|
||||
Example("case (↓let x, ↓let y, _)"),
|
||||
Example("case .foo(↓let x, ↓let y)"),
|
||||
Example("case (.yamlParsing(↓let x), .yamlParsing(↓let y))"),
|
||||
Example("case (↓var x, ↓var y)"),
|
||||
Example("case .foo(↓var x, ↓var y)"),
|
||||
Example("case (.yamlParsing(↓var x), .yamlParsing(↓var y))")
|
||||
].map(wrapInSwitch)
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension PatternMatchingKeywordsRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: CaseItemSyntax) {
|
||||
let localViolations = TupleVisitor(viewMode: .sourceAccurate)
|
||||
.walk(tree: node.pattern, handler: \.violations)
|
||||
violations.append(contentsOf: localViolations)
|
||||
}
|
||||
}
|
||||
|
||||
final class TupleVisitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: TupleExprElementListSyntax) {
|
||||
let list = node.flatteningEnumPatterns()
|
||||
.compactMap { elem in
|
||||
elem.expression.asValueBindingPattern()
|
||||
}
|
||||
|
||||
guard list.count > 1,
|
||||
let firstLetOrVar = list.first?.bindingKeyword.tokenKind else {
|
||||
return
|
||||
}
|
||||
|
||||
let hasViolation = list.allSatisfy { elem in
|
||||
elem.bindingKeyword.tokenKind == firstLetOrVar
|
||||
}
|
||||
|
||||
guard hasViolation else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(contentsOf: list.compactMap { elem in
|
||||
return elem.bindingKeyword.positionAfterSkippingLeadingTrivia
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TupleExprElementListSyntax {
|
||||
func flatteningEnumPatterns() -> [TupleExprElementSyntax] {
|
||||
flatMap { elem in
|
||||
guard let pattern = elem.expression.as(FunctionCallExprSyntax.self),
|
||||
pattern.calledExpression.is(MemberAccessExprSyntax.self) else {
|
||||
return [elem]
|
||||
}
|
||||
|
||||
return Array(pattern.argumentList)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ExprSyntax {
|
||||
func asValueBindingPattern() -> ValueBindingPatternSyntax? {
|
||||
if let pattern = self.as(UnresolvedPatternExprSyntax.self) {
|
||||
return pattern.pattern.as(ValueBindingPatternSyntax.self)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func wrapInSwitch(_ example: Example) -> Example {
|
||||
return example.with(code: """
|
||||
switch foo {
|
||||
\(example.code): break
|
||||
}
|
||||
""")
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct PreferNimbleRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "prefer_nimble",
|
||||
name: "Prefer Nimble",
|
||||
description: "Prefer Nimble matchers over XCTAssert functions",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("expect(foo) == 1"),
|
||||
Example("expect(foo).to(equal(1))")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓XCTAssertTrue(foo)"),
|
||||
Example("↓XCTAssertEqual(foo, 2)"),
|
||||
Example("↓XCTAssertNotEqual(foo, 2)"),
|
||||
Example("↓XCTAssertNil(foo)"),
|
||||
Example("↓XCTAssert(foo)"),
|
||||
Example("↓XCTAssertGreaterThan(foo, 10)")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension PreferNimbleRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if let expr = node.calledExpression.as(IdentifierExprSyntax.self),
|
||||
expr.identifier.text.starts(with: "XCTAssert") {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct PreferZeroOverExplicitInitRule: SwiftSyntaxCorrectableRule, OptInRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "prefer_zero_over_explicit_init",
|
||||
name: "Prefer Zero Over Explicit Init",
|
||||
description: "Prefer `.zero` over explicit init with zero parameters (e.g. `CGPoint(x: 0, y: 0)`)",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("CGRect(x: 0, y: 0, width: 0, height: 1)"),
|
||||
Example("CGPoint(x: 0, y: -1)"),
|
||||
Example("CGSize(width: 2, height: 4)"),
|
||||
Example("CGVector(dx: -5, dy: 0)"),
|
||||
Example("UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓CGPoint(x: 0, y: 0)"),
|
||||
Example("↓CGPoint(x: 0.000000, y: 0)"),
|
||||
Example("↓CGPoint(x: 0.000000, y: 0.000)"),
|
||||
Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"),
|
||||
Example("↓CGSize(width: 0, height: 0)"),
|
||||
Example("↓CGVector(dx: 0, dy: 0)"),
|
||||
Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓CGPoint(x: 0, y: 0)"): Example("CGPoint.zero"),
|
||||
Example("(↓CGPoint(x: 0, y: 0))"): Example("(CGPoint.zero)"),
|
||||
Example("↓CGRect(x: 0, y: 0, width: 0, height: 0)"): Example("CGRect.zero"),
|
||||
Example("↓CGSize(width: 0, height: 0.000)"): Example("CGSize.zero"),
|
||||
Example("↓CGVector(dx: 0, dy: 0)"): Example("CGVector.zero"),
|
||||
Example("↓UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)"): Example("UIEdgeInsets.zero")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension PreferZeroOverExplicitInitRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: FunctionCallExprSyntax) {
|
||||
if node.hasViolation {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
|
||||
guard node.hasViolation,
|
||||
let name = node.name,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
|
||||
let newNode = MemberAccessExprSyntax(name: "zero")
|
||||
.with(\.base, "\(raw: name)")
|
||||
return super.visit(
|
||||
newNode
|
||||
.with(\.leadingTrivia, node.leadingTrivia)
|
||||
.with(\.trailingTrivia, node.trailingTrivia)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension FunctionCallExprSyntax {
|
||||
var hasViolation: Bool {
|
||||
isCGPointZeroCall ||
|
||||
isCGSizeCall ||
|
||||
isCGRectCall ||
|
||||
isCGVectorCall ||
|
||||
isUIEdgeInsetsCall
|
||||
}
|
||||
|
||||
var isCGPointZeroCall: Bool {
|
||||
return name == "CGPoint" &&
|
||||
argumentNames == ["x", "y"] &&
|
||||
argumentsAreAllZero
|
||||
}
|
||||
|
||||
var isCGSizeCall: Bool {
|
||||
return name == "CGSize" &&
|
||||
argumentNames == ["width", "height"] &&
|
||||
argumentsAreAllZero
|
||||
}
|
||||
|
||||
var isCGRectCall: Bool {
|
||||
return name == "CGRect" &&
|
||||
argumentNames == ["x", "y", "width", "height"] &&
|
||||
argumentsAreAllZero
|
||||
}
|
||||
|
||||
var isCGVectorCall: Bool {
|
||||
return name == "CGVector" &&
|
||||
argumentNames == ["dx", "dy"] &&
|
||||
argumentsAreAllZero
|
||||
}
|
||||
|
||||
var isUIEdgeInsetsCall: Bool {
|
||||
return name == "UIEdgeInsets" &&
|
||||
argumentNames == ["top", "left", "bottom", "right"] &&
|
||||
argumentsAreAllZero
|
||||
}
|
||||
|
||||
var name: String? {
|
||||
guard let expr = calledExpression.as(IdentifierExprSyntax.self) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return expr.identifier.text
|
||||
}
|
||||
|
||||
var argumentNames: [String?] {
|
||||
argumentList.map(\.label?.text)
|
||||
}
|
||||
|
||||
var argumentsAreAllZero: Bool {
|
||||
argumentList.allSatisfy { arg in
|
||||
if let intExpr = arg.expression.as(IntegerLiteralExprSyntax.self) {
|
||||
return intExpr.isZero
|
||||
} else if let floatExpr = arg.expression.as(FloatLiteralExprSyntax.self) {
|
||||
return floatExpr.isZero
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,272 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct PrivateOverFilePrivateRule: ConfigurationProviderRule, SwiftSyntaxCorrectableRule {
|
||||
var configuration = PrivateOverFilePrivateConfiguration()
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "private_over_fileprivate",
|
||||
name: "Private over Fileprivate",
|
||||
description: "Prefer `private` over `fileprivate` declarations",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("extension String {}"),
|
||||
Example("private extension String {}"),
|
||||
Example("public \n enum MyEnum {}"),
|
||||
Example("open extension \n String {}"),
|
||||
Example("internal extension String {}"),
|
||||
Example("""
|
||||
extension String {
|
||||
fileprivate func Something(){}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
fileprivate let myInt = 4
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class MyClass {
|
||||
fileprivate(set) var myInt = 4
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
struct Outter {
|
||||
struct Inter {
|
||||
fileprivate struct Inner {}
|
||||
}
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓fileprivate enum MyEnum {}"),
|
||||
Example("""
|
||||
↓fileprivate class MyClass {
|
||||
fileprivate(set) var myInt = 4
|
||||
}
|
||||
""")
|
||||
],
|
||||
corrections: [
|
||||
Example("↓fileprivate enum MyEnum {}"): Example("private enum MyEnum {}"),
|
||||
Example("↓fileprivate enum MyEnum { fileprivate class A {} }"):
|
||||
Example("private enum MyEnum { fileprivate class A {} }"),
|
||||
Example("↓fileprivate class MyClass {\nfileprivate(set) var myInt = 4\n}"):
|
||||
Example("private class MyClass {\nfileprivate(set) var myInt = 4\n}")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(validateExtensions: configuration.validateExtensions)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
validateExtensions: configuration.validateExtensions,
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension PrivateOverFilePrivateRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
private let validateExtensions: Bool
|
||||
|
||||
init(validateExtensions: Bool) {
|
||||
self.validateExtensions = validateExtensions
|
||||
super.init(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if validateExtensions, let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: ProtocolDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
|
||||
override func visit(_ node: TypealiasDeclSyntax) -> SyntaxVisitorContinueKind {
|
||||
if let privateModifier = node.modifiers.fileprivateModifier {
|
||||
violations.append(privateModifier.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
return .skipChildren
|
||||
}
|
||||
}
|
||||
|
||||
private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
private let validateExtensions: Bool
|
||||
private let locationConverter: SourceLocationConverter
|
||||
private let disabledRegions: [SourceRange]
|
||||
|
||||
init(validateExtensions: Bool, locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.validateExtensions = validateExtensions
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
// don't call super in any of the `visit` methods to avoid digging into the children
|
||||
override func visit(_ node: ExtensionDeclSyntax) -> DeclSyntax {
|
||||
guard validateExtensions, let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: ClassDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: StructDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: EnumDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: ProtocolDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: FunctionDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: VariableDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
|
||||
override func visit(_ node: TypealiasDeclSyntax) -> DeclSyntax {
|
||||
guard let modifier = node.modifiers.fileprivateModifier,
|
||||
let modifierIndex = node.modifiers.fileprivateModifierIndex,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else {
|
||||
return DeclSyntax(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(modifier.positionAfterSkippingLeadingTrivia)
|
||||
let newNode = node.with(\.modifiers, node.modifiers?.replacing(fileprivateModifierIndex: modifierIndex))
|
||||
return DeclSyntax(newNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ModifierListSyntax? {
|
||||
var fileprivateModifierIndex: ModifierListSyntax.Index? {
|
||||
self?.firstIndex(where: { $0.name.tokenKind == .keyword(.fileprivate) })
|
||||
}
|
||||
|
||||
var fileprivateModifier: DeclModifierSyntax? {
|
||||
fileprivateModifierIndex.flatMap { self?[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
private extension ModifierListSyntax {
|
||||
func replacing(fileprivateModifierIndex: ModifierListSyntax.Index) -> ModifierListSyntax? {
|
||||
let fileprivateModifier = self[fileprivateModifierIndex]
|
||||
return replacing(
|
||||
childAt: self.distance(from: self.startIndex, to: fileprivateModifierIndex),
|
||||
with: fileprivateModifier.with(
|
||||
\.name,
|
||||
.keyword(
|
||||
.private,
|
||||
leadingTrivia: fileprivateModifier.leadingTrivia,
|
||||
trailingTrivia: fileprivateModifier.trailingTrivia
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct RedundantNilCoalescingRule: OptInRule, SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_nil_coalescing",
|
||||
name: "Redundant Nil Coalescing",
|
||||
description: "nil coalescing operator is only evaluated if the lhs is nil" +
|
||||
", coalescing operator with nil as rhs is redundant",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("var myVar: Int?; myVar ?? 0\n")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("var myVar: Int? = nil; myVar ↓?? nil\n")
|
||||
],
|
||||
corrections: [
|
||||
Example("var myVar: Int? = nil; let foo = myVar↓ ?? nil\n"):
|
||||
Example("var myVar: Int? = nil; let foo = myVar\n")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension RedundantNilCoalescingRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: TokenSyntax) {
|
||||
if node.tokenKind.isNilCoalescingOperator,
|
||||
node.nextToken(viewMode: .sourceAccurate)?.tokenKind == .keyword(.nil) {
|
||||
violations.append(node.position)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
let locationConverter: SourceLocationConverter
|
||||
let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: ExprListSyntax) -> ExprListSyntax {
|
||||
guard
|
||||
node.count > 2,
|
||||
let lastExpression = node.last,
|
||||
lastExpression.is(NilLiteralExprSyntax.self),
|
||||
let secondToLastExpression = node.dropLast().last?.as(BinaryOperatorExprSyntax.self),
|
||||
secondToLastExpression.operatorToken.tokenKind.isNilCoalescingOperator,
|
||||
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
let newNode = node.removingLast().removingLast().with(\.trailingTrivia, [])
|
||||
correctionPositions.append(newNode.endPosition)
|
||||
return super.visit(newNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TokenKind {
|
||||
var isNilCoalescingOperator: Bool {
|
||||
self == .binaryOperator("??")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
import Foundation
|
||||
import SwiftSyntax
|
||||
|
||||
private let attributeNamesImplyingObjc: Set<String> = [
|
||||
"IBAction", "IBOutlet", "IBInspectable", "GKInspectable", "IBDesignable", "NSManaged"
|
||||
]
|
||||
|
||||
struct RedundantObjcAttributeRule: SwiftSyntaxRule, SubstitutionCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_objc_attribute",
|
||||
name: "Redundant @objc Attribute",
|
||||
description: "Objective-C attribute (@objc) is redundant in declaration",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: RedundantObjcAttributeRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: RedundantObjcAttributeRuleExamples.triggeringExamples,
|
||||
corrections: RedundantObjcAttributeRuleExamples.corrections
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: AttributeListSyntax) {
|
||||
if let objcAttribute = node.violatingObjCAttribute {
|
||||
violations.append(objcAttribute.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
||||
return Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func violationRanges(in file: SwiftLintFile) -> [NSRange] {
|
||||
makeVisitor(file: file)
|
||||
.walk(tree: file.syntaxTree, handler: \.violations)
|
||||
.compactMap { violation in
|
||||
let end = AbsolutePosition(utf8Offset: violation.position.utf8Offset + "@objc".count)
|
||||
return file.stringView.NSRange(start: violation.position, end: end)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension AttributeListSyntax {
|
||||
var objCAttribute: AttributeSyntax? {
|
||||
lazy
|
||||
.compactMap { $0.as(AttributeSyntax.self) }
|
||||
.first { $0.attributeNameText == "objc" && $0.argument == nil }
|
||||
}
|
||||
|
||||
var hasAttributeImplyingObjC: Bool {
|
||||
contains { element in
|
||||
guard let attributeName = element.as(AttributeSyntax.self)?.attributeNameText else {
|
||||
return false
|
||||
}
|
||||
|
||||
return attributeNamesImplyingObjc.contains(attributeName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension Syntax {
|
||||
var isFunctionOrStoredProperty: Bool {
|
||||
if self.is(FunctionDeclSyntax.self) {
|
||||
return true
|
||||
} else if let variableDecl = self.as(VariableDeclSyntax.self),
|
||||
variableDecl.bindings.allSatisfy({ $0.accessor == nil }) {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
var functionOrVariableModifiers: ModifierListSyntax? {
|
||||
if let functionDecl = self.as(FunctionDeclSyntax.self) {
|
||||
return functionDecl.modifiers
|
||||
} else if let variableDecl = self.as(VariableDeclSyntax.self) {
|
||||
return variableDecl.modifiers
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private extension AttributeListSyntax {
|
||||
var violatingObjCAttribute: AttributeSyntax? {
|
||||
guard let objcAttribute = objCAttribute else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if hasAttributeImplyingObjC, parent?.is(ExtensionDeclSyntax.self) != true {
|
||||
return objcAttribute
|
||||
} else if parent?.is(EnumDeclSyntax.self) == true {
|
||||
return nil
|
||||
} else if parent?.isFunctionOrStoredProperty == true,
|
||||
let parentClassDecl = parent?.parent?.parent?.parent?.parent?.as(ClassDeclSyntax.self),
|
||||
parentClassDecl.attributes.contains(attributeNamed: "objcMembers") {
|
||||
return parent?.functionOrVariableModifiers.isPrivateOrFileprivate == true ? nil : objcAttribute
|
||||
} else if let parentExtensionDecl = parent?.parent?.parent?.parent?.parent?.as(ExtensionDeclSyntax.self),
|
||||
parentExtensionDecl.attributes?.objCAttribute != nil {
|
||||
return objcAttribute
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RedundantObjcAttributeRule {
|
||||
func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? {
|
||||
var whitespaceAndNewlineOffset = 0
|
||||
let nsCharSet = CharacterSet.whitespacesAndNewlines.bridge()
|
||||
let nsContent = file.contents.bridge()
|
||||
while nsCharSet
|
||||
.characterIsMember(nsContent.character(at: violationRange.upperBound + whitespaceAndNewlineOffset)) {
|
||||
whitespaceAndNewlineOffset += 1
|
||||
}
|
||||
|
||||
let withTrailingWhitespaceAndNewlineRange = NSRange(location: violationRange.location,
|
||||
length: violationRange.length + whitespaceAndNewlineOffset)
|
||||
return (withTrailingWhitespaceAndNewlineRange, "")
|
||||
}
|
||||
}
|
|
@ -1,4 +1,3 @@
|
|||
// swiftlint:disable:next type_body_length
|
||||
struct RedundantObjcAttributeRuleExamples {
|
||||
static let nonTriggeringExamples = [
|
||||
Example("@objc private var foo: String? {}"),
|
||||
|
@ -14,7 +13,7 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
class Foo {
|
||||
var bar: Any?
|
||||
@objc
|
||||
class Bar {
|
||||
class Bar: NSObject {
|
||||
@objc
|
||||
var foo: Any?
|
||||
}
|
||||
|
@ -60,16 +59,76 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
@objc
|
||||
class Bar: NSObject {
|
||||
@objc var foo: Any
|
||||
@objc var foo: Any?
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
@objc class Bar {}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
extension BlockEditorSettings {
|
||||
@objc(addElementsObject:)
|
||||
@NSManaged public func addToElements(_ value: BlockEditorSettingElement)
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
public class Foo: NSObject {
|
||||
@objc
|
||||
private func handler(_ notification: Notification) {
|
||||
}
|
||||
|
||||
func registerForNotifications() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(handler(_:)), name: nil, object: nil)
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: NSObject { }
|
||||
|
||||
@objc extension Foo {
|
||||
@objc enum Bar: Int {
|
||||
case bar
|
||||
}
|
||||
|
||||
var bar: Bar { .bar }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class Foo: NSObject { }
|
||||
|
||||
@objc extension Foo {
|
||||
@objc private enum Baz: Int {
|
||||
case baz
|
||||
}
|
||||
|
||||
private var baz: Baz { .baz }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
internal class Foo: NSObject {
|
||||
@objc
|
||||
private var baz: Int = 1
|
||||
|
||||
var x: Any? {
|
||||
value(forKey: "baz")
|
||||
}
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo: NSObject {
|
||||
@objc enum Bar: Int {
|
||||
case bar
|
||||
}
|
||||
}
|
||||
""")
|
||||
]
|
||||
|
||||
|
@ -85,13 +144,13 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
Example("↓@objc @IBDesignable class Foo {}"),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
↓@objc var bar: Any?
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
↓@objc var bar: Any?
|
||||
↓@objc var foo: Any?
|
||||
@objc
|
||||
|
@ -121,7 +180,7 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
@objcMembers
|
||||
class Bar: NSObject {
|
||||
↓@objc var foo: Any
|
||||
|
@ -155,23 +214,23 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
Example("↓@objc @IBDesignable class Foo {}"): Example("@IBDesignable class Foo {}"),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
↓@objc var bar: Any?
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
var bar: Any?
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
↓@objc var bar: Any?
|
||||
↓@objc var foo: Any?
|
||||
@objc
|
||||
class Bar {
|
||||
class Bar: NSObject {
|
||||
@objc
|
||||
var foo2: Any?
|
||||
}
|
||||
|
@ -179,11 +238,11 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
"""):
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
var bar: Any?
|
||||
var foo: Any?
|
||||
@objc
|
||||
class Bar {
|
||||
class Bar: NSObject {
|
||||
@objc
|
||||
var foo2: Any?
|
||||
}
|
||||
|
@ -225,7 +284,7 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
"""),
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
@objcMembers
|
||||
class Bar: NSObject {
|
||||
↓@objc var foo: Any
|
||||
|
@ -234,7 +293,7 @@ struct RedundantObjcAttributeRuleExamples {
|
|||
"""):
|
||||
Example("""
|
||||
@objcMembers
|
||||
class Foo {
|
||||
class Foo: NSObject {
|
||||
@objcMembers
|
||||
class Bar: NSObject {
|
||||
var foo: Any
|
|
@ -0,0 +1,212 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct RedundantOptionalInitializationRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_optional_initialization",
|
||||
name: "Redundant Optional Initialization",
|
||||
description: "Initializing an optional variable with nil is redundant",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("var myVar: Int?\n"),
|
||||
Example("let myVar: Int? = nil\n"),
|
||||
Example("var myVar: Int? = 0\n"),
|
||||
Example("func foo(bar: Int? = 0) { }\n"),
|
||||
Example("var myVar: Optional<Int>\n"),
|
||||
Example("let myVar: Optional<Int> = nil\n"),
|
||||
Example("var myVar: Optional<Int> = 0\n"),
|
||||
// properties with body should be ignored
|
||||
Example("""
|
||||
var foo: Int? {
|
||||
if bar != nil { }
|
||||
return 0
|
||||
}
|
||||
"""),
|
||||
// properties with a closure call
|
||||
Example("""
|
||||
var foo: Int? = {
|
||||
if bar != nil { }
|
||||
return 0
|
||||
}()
|
||||
"""),
|
||||
// lazy variables need to be initialized
|
||||
Example("lazy var test: Int? = nil"),
|
||||
// local variables
|
||||
Example("""
|
||||
func funcName() {
|
||||
var myVar: String?
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func funcName() {
|
||||
let myVar: String? = nil
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: triggeringExamples,
|
||||
corrections: corrections
|
||||
)
|
||||
|
||||
private static let triggeringExamples: [Example] = [
|
||||
Example("var myVar: Int?↓ = nil\n"),
|
||||
Example("var myVar: Optional<Int>↓ = nil\n"),
|
||||
Example("var myVar: Int?↓=nil\n"),
|
||||
Example("var myVar: Optional<Int>↓=nil\n)"),
|
||||
Example("""
|
||||
var myVar: String?↓ = nil {
|
||||
didSet { print("didSet") }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func funcName() {
|
||||
var myVar: String?↓ = nil
|
||||
}
|
||||
""")
|
||||
]
|
||||
|
||||
private static let corrections: [Example: Example] = [
|
||||
Example("var myVar: Int?↓ = nil\n"): Example("var myVar: Int?\n"),
|
||||
Example("var myVar: Optional<Int>↓ = nil\n"): Example("var myVar: Optional<Int>\n"),
|
||||
Example("var myVar: Int?↓=nil\n"): Example("var myVar: Int?\n"),
|
||||
Example("var myVar: Optional<Int>↓=nil\n"): Example("var myVar: Optional<Int>\n"),
|
||||
Example("class C {\n#if true\nvar myVar: Int?↓ = nil\n#endif\n}"):
|
||||
Example("class C {\n#if true\nvar myVar: Int?\n#endif\n}"),
|
||||
Example("""
|
||||
var myVar: Int?↓ = nil {
|
||||
didSet { }
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
var myVar: Int? {
|
||||
didSet { }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
var myVar: Int?↓=nil{
|
||||
didSet { }
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
var myVar: Int?{
|
||||
didSet { }
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
func foo() {
|
||||
var myVar: String?↓ = nil, b: Int
|
||||
}
|
||||
"""):
|
||||
Example("""
|
||||
func foo() {
|
||||
var myVar: String?, b: Int
|
||||
}
|
||||
""")
|
||||
]
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
|
||||
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
|
||||
Rewriter(
|
||||
locationConverter: file.locationConverter,
|
||||
disabledRegions: disabledRegions(file: file)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension RedundantOptionalInitializationRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
guard node.bindingKeyword.tokenKind == .keyword(.var),
|
||||
!node.modifiers.containsLazy else {
|
||||
return
|
||||
}
|
||||
|
||||
violations.append(contentsOf: node.bindings.compactMap(\.violationPosition))
|
||||
}
|
||||
}
|
||||
|
||||
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
|
||||
private(set) var correctionPositions: [AbsolutePosition] = []
|
||||
private let locationConverter: SourceLocationConverter
|
||||
private let disabledRegions: [SourceRange]
|
||||
|
||||
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
|
||||
self.locationConverter = locationConverter
|
||||
self.disabledRegions = disabledRegions
|
||||
}
|
||||
|
||||
override func visit(_ node: VariableDeclSyntax) -> DeclSyntax {
|
||||
guard node.bindingKeyword.tokenKind == .keyword(.var),
|
||||
!node.modifiers.containsLazy else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
let violations = node.bindings
|
||||
.compactMap { binding in
|
||||
binding.violationPosition.map { ($0, binding) }
|
||||
}
|
||||
.filter { position, _ in
|
||||
!position.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
|
||||
}
|
||||
|
||||
guard violations.isNotEmpty else {
|
||||
return super.visit(node)
|
||||
}
|
||||
|
||||
correctionPositions.append(contentsOf: violations.map(\.0))
|
||||
|
||||
let violatingBindings = violations.map(\.1)
|
||||
let newBindings = PatternBindingListSyntax(node.bindings.map { binding in
|
||||
guard violatingBindings.contains(binding) else {
|
||||
return binding
|
||||
}
|
||||
let newBinding = binding.with(\.initializer, nil)
|
||||
if newBinding.accessor != nil {
|
||||
return newBinding
|
||||
}
|
||||
if binding.trailingComma != nil {
|
||||
return newBinding.with(\.typeAnnotation, binding.typeAnnotation?.with(\.trailingTrivia, Trivia()))
|
||||
}
|
||||
return newBinding.with(\.trailingTrivia, binding.initializer?.trailingTrivia ?? Trivia())
|
||||
})
|
||||
|
||||
return super.visit(node.with(\.bindings, newBindings))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension PatternBindingSyntax {
|
||||
var violationPosition: AbsolutePosition? {
|
||||
guard let initializer,
|
||||
let type = typeAnnotation,
|
||||
initializer.isInitializingToNil,
|
||||
type.isOptionalType else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return type.endPositionBeforeTrailingTrivia
|
||||
}
|
||||
}
|
||||
|
||||
private extension InitializerClauseSyntax {
|
||||
var isInitializingToNil: Bool {
|
||||
value.is(NilLiteralExprSyntax.self)
|
||||
}
|
||||
}
|
||||
|
||||
private extension TypeAnnotationSyntax {
|
||||
var isOptionalType: Bool {
|
||||
if type.is(OptionalTypeSyntax.self) {
|
||||
return true
|
||||
}
|
||||
|
||||
if let type = type.as(SimpleTypeIdentifierSyntax.self), let genericClause = type.genericArgumentClause {
|
||||
return genericClause.arguments.count == 1 && type.name.text == "Optional"
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct RedundantSetAccessControlRule: ConfigurationProviderRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_set_access_control",
|
||||
name: "Redundant Access Control for Setter",
|
||||
description: "Property setter access level shouldn't be explicit if " +
|
||||
"it's the same as the variable access level",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("private(set) public var foo: Int"),
|
||||
Example("public let foo: Int"),
|
||||
Example("public var foo: Int"),
|
||||
Example("var foo: Int"),
|
||||
Example("""
|
||||
private final class A {
|
||||
private(set) var value: Int
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
fileprivate class A {
|
||||
public fileprivate(set) var value: Int
|
||||
}
|
||||
""", excludeFromDocumentation: true),
|
||||
Example("""
|
||||
extension Color {
|
||||
public internal(set) static var someColor = Color.anotherColor
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("↓private(set) private var foo: Int"),
|
||||
Example("↓fileprivate(set) fileprivate var foo: Int"),
|
||||
Example("↓internal(set) internal var foo: Int"),
|
||||
Example("↓public(set) public var foo: Int"),
|
||||
Example("""
|
||||
open class Foo {
|
||||
↓open(set) open var bar: Int
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
class A {
|
||||
↓internal(set) var value: Int
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
internal class A {
|
||||
↓internal(set) var value: Int
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
fileprivate class A {
|
||||
↓fileprivate(set) var value: Int
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension RedundantSetAccessControlRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override var skippableDeclarations: [DeclSyntaxProtocol.Type] {
|
||||
[FunctionDeclSyntax.self]
|
||||
}
|
||||
|
||||
override func visitPost(_ node: VariableDeclSyntax) {
|
||||
guard let modifiers = node.modifiers, let setAccessor = modifiers.setAccessor else {
|
||||
return
|
||||
}
|
||||
|
||||
let uniqueModifiers = Set(modifiers.map(\.name.tokenKind))
|
||||
if uniqueModifiers.count != modifiers.count {
|
||||
violations.append(modifiers.positionAfterSkippingLeadingTrivia)
|
||||
return
|
||||
}
|
||||
|
||||
if setAccessor.name.tokenKind == .keyword(.fileprivate),
|
||||
modifiers.getAccessor == nil,
|
||||
let closestDeclModifiers = node.closestDecl()?.modifiers {
|
||||
let closestDeclIsFilePrivate = closestDeclModifiers.contains {
|
||||
$0.name.tokenKind == .keyword(.fileprivate)
|
||||
}
|
||||
|
||||
if closestDeclIsFilePrivate {
|
||||
violations.append(modifiers.positionAfterSkippingLeadingTrivia)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if setAccessor.name.tokenKind == .keyword(.internal),
|
||||
modifiers.getAccessor == nil,
|
||||
let closesDecl = node.closestDecl(),
|
||||
let closestDeclModifiers = closesDecl.modifiers {
|
||||
let closestDeclIsInternal = closestDeclModifiers.isEmpty || closestDeclModifiers.contains {
|
||||
$0.name.tokenKind == .keyword(.internal)
|
||||
}
|
||||
|
||||
if closestDeclIsInternal {
|
||||
violations.append(modifiers.positionAfterSkippingLeadingTrivia)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension SyntaxProtocol {
|
||||
func closestDecl() -> DeclSyntax? {
|
||||
if let decl = self.parent?.as(DeclSyntax.self) {
|
||||
return decl
|
||||
}
|
||||
|
||||
return parent?.closestDecl()
|
||||
}
|
||||
}
|
||||
|
||||
private extension DeclSyntax {
|
||||
var modifiers: ModifierListSyntax? {
|
||||
if let decl = self.as(ClassDeclSyntax.self) {
|
||||
return decl.modifiers ?? ModifierListSyntax([])
|
||||
} else if let decl = self.as(ActorDeclSyntax.self) {
|
||||
return decl.modifiers ?? ModifierListSyntax([])
|
||||
} else if let decl = self.as(StructDeclSyntax.self) {
|
||||
return decl.modifiers ?? ModifierListSyntax([])
|
||||
} else if let decl = self.as(ProtocolDeclSyntax.self) {
|
||||
return decl.modifiers ?? ModifierListSyntax([])
|
||||
} else if let decl = self.as(ExtensionDeclSyntax.self) {
|
||||
return decl.modifiers ?? ModifierListSyntax([])
|
||||
} else if let decl = self.as(EnumDeclSyntax.self) {
|
||||
return decl.modifiers ?? ModifierListSyntax([])
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private extension ModifierListSyntax {
|
||||
var setAccessor: DeclModifierSyntax? {
|
||||
first { $0.detail?.detail.tokenKind == .identifier("set") }
|
||||
}
|
||||
|
||||
var getAccessor: DeclModifierSyntax? {
|
||||
first { $0.detail == nil }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,112 @@
|
|||
import SwiftSyntax
|
||||
|
||||
struct RedundantStringEnumValueRule: SwiftSyntaxRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_string_enum_value",
|
||||
name: "Redundant String Enum Value",
|
||||
description: "String enum values can be omitted when they are equal to the enumcase name",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one
|
||||
case two
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: Int {
|
||||
case one = 1
|
||||
case two = 2
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one = "ONE"
|
||||
case two = "TWO"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one = "ONE"
|
||||
case two = "two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one, two
|
||||
}
|
||||
""")
|
||||
],
|
||||
triggeringExamples: [
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one = ↓"one"
|
||||
case two = ↓"two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one = ↓"one", two = ↓"two"
|
||||
}
|
||||
"""),
|
||||
Example("""
|
||||
enum Numbers: String {
|
||||
case one, two = ↓"two"
|
||||
}
|
||||
""")
|
||||
]
|
||||
)
|
||||
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
Visitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private extension RedundantStringEnumValueRule {
|
||||
final class Visitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: EnumDeclSyntax) {
|
||||
guard node.isStringEnum else {
|
||||
return
|
||||
}
|
||||
|
||||
let enumsWithExplicitValues = node.memberBlock.members
|
||||
.flatMap { member -> EnumCaseElementListSyntax in
|
||||
guard let enumCaseDecl = member.decl.as(EnumCaseDeclSyntax.self) else {
|
||||
return EnumCaseElementListSyntax([])
|
||||
}
|
||||
|
||||
return enumCaseDecl.elements
|
||||
}
|
||||
.filter { $0.rawValue != nil }
|
||||
|
||||
let redundantMembersPositions = enumsWithExplicitValues
|
||||
.compactMap { element -> AbsolutePosition? in
|
||||
guard let stringExpr = element.rawValue?.value.as(StringLiteralExprSyntax.self),
|
||||
let segment = stringExpr.segments.onlyElement?.as(StringSegmentSyntax.self),
|
||||
segment.content.text == element.identifier.text else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return stringExpr.positionAfterSkippingLeadingTrivia
|
||||
}
|
||||
|
||||
if redundantMembersPositions.count == enumsWithExplicitValues.count {
|
||||
violations.append(contentsOf: redundantMembersPositions)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension EnumDeclSyntax {
|
||||
var isStringEnum: Bool {
|
||||
guard let inheritanceClause else {
|
||||
return false
|
||||
}
|
||||
|
||||
return inheritanceClause.inheritedTypeCollection.contains { elem in
|
||||
elem.typeName.as(SimpleTypeIdentifierSyntax.self)?.typeName == "String"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,10 +1,10 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRule, ConfigurationProviderRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRule, ConfigurationProviderRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_type_annotation",
|
||||
name: "Redundant Type Annotation",
|
||||
description: "Variables should not have redundant type annotation",
|
||||
|
@ -76,7 +76,7 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul
|
|||
]
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
return violationRanges(in: file).map { range in
|
||||
StyleViolation(
|
||||
ruleDescription: Self.description,
|
||||
|
@ -86,14 +86,14 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul
|
|||
}
|
||||
}
|
||||
|
||||
public func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? {
|
||||
func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? {
|
||||
return (violationRange, "")
|
||||
}
|
||||
|
||||
private let typeAnnotationPattern: String
|
||||
private let expressionPattern: String
|
||||
|
||||
public init() {
|
||||
init() {
|
||||
typeAnnotationPattern =
|
||||
":\\s*" + // semicolon and any number of whitespaces
|
||||
"\\w+" // type name
|
||||
|
@ -109,8 +109,8 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul
|
|||
"[\\(\\.]?" // possible opening parenthesis or dot
|
||||
}
|
||||
|
||||
public func violationRanges(in file: SwiftLintFile) -> [NSRange] {
|
||||
let violatingRanges = file
|
||||
func violationRanges(in file: SwiftLintFile) -> [NSRange] {
|
||||
return file
|
||||
.match(pattern: expressionPattern)
|
||||
.filter {
|
||||
$0.1 == [.keyword, .identifier, .typeidentifier, .identifier] ||
|
||||
|
@ -122,8 +122,6 @@ public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRul
|
|||
file.match(pattern: typeAnnotationPattern,
|
||||
excludingSyntaxKinds: SyntaxKind.commentAndStringKinds, range: $0.0).first
|
||||
}
|
||||
|
||||
return violatingRanges
|
||||
}
|
||||
|
||||
private func isFalsePositive(file: SwiftLintFile, range: NSRange) -> Bool {
|
|
@ -1,15 +1,13 @@
|
|||
import Foundation
|
||||
import SourceKittenFramework
|
||||
|
||||
public struct RedundantVoidReturnRule: ConfigurationProviderRule, SubstitutionCorrectableASTRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct RedundantVoidReturnRule: ConfigurationProviderRule, SubstitutionCorrectableASTRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "redundant_void_return",
|
||||
name: "Redundant Void Return",
|
||||
description: "Returning Void in a function declaration is redundant.",
|
||||
description: "Returning Void in a function declaration is redundant",
|
||||
kind: .idiomatic,
|
||||
nonTriggeringExamples: [
|
||||
Example("func foo() {}\n"),
|
||||
|
@ -60,8 +58,8 @@ public struct RedundantVoidReturnRule: ConfigurationProviderRule, SubstitutionCo
|
|||
private let excludingKinds = SyntaxKind.allKinds.subtracting([.typeidentifier])
|
||||
private let functionKinds = SwiftDeclarationKind.functionKinds.subtracting([.functionSubscript])
|
||||
|
||||
public func validate(file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
func validate(file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [StyleViolation] {
|
||||
return violationRanges(in: file, kind: kind, dictionary: dictionary).map {
|
||||
StyleViolation(ruleDescription: Self.description,
|
||||
severity: configuration.severity,
|
||||
|
@ -69,8 +67,8 @@ public struct RedundantVoidReturnRule: ConfigurationProviderRule, SubstitutionCo
|
|||
}
|
||||
}
|
||||
|
||||
public func violationRanges(in file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [NSRange] {
|
||||
func violationRanges(in file: SwiftLintFile, kind: SwiftDeclarationKind,
|
||||
dictionary: SourceKittenDictionary) -> [NSRange] {
|
||||
guard functionKinds.contains(kind),
|
||||
containsVoidReturnTypeBasedOnTypeName(dictionary: dictionary),
|
||||
let nameOffset = dictionary.nameOffset,
|
||||
|
@ -90,7 +88,7 @@ public struct RedundantVoidReturnRule: ConfigurationProviderRule, SubstitutionCo
|
|||
return [match]
|
||||
}
|
||||
|
||||
public func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? {
|
||||
func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? {
|
||||
return (violationRange, "")
|
||||
}
|
||||
|
|
@ -1,45 +1,29 @@
|
|||
import SourceKittenFramework
|
||||
import SwiftSyntax
|
||||
|
||||
public struct ReturnValueFromVoidFunctionRule: ConfigurationProviderRule, OptInRule, SourceKitFreeRule {
|
||||
public var configuration = SeverityConfiguration(.warning)
|
||||
struct ReturnValueFromVoidFunctionRule: ConfigurationProviderRule, OptInRule, SwiftSyntaxRule {
|
||||
var configuration = SeverityConfiguration<Self>(.warning)
|
||||
|
||||
public init() {}
|
||||
|
||||
public static let description = RuleDescription(
|
||||
static let description = RuleDescription(
|
||||
identifier: "return_value_from_void_function",
|
||||
name: "Return Value from Void Function",
|
||||
description: "Returning values from Void functions should be avoided.",
|
||||
description: "Returning values from Void functions should be avoided",
|
||||
kind: .idiomatic,
|
||||
minSwiftVersion: .fiveDotOne,
|
||||
nonTriggeringExamples: ReturnValueFromVoidFunctionRuleExamples.nonTriggeringExamples,
|
||||
triggeringExamples: ReturnValueFromVoidFunctionRuleExamples.triggeringExamples
|
||||
)
|
||||
|
||||
public func validate(file: SwiftLintFile) -> [StyleViolation] {
|
||||
ReturnValueFromVoidFunctionVisitor()
|
||||
.walk(file: file) { visitor in
|
||||
visitor.violations(for: self, in: file)
|
||||
}
|
||||
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
|
||||
ReturnValueFromVoidFunctionVisitor(viewMode: .sourceAccurate)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ReturnValueFromVoidFunctionVisitor: SyntaxVisitor {
|
||||
private var positions = [AbsolutePosition]()
|
||||
|
||||
private final class ReturnValueFromVoidFunctionVisitor: ViolationsSyntaxVisitor {
|
||||
override func visitPost(_ node: ReturnStmtSyntax) {
|
||||
if node.expression != nil,
|
||||
let functionNode = Syntax(node).enclosingFunction(),
|
||||
functionNode.returnsVoid {
|
||||
positions.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
|
||||
func violations(for rule: ReturnValueFromVoidFunctionRule, in file: SwiftLintFile) -> [StyleViolation] {
|
||||
return positions.map { position in
|
||||
StyleViolation(ruleDescription: type(of: rule).description,
|
||||
severity: rule.configuration.severity,
|
||||
location: Location(file: file, byteOffset: ByteCount(position.utf8Offset)))
|
||||
functionNode.returnsVoid {
|
||||
violations.append(node.positionAfterSkippingLeadingTrivia)
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue