diff options
198 files changed, 6076 insertions, 1879 deletions
diff --git a/.github/actions/github-release/main.js b/.github/actions/github-release/main.js index b499cd0fd..a08e59a91 100644 --- a/.github/actions/github-release/main.js +++ b/.github/actions/github-release/main.js | |||
@@ -70,6 +70,7 @@ async function runOnce() { | |||
70 | repo, | 70 | repo, |
71 | name, | 71 | name, |
72 | tag_name: name, | 72 | tag_name: name, |
73 | target_commitish: sha, | ||
73 | prerelease: name === 'nightly', | 74 | prerelease: name === 'nightly', |
74 | }); | 75 | }); |
75 | 76 | ||
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 1ae8ed1b6..c1d56a8e0 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml | |||
@@ -79,16 +79,16 @@ jobs: | |||
79 | with: | 79 | with: |
80 | node-version: 12.x | 80 | node-version: 12.x |
81 | 81 | ||
82 | - run: echo "::set-env name=TAG::$(date --iso --utc)" | 82 | - run: echo "TAG=$(date --iso --utc)" >> $GITHUB_ENV |
83 | if: github.ref == 'refs/heads/release' | 83 | if: github.ref == 'refs/heads/release' |
84 | - run: echo "::set-env name=TAG::nightly" | 84 | - run: echo "TAG=nightly" >> $GITHUB_ENV |
85 | if: github.ref != 'refs/heads/release' | 85 | if: github.ref != 'refs/heads/release' |
86 | - run: 'echo "TAG: $TAG"' | 86 | - run: 'echo "TAG: $TAG"' |
87 | 87 | ||
88 | - name: Checkout repository | 88 | - name: Checkout repository |
89 | uses: actions/checkout@v2 | 89 | uses: actions/checkout@v2 |
90 | 90 | ||
91 | - run: echo "::set-env name=HEAD_SHA::$(git rev-parse HEAD)" | 91 | - run: echo "HEAD_SHA=$(git rev-parse HEAD)" >> $GITHUB_ENV |
92 | - run: 'echo "HEAD_SHA: $HEAD_SHA"' | 92 | - run: 'echo "HEAD_SHA: $HEAD_SHA"' |
93 | 93 | ||
94 | - uses: actions/download-artifact@v1 | 94 | - uses: actions/download-artifact@v1 |
diff --git a/.gitignore b/.gitignore index 472fe1a13..b205bf3fb 100644 --- a/.gitignore +++ b/.gitignore | |||
@@ -9,3 +9,4 @@ crates/*/target | |||
9 | .vscode/settings.json | 9 | .vscode/settings.json |
10 | generated_assists.adoc | 10 | generated_assists.adoc |
11 | generated_features.adoc | 11 | generated_features.adoc |
12 | generated_diagnostic.adoc | ||
diff --git a/Cargo.lock b/Cargo.lock index d470d84f2..fe211b9b3 100644 --- a/Cargo.lock +++ b/Cargo.lock | |||
@@ -42,15 +42,14 @@ version = "0.0.0" | |||
42 | 42 | ||
43 | [[package]] | 43 | [[package]] |
44 | name = "arrayvec" | 44 | name = "arrayvec" |
45 | version = "0.5.1" | 45 | version = "0.5.2" |
46 | source = "registry+https://github.com/rust-lang/crates.io-index" | 46 | source = "registry+https://github.com/rust-lang/crates.io-index" |
47 | checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" | 47 | checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" |
48 | 48 | ||
49 | [[package]] | 49 | [[package]] |
50 | name = "assists" | 50 | name = "assists" |
51 | version = "0.0.0" | 51 | version = "0.0.0" |
52 | dependencies = [ | 52 | dependencies = [ |
53 | "base_db", | ||
54 | "either", | 53 | "either", |
55 | "hir", | 54 | "hir", |
56 | "ide_db", | 55 | "ide_db", |
@@ -129,11 +128,11 @@ checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" | |||
129 | 128 | ||
130 | [[package]] | 129 | [[package]] |
131 | name = "cargo_metadata" | 130 | name = "cargo_metadata" |
132 | version = "0.11.4" | 131 | version = "0.12.0" |
133 | source = "registry+https://github.com/rust-lang/crates.io-index" | 132 | source = "registry+https://github.com/rust-lang/crates.io-index" |
134 | checksum = "a3a567c24b86754d629addc2db89e340ac9398d07b5875efcff837e3878e17ec" | 133 | checksum = "d5a5f7b42f606b7f23674f6f4d877628350682bc40687d3fae65679a58d55345" |
135 | dependencies = [ | 134 | dependencies = [ |
136 | "semver", | 135 | "semver 0.11.0", |
137 | "serde", | 136 | "serde", |
138 | "serde_json", | 137 | "serde_json", |
139 | ] | 138 | ] |
@@ -148,6 +147,7 @@ checksum = "ed67cbde08356238e75fc4656be4749481eeffb09e19f320a25237d5221c985d" | |||
148 | name = "cfg" | 147 | name = "cfg" |
149 | version = "0.0.0" | 148 | version = "0.0.0" |
150 | dependencies = [ | 149 | dependencies = [ |
150 | "expect-test", | ||
151 | "mbe", | 151 | "mbe", |
152 | "rustc-hash", | 152 | "rustc-hash", |
153 | "syntax", | 153 | "syntax", |
@@ -168,9 +168,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" | |||
168 | 168 | ||
169 | [[package]] | 169 | [[package]] |
170 | name = "chalk-derive" | 170 | name = "chalk-derive" |
171 | version = "0.33.0" | 171 | version = "0.34.0" |
172 | source = "registry+https://github.com/rust-lang/crates.io-index" | 172 | source = "registry+https://github.com/rust-lang/crates.io-index" |
173 | checksum = "569014cab9084a6b826fe2507cc6d08f7897ba144fb1bc74e71b593dc8a0b952" | 173 | checksum = "0e9f986750ecb4df889d0a95d4586bd921889497b33908cc75bb80eadb4c600a" |
174 | dependencies = [ | 174 | dependencies = [ |
175 | "proc-macro2", | 175 | "proc-macro2", |
176 | "quote", | 176 | "quote", |
@@ -180,9 +180,9 @@ dependencies = [ | |||
180 | 180 | ||
181 | [[package]] | 181 | [[package]] |
182 | name = "chalk-ir" | 182 | name = "chalk-ir" |
183 | version = "0.33.0" | 183 | version = "0.34.0" |
184 | source = "registry+https://github.com/rust-lang/crates.io-index" | 184 | source = "registry+https://github.com/rust-lang/crates.io-index" |
185 | checksum = "8d9eab2a6590b696419f89c9ca3616fe8e8266ef676e6a6da8818c94963c9541" | 185 | checksum = "5c352c4649f1408bb3de5d86a248fda78d3d9cd1cbbd9502e7eca1be1e7ac368" |
186 | dependencies = [ | 186 | dependencies = [ |
187 | "chalk-derive", | 187 | "chalk-derive", |
188 | "lazy_static", | 188 | "lazy_static", |
@@ -190,9 +190,9 @@ dependencies = [ | |||
190 | 190 | ||
191 | [[package]] | 191 | [[package]] |
192 | name = "chalk-recursive" | 192 | name = "chalk-recursive" |
193 | version = "0.33.0" | 193 | version = "0.34.0" |
194 | source = "registry+https://github.com/rust-lang/crates.io-index" | 194 | source = "registry+https://github.com/rust-lang/crates.io-index" |
195 | checksum = "4a4671bcc70aa2d7e12ff4fe03f91d0c3c9ce387de915915e57fdf0c91dc5abd" | 195 | checksum = "7294bb2ac5446fcb83ec9524b9113f59a8913f174a9c1dea6db60532f17a1579" |
196 | dependencies = [ | 196 | dependencies = [ |
197 | "chalk-derive", | 197 | "chalk-derive", |
198 | "chalk-ir", | 198 | "chalk-ir", |
@@ -203,9 +203,9 @@ dependencies = [ | |||
203 | 203 | ||
204 | [[package]] | 204 | [[package]] |
205 | name = "chalk-solve" | 205 | name = "chalk-solve" |
206 | version = "0.33.0" | 206 | version = "0.34.0" |
207 | source = "registry+https://github.com/rust-lang/crates.io-index" | 207 | source = "registry+https://github.com/rust-lang/crates.io-index" |
208 | checksum = "45f75cc603f2fd302576c8b2976437f334e159e26d0afbb108a565b96c52184e" | 208 | checksum = "ffbca06963ed6f3d22faed840847a685f02feefa3825c0b94f9b791d03a0ac6f" |
209 | dependencies = [ | 209 | dependencies = [ |
210 | "chalk-derive", | 210 | "chalk-derive", |
211 | "chalk-ir", | 211 | "chalk-ir", |
@@ -250,6 +250,24 @@ dependencies = [ | |||
250 | ] | 250 | ] |
251 | 251 | ||
252 | [[package]] | 252 | [[package]] |
253 | name = "completion" | ||
254 | version = "0.0.0" | ||
255 | dependencies = [ | ||
256 | "base_db", | ||
257 | "expect-test", | ||
258 | "hir", | ||
259 | "ide_db", | ||
260 | "itertools", | ||
261 | "log", | ||
262 | "profile", | ||
263 | "rustc-hash", | ||
264 | "stdx", | ||
265 | "syntax", | ||
266 | "test_utils", | ||
267 | "text_edit", | ||
268 | ] | ||
269 | |||
270 | [[package]] | ||
253 | name = "const_fn" | 271 | name = "const_fn" |
254 | version = "0.4.2" | 272 | version = "0.4.2" |
255 | source = "registry+https://github.com/rust-lang/crates.io-index" | 273 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -257,11 +275,11 @@ checksum = "ce90df4c658c62f12d78f7508cf92f9173e5184a539c10bfe54a3107b3ffd0f2" | |||
257 | 275 | ||
258 | [[package]] | 276 | [[package]] |
259 | name = "crc32fast" | 277 | name = "crc32fast" |
260 | version = "1.2.0" | 278 | version = "1.2.1" |
261 | source = "registry+https://github.com/rust-lang/crates.io-index" | 279 | source = "registry+https://github.com/rust-lang/crates.io-index" |
262 | checksum = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" | 280 | checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a" |
263 | dependencies = [ | 281 | dependencies = [ |
264 | "cfg-if 0.1.10", | 282 | "cfg-if 1.0.0", |
265 | ] | 283 | ] |
266 | 284 | ||
267 | [[package]] | 285 | [[package]] |
@@ -286,26 +304,25 @@ dependencies = [ | |||
286 | 304 | ||
287 | [[package]] | 305 | [[package]] |
288 | name = "crossbeam-deque" | 306 | name = "crossbeam-deque" |
289 | version = "0.7.3" | 307 | version = "0.8.0" |
290 | source = "registry+https://github.com/rust-lang/crates.io-index" | 308 | source = "registry+https://github.com/rust-lang/crates.io-index" |
291 | checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" | 309 | checksum = "94af6efb46fef72616855b036a624cf27ba656ffc9be1b9a3c931cfc7749a9a9" |
292 | dependencies = [ | 310 | dependencies = [ |
311 | "cfg-if 1.0.0", | ||
293 | "crossbeam-epoch", | 312 | "crossbeam-epoch", |
294 | "crossbeam-utils 0.7.2", | 313 | "crossbeam-utils 0.8.0", |
295 | "maybe-uninit", | ||
296 | ] | 314 | ] |
297 | 315 | ||
298 | [[package]] | 316 | [[package]] |
299 | name = "crossbeam-epoch" | 317 | name = "crossbeam-epoch" |
300 | version = "0.8.2" | 318 | version = "0.9.0" |
301 | source = "registry+https://github.com/rust-lang/crates.io-index" | 319 | source = "registry+https://github.com/rust-lang/crates.io-index" |
302 | checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" | 320 | checksum = "ec0f606a85340376eef0d6d8fec399e6d4a544d648386c6645eb6d0653b27d9f" |
303 | dependencies = [ | 321 | dependencies = [ |
304 | "autocfg", | 322 | "cfg-if 1.0.0", |
305 | "cfg-if 0.1.10", | 323 | "const_fn", |
306 | "crossbeam-utils 0.7.2", | 324 | "crossbeam-utils 0.8.0", |
307 | "lazy_static", | 325 | "lazy_static", |
308 | "maybe-uninit", | ||
309 | "memoffset", | 326 | "memoffset", |
310 | "scopeguard", | 327 | "scopeguard", |
311 | ] | 328 | ] |
@@ -362,9 +379,9 @@ dependencies = [ | |||
362 | 379 | ||
363 | [[package]] | 380 | [[package]] |
364 | name = "env_logger" | 381 | name = "env_logger" |
365 | version = "0.7.1" | 382 | version = "0.8.1" |
366 | source = "registry+https://github.com/rust-lang/crates.io-index" | 383 | source = "registry+https://github.com/rust-lang/crates.io-index" |
367 | checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" | 384 | checksum = "54532e3223c5af90a6a757c90b5c5521564b07e5e7a958681bcd2afad421cdcd" |
368 | dependencies = [ | 385 | dependencies = [ |
369 | "log", | 386 | "log", |
370 | ] | 387 | ] |
@@ -422,12 +439,6 @@ dependencies = [ | |||
422 | ] | 439 | ] |
423 | 440 | ||
424 | [[package]] | 441 | [[package]] |
425 | name = "fs-err" | ||
426 | version = "2.5.0" | ||
427 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
428 | checksum = "bcd1163ae48bda72a20ae26d66a04d3094135cadab911cff418ae5e33f253431" | ||
429 | |||
430 | [[package]] | ||
431 | name = "fsevent" | 442 | name = "fsevent" |
432 | version = "2.0.2" | 443 | version = "2.0.2" |
433 | source = "registry+https://github.com/rust-lang/crates.io-index" | 444 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -469,6 +480,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
469 | checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" | 480 | checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" |
470 | 481 | ||
471 | [[package]] | 482 | [[package]] |
483 | name = "generator" | ||
484 | version = "0.6.23" | ||
485 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
486 | checksum = "8cdc09201b2e8ca1b19290cf7e65de2246b8e91fb6874279722189c4de7b94dc" | ||
487 | dependencies = [ | ||
488 | "cc", | ||
489 | "libc", | ||
490 | "log", | ||
491 | "rustc_version", | ||
492 | "winapi 0.3.9", | ||
493 | ] | ||
494 | |||
495 | [[package]] | ||
472 | name = "gimli" | 496 | name = "gimli" |
473 | version = "0.22.0" | 497 | version = "0.22.0" |
474 | source = "registry+https://github.com/rust-lang/crates.io-index" | 498 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -614,8 +638,8 @@ name = "ide" | |||
614 | version = "0.0.0" | 638 | version = "0.0.0" |
615 | dependencies = [ | 639 | dependencies = [ |
616 | "assists", | 640 | "assists", |
617 | "base_db", | ||
618 | "cfg", | 641 | "cfg", |
642 | "completion", | ||
619 | "either", | 643 | "either", |
620 | "expect-test", | 644 | "expect-test", |
621 | "hir", | 645 | "hir", |
@@ -642,6 +666,7 @@ version = "0.0.0" | |||
642 | dependencies = [ | 666 | dependencies = [ |
643 | "base_db", | 667 | "base_db", |
644 | "either", | 668 | "either", |
669 | "expect-test", | ||
645 | "fst", | 670 | "fst", |
646 | "hir", | 671 | "hir", |
647 | "log", | 672 | "log", |
@@ -765,11 +790,11 @@ checksum = "2448f6066e80e3bfc792e9c98bf705b4b0fc6e8ef5b43e5889aff0eaa9c58743" | |||
765 | 790 | ||
766 | [[package]] | 791 | [[package]] |
767 | name = "libloading" | 792 | name = "libloading" |
768 | version = "0.6.4" | 793 | version = "0.6.5" |
769 | source = "registry+https://github.com/rust-lang/crates.io-index" | 794 | source = "registry+https://github.com/rust-lang/crates.io-index" |
770 | checksum = "3557c9384f7f757f6d139cd3a4c62ef4e850696c16bf27924a5538c8a09717a1" | 795 | checksum = "1090080fe06ec2648d0da3881d9453d97e71a45f00eb179af7fdd7e3f686fdb0" |
771 | dependencies = [ | 796 | dependencies = [ |
772 | "cfg-if 0.1.10", | 797 | "cfg-if 1.0.0", |
773 | "winapi 0.3.9", | 798 | "winapi 0.3.9", |
774 | ] | 799 | ] |
775 | 800 | ||
@@ -801,10 +826,23 @@ dependencies = [ | |||
801 | ] | 826 | ] |
802 | 827 | ||
803 | [[package]] | 828 | [[package]] |
829 | name = "loom" | ||
830 | version = "0.3.6" | ||
831 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
832 | checksum = "a0e8460f2f2121162705187214720353c517b97bdfb3494c0b1e33d83ebe4bed" | ||
833 | dependencies = [ | ||
834 | "cfg-if 0.1.10", | ||
835 | "generator", | ||
836 | "scoped-tls", | ||
837 | "serde", | ||
838 | "serde_json", | ||
839 | ] | ||
840 | |||
841 | [[package]] | ||
804 | name = "lsp-server" | 842 | name = "lsp-server" |
805 | version = "0.4.0" | 843 | version = "0.4.1" |
806 | source = "registry+https://github.com/rust-lang/crates.io-index" | 844 | source = "registry+https://github.com/rust-lang/crates.io-index" |
807 | checksum = "ff7452ee21b8de64f10ceb4e9fee1212e1a9579cd717226613333e751676c86a" | 845 | checksum = "9c85acaf36c53bf15da2b8b35afeea56747707261f59eb0b77229081dd72b04e" |
808 | dependencies = [ | 846 | dependencies = [ |
809 | "crossbeam-channel 0.5.0", | 847 | "crossbeam-channel 0.5.0", |
810 | "log", | 848 | "log", |
@@ -814,9 +852,9 @@ dependencies = [ | |||
814 | 852 | ||
815 | [[package]] | 853 | [[package]] |
816 | name = "lsp-types" | 854 | name = "lsp-types" |
817 | version = "0.82.0" | 855 | version = "0.83.0" |
818 | source = "registry+https://github.com/rust-lang/crates.io-index" | 856 | source = "registry+https://github.com/rust-lang/crates.io-index" |
819 | checksum = "db895abb8527cf59e3de893ab2acf52cf904faeb65e60ea6f373e11fe86464e8" | 857 | checksum = "25e0bd4b95038f2c23bda332ba0ca684e8dda765db1f9bdb63dc4c3e01f3b456" |
820 | dependencies = [ | 858 | dependencies = [ |
821 | "base64", | 859 | "base64", |
822 | "bitflags", | 860 | "bitflags", |
@@ -1088,6 +1126,15 @@ dependencies = [ | |||
1088 | ] | 1126 | ] |
1089 | 1127 | ||
1090 | [[package]] | 1128 | [[package]] |
1129 | name = "pest" | ||
1130 | version = "2.1.3" | ||
1131 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
1132 | checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" | ||
1133 | dependencies = [ | ||
1134 | "ucd-trie", | ||
1135 | ] | ||
1136 | |||
1137 | [[package]] | ||
1091 | name = "petgraph" | 1138 | name = "petgraph" |
1092 | version = "0.5.1" | 1139 | version = "0.5.1" |
1093 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1140 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1105,9 +1152,9 @@ checksum = "28b9b4df73455c861d7cbf8be42f01d3b373ed7f02e378d55fa84eafc6f638b1" | |||
1105 | 1152 | ||
1106 | [[package]] | 1153 | [[package]] |
1107 | name = "pin-project-lite" | 1154 | name = "pin-project-lite" |
1108 | version = "0.1.10" | 1155 | version = "0.1.11" |
1109 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1156 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1110 | checksum = "e555d9e657502182ac97b539fb3dae8b79cda19e3e4f8ffb5e8de4f18df93c95" | 1157 | checksum = "c917123afa01924fc84bb20c4c03f004d9c38e5127e3c039bbf7f4b9c76a2f6b" |
1111 | 1158 | ||
1112 | [[package]] | 1159 | [[package]] |
1113 | name = "plain" | 1160 | name = "plain" |
@@ -1220,9 +1267,9 @@ dependencies = [ | |||
1220 | 1267 | ||
1221 | [[package]] | 1268 | [[package]] |
1222 | name = "rayon" | 1269 | name = "rayon" |
1223 | version = "1.4.1" | 1270 | version = "1.5.0" |
1224 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1271 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1225 | checksum = "dcf6960dc9a5b4ee8d3e4c5787b4a112a8818e0290a42ff664ad60692fdf2032" | 1272 | checksum = "8b0d8e0819fadc20c74ea8373106ead0600e3a67ef1fe8da56e39b9ae7275674" |
1226 | dependencies = [ | 1273 | dependencies = [ |
1227 | "autocfg", | 1274 | "autocfg", |
1228 | "crossbeam-deque", | 1275 | "crossbeam-deque", |
@@ -1232,13 +1279,13 @@ dependencies = [ | |||
1232 | 1279 | ||
1233 | [[package]] | 1280 | [[package]] |
1234 | name = "rayon-core" | 1281 | name = "rayon-core" |
1235 | version = "1.8.1" | 1282 | version = "1.9.0" |
1236 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1283 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1237 | checksum = "e8c4fec834fb6e6d2dd5eece3c7b432a52f0ba887cf40e595190c4107edc08bf" | 1284 | checksum = "9ab346ac5921dc62ffa9f89b7a773907511cdfa5490c572ae9be1be33e8afa4a" |
1238 | dependencies = [ | 1285 | dependencies = [ |
1239 | "crossbeam-channel 0.4.4", | 1286 | "crossbeam-channel 0.5.0", |
1240 | "crossbeam-deque", | 1287 | "crossbeam-deque", |
1241 | "crossbeam-utils 0.7.2", | 1288 | "crossbeam-utils 0.8.0", |
1242 | "lazy_static", | 1289 | "lazy_static", |
1243 | "num_cpus", | 1290 | "num_cpus", |
1244 | ] | 1291 | ] |
@@ -1291,7 +1338,6 @@ name = "rust-analyzer" | |||
1291 | version = "0.0.0" | 1338 | version = "0.0.0" |
1292 | dependencies = [ | 1339 | dependencies = [ |
1293 | "anyhow", | 1340 | "anyhow", |
1294 | "base_db", | ||
1295 | "cfg", | 1341 | "cfg", |
1296 | "crossbeam-channel 0.5.0", | 1342 | "crossbeam-channel 0.5.0", |
1297 | "env_logger", | 1343 | "env_logger", |
@@ -1326,6 +1372,9 @@ dependencies = [ | |||
1326 | "text_edit", | 1372 | "text_edit", |
1327 | "threadpool", | 1373 | "threadpool", |
1328 | "toolchain", | 1374 | "toolchain", |
1375 | "tracing", | ||
1376 | "tracing-subscriber", | ||
1377 | "tracing-tree", | ||
1329 | "tt", | 1378 | "tt", |
1330 | "vfs", | 1379 | "vfs", |
1331 | "vfs-notify", | 1380 | "vfs-notify", |
@@ -1334,18 +1383,18 @@ dependencies = [ | |||
1334 | 1383 | ||
1335 | [[package]] | 1384 | [[package]] |
1336 | name = "rustc-ap-rustc_lexer" | 1385 | name = "rustc-ap-rustc_lexer" |
1337 | version = "683.0.0" | 1386 | version = "685.0.0" |
1338 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1387 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1339 | checksum = "c0c9a47e24d4b7d74ec583d8813803b36985ee082fe7debe55f257df92d5fe50" | 1388 | checksum = "4d6465438127d20bf9d0f5148f806c029934a74c9bce1103a42d47e81d3fe89a" |
1340 | dependencies = [ | 1389 | dependencies = [ |
1341 | "unicode-xid", | 1390 | "unicode-xid", |
1342 | ] | 1391 | ] |
1343 | 1392 | ||
1344 | [[package]] | 1393 | [[package]] |
1345 | name = "rustc-demangle" | 1394 | name = "rustc-demangle" |
1346 | version = "0.1.17" | 1395 | version = "0.1.18" |
1347 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1396 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1348 | checksum = "b2610b7f643d18c87dff3b489950269617e6601a51f1f05aa5daefee36f64f0b" | 1397 | checksum = "6e3bad0ee36814ca07d7968269dd4b7ec89ec2da10c4bb613928d3077083c232" |
1349 | 1398 | ||
1350 | [[package]] | 1399 | [[package]] |
1351 | name = "rustc-hash" | 1400 | name = "rustc-hash" |
@@ -1354,6 +1403,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
1354 | checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" | 1403 | checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" |
1355 | 1404 | ||
1356 | [[package]] | 1405 | [[package]] |
1406 | name = "rustc_version" | ||
1407 | version = "0.2.3" | ||
1408 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
1409 | checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" | ||
1410 | dependencies = [ | ||
1411 | "semver 0.9.0", | ||
1412 | ] | ||
1413 | |||
1414 | [[package]] | ||
1357 | name = "ryu" | 1415 | name = "ryu" |
1358 | version = "1.0.5" | 1416 | version = "1.0.5" |
1359 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1417 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1420,9 +1478,9 @@ dependencies = [ | |||
1420 | 1478 | ||
1421 | [[package]] | 1479 | [[package]] |
1422 | name = "scroll_derive" | 1480 | name = "scroll_derive" |
1423 | version = "0.10.3" | 1481 | version = "0.10.4" |
1424 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1482 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1425 | checksum = "6dfde5d1531034db129e95c76ac857e2baecea3443579d493d02224950b0fb6d" | 1483 | checksum = "b12bd20b94c7cdfda8c7ba9b92ad0d9a56e3fa018c25fca83b51aa664c9b4c0d" |
1426 | dependencies = [ | 1484 | dependencies = [ |
1427 | "proc-macro2", | 1485 | "proc-macro2", |
1428 | "quote", | 1486 | "quote", |
@@ -1431,11 +1489,20 @@ dependencies = [ | |||
1431 | 1489 | ||
1432 | [[package]] | 1490 | [[package]] |
1433 | name = "semver" | 1491 | name = "semver" |
1434 | version = "0.10.0" | 1492 | version = "0.9.0" |
1493 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
1494 | checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" | ||
1495 | dependencies = [ | ||
1496 | "semver-parser 0.7.0", | ||
1497 | ] | ||
1498 | |||
1499 | [[package]] | ||
1500 | name = "semver" | ||
1501 | version = "0.11.0" | ||
1435 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1502 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1436 | checksum = "394cec28fa623e00903caf7ba4fa6fb9a0e260280bb8cdbbba029611108a0190" | 1503 | checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" |
1437 | dependencies = [ | 1504 | dependencies = [ |
1438 | "semver-parser", | 1505 | "semver-parser 0.10.1", |
1439 | "serde", | 1506 | "serde", |
1440 | ] | 1507 | ] |
1441 | 1508 | ||
@@ -1446,19 +1513,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
1446 | checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" | 1513 | checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" |
1447 | 1514 | ||
1448 | [[package]] | 1515 | [[package]] |
1516 | name = "semver-parser" | ||
1517 | version = "0.10.1" | ||
1518 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
1519 | checksum = "42ef146c2ad5e5f4b037cd6ce2ebb775401729b19a82040c1beac9d36c7d1428" | ||
1520 | dependencies = [ | ||
1521 | "pest", | ||
1522 | ] | ||
1523 | |||
1524 | [[package]] | ||
1449 | name = "serde" | 1525 | name = "serde" |
1450 | version = "1.0.116" | 1526 | version = "1.0.117" |
1451 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1527 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1452 | checksum = "96fe57af81d28386a513cbc6858332abc6117cfdb5999647c6444b8f43a370a5" | 1528 | checksum = "b88fa983de7720629c9387e9f517353ed404164b1e482c970a90c1a4aaf7dc1a" |
1453 | dependencies = [ | 1529 | dependencies = [ |
1454 | "serde_derive", | 1530 | "serde_derive", |
1455 | ] | 1531 | ] |
1456 | 1532 | ||
1457 | [[package]] | 1533 | [[package]] |
1458 | name = "serde_derive" | 1534 | name = "serde_derive" |
1459 | version = "1.0.116" | 1535 | version = "1.0.117" |
1460 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1536 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1461 | checksum = "f630a6370fd8e457873b4bd2ffdae75408bc291ba72be773772a4c2a065d9ae8" | 1537 | checksum = "cbd1ae72adb44aab48f325a02444a5fc079349a8d804c1fc922aed3f7454c74e" |
1462 | dependencies = [ | 1538 | dependencies = [ |
1463 | "proc-macro2", | 1539 | "proc-macro2", |
1464 | "quote", | 1540 | "quote", |
@@ -1489,11 +1565,12 @@ dependencies = [ | |||
1489 | 1565 | ||
1490 | [[package]] | 1566 | [[package]] |
1491 | name = "sharded-slab" | 1567 | name = "sharded-slab" |
1492 | version = "0.0.9" | 1568 | version = "0.1.0" |
1493 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1569 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1494 | checksum = "06d5a3f5166fb5b42a5439f2eee8b9de149e235961e3eb21c5808fc3ea17ff3e" | 1570 | checksum = "7b4921be914e16899a80adefb821f8ddb7974e3f1250223575a44ed994882127" |
1495 | dependencies = [ | 1571 | dependencies = [ |
1496 | "lazy_static", | 1572 | "lazy_static", |
1573 | "loom", | ||
1497 | ] | 1574 | ] |
1498 | 1575 | ||
1499 | [[package]] | 1576 | [[package]] |
@@ -1521,7 +1598,6 @@ dependencies = [ | |||
1521 | name = "ssr" | 1598 | name = "ssr" |
1522 | version = "0.0.0" | 1599 | version = "0.0.0" |
1523 | dependencies = [ | 1600 | dependencies = [ |
1524 | "base_db", | ||
1525 | "expect-test", | 1601 | "expect-test", |
1526 | "hir", | 1602 | "hir", |
1527 | "ide_db", | 1603 | "ide_db", |
@@ -1538,9 +1614,9 @@ version = "0.0.0" | |||
1538 | 1614 | ||
1539 | [[package]] | 1615 | [[package]] |
1540 | name = "syn" | 1616 | name = "syn" |
1541 | version = "1.0.44" | 1617 | version = "1.0.46" |
1542 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1618 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1543 | checksum = "e03e57e4fcbfe7749842d53e24ccb9aa12b7252dbe5e91d2acad31834c8b8fdd" | 1619 | checksum = "5ad5de3220ea04da322618ded2c42233d02baca219d6f160a3e9c87cda16c942" |
1544 | dependencies = [ | 1620 | dependencies = [ |
1545 | "proc-macro2", | 1621 | "proc-macro2", |
1546 | "quote", | 1622 | "quote", |
@@ -1565,6 +1641,7 @@ version = "0.0.0" | |||
1565 | dependencies = [ | 1641 | dependencies = [ |
1566 | "arrayvec", | 1642 | "arrayvec", |
1567 | "expect-test", | 1643 | "expect-test", |
1644 | "indexmap", | ||
1568 | "itertools", | 1645 | "itertools", |
1569 | "once_cell", | 1646 | "once_cell", |
1570 | "parser", | 1647 | "parser", |
@@ -1716,9 +1793,9 @@ dependencies = [ | |||
1716 | 1793 | ||
1717 | [[package]] | 1794 | [[package]] |
1718 | name = "tracing-subscriber" | 1795 | name = "tracing-subscriber" |
1719 | version = "0.2.13" | 1796 | version = "0.2.14" |
1720 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1797 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1721 | checksum = "4ef0a5e15477aa303afbfac3a44cba9b6430fdaad52423b1e6c0dbbe28c3eedd" | 1798 | checksum = "2810660b9d5b18895d140caba6401765749a6a162e5d0736cfc44ea50db9d79d" |
1722 | dependencies = [ | 1799 | dependencies = [ |
1723 | "ansi_term", | 1800 | "ansi_term", |
1724 | "chrono", | 1801 | "chrono", |
@@ -1759,6 +1836,12 @@ dependencies = [ | |||
1759 | ] | 1836 | ] |
1760 | 1837 | ||
1761 | [[package]] | 1838 | [[package]] |
1839 | name = "ucd-trie" | ||
1840 | version = "0.1.3" | ||
1841 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
1842 | checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" | ||
1843 | |||
1844 | [[package]] | ||
1762 | name = "ungrammar" | 1845 | name = "ungrammar" |
1763 | version = "1.1.4" | 1846 | version = "1.1.4" |
1764 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1847 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1921,16 +2004,31 @@ dependencies = [ | |||
1921 | ] | 2004 | ] |
1922 | 2005 | ||
1923 | [[package]] | 2006 | [[package]] |
2007 | name = "xshell" | ||
2008 | version = "0.1.6" | ||
2009 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
2010 | checksum = "3e9bbfccbb2233e6b0473b7870d4b0811a402e9e249a5e8394e768e5a5c9c37d" | ||
2011 | dependencies = [ | ||
2012 | "xshell-macros", | ||
2013 | ] | ||
2014 | |||
2015 | [[package]] | ||
2016 | name = "xshell-macros" | ||
2017 | version = "0.1.6" | ||
2018 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
2019 | checksum = "b94f1c632d730a1704b21dc551a4c74fbed713cfa59593708f94943548206134" | ||
2020 | |||
2021 | [[package]] | ||
1924 | name = "xtask" | 2022 | name = "xtask" |
1925 | version = "0.1.0" | 2023 | version = "0.1.0" |
1926 | dependencies = [ | 2024 | dependencies = [ |
1927 | "anyhow", | 2025 | "anyhow", |
1928 | "flate2", | 2026 | "flate2", |
1929 | "fs-err", | ||
1930 | "pico-args", | 2027 | "pico-args", |
1931 | "proc-macro2", | 2028 | "proc-macro2", |
1932 | "quote", | 2029 | "quote", |
1933 | "ungrammar", | 2030 | "ungrammar", |
1934 | "walkdir", | 2031 | "walkdir", |
1935 | "write-json", | 2032 | "write-json", |
2033 | "xshell", | ||
1936 | ] | 2034 | ] |
diff --git a/crates/assists/Cargo.toml b/crates/assists/Cargo.toml index 264125651..108f656e9 100644 --- a/crates/assists/Cargo.toml +++ b/crates/assists/Cargo.toml | |||
@@ -18,7 +18,6 @@ stdx = { path = "../stdx", version = "0.0.0" } | |||
18 | syntax = { path = "../syntax", version = "0.0.0" } | 18 | syntax = { path = "../syntax", version = "0.0.0" } |
19 | text_edit = { path = "../text_edit", version = "0.0.0" } | 19 | text_edit = { path = "../text_edit", version = "0.0.0" } |
20 | profile = { path = "../profile", version = "0.0.0" } | 20 | profile = { path = "../profile", version = "0.0.0" } |
21 | base_db = { path = "../base_db", version = "0.0.0" } | ||
22 | ide_db = { path = "../ide_db", version = "0.0.0" } | 21 | ide_db = { path = "../ide_db", version = "0.0.0" } |
23 | hir = { path = "../hir", version = "0.0.0" } | 22 | hir = { path = "../hir", version = "0.0.0" } |
24 | test_utils = { path = "../test_utils", version = "0.0.0" } | 23 | test_utils = { path = "../test_utils", version = "0.0.0" } |
diff --git a/crates/assists/src/assist_context.rs b/crates/assists/src/assist_context.rs index bf520069e..d11fee196 100644 --- a/crates/assists/src/assist_context.rs +++ b/crates/assists/src/assist_context.rs | |||
@@ -3,8 +3,8 @@ | |||
3 | use std::mem; | 3 | use std::mem; |
4 | 4 | ||
5 | use algo::find_covering_element; | 5 | use algo::find_covering_element; |
6 | use base_db::{FileId, FileRange}; | ||
7 | use hir::Semantics; | 6 | use hir::Semantics; |
7 | use ide_db::base_db::{FileId, FileRange}; | ||
8 | use ide_db::{ | 8 | use ide_db::{ |
9 | label::Label, | 9 | label::Label, |
10 | source_change::{SourceChange, SourceFileEdit}, | 10 | source_change::{SourceChange, SourceFileEdit}, |
diff --git a/crates/assists/src/handlers/add_missing_impl_members.rs b/crates/assists/src/handlers/add_missing_impl_members.rs index 4c400f287..b82fb30ad 100644 --- a/crates/assists/src/handlers/add_missing_impl_members.rs +++ b/crates/assists/src/handlers/add_missing_impl_members.rs | |||
@@ -1,4 +1,5 @@ | |||
1 | use hir::HasSource; | 1 | use hir::HasSource; |
2 | use ide_db::traits::{get_missing_assoc_items, resolve_target_trait}; | ||
2 | use syntax::{ | 3 | use syntax::{ |
3 | ast::{ | 4 | ast::{ |
4 | self, | 5 | self, |
@@ -11,7 +12,7 @@ use syntax::{ | |||
11 | use crate::{ | 12 | use crate::{ |
12 | assist_context::{AssistContext, Assists}, | 13 | assist_context::{AssistContext, Assists}, |
13 | ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams}, | 14 | ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams}, |
14 | utils::{get_missing_assoc_items, render_snippet, resolve_target_trait, Cursor}, | 15 | utils::{render_snippet, Cursor}, |
15 | AssistId, AssistKind, | 16 | AssistId, AssistKind, |
16 | }; | 17 | }; |
17 | 18 | ||
diff --git a/crates/assists/src/handlers/auto_import.rs b/crates/assists/src/handlers/auto_import.rs index 4a7059c83..e49e641b3 100644 --- a/crates/assists/src/handlers/auto_import.rs +++ b/crates/assists/src/handlers/auto_import.rs | |||
@@ -6,7 +6,7 @@ use crate::{ | |||
6 | AssistContext, AssistId, AssistKind, Assists, GroupLabel, | 6 | AssistContext, AssistId, AssistKind, Assists, GroupLabel, |
7 | }; | 7 | }; |
8 | 8 | ||
9 | // Feature: Import Insertion | 9 | // Feature: Auto Import |
10 | // | 10 | // |
11 | // Using the `auto-import` assist it is possible to insert missing imports for unresolved items. | 11 | // Using the `auto-import` assist it is possible to insert missing imports for unresolved items. |
12 | // When inserting an import it will do so in a structured manner by keeping imports grouped, | 12 | // When inserting an import it will do so in a structured manner by keeping imports grouped, |
@@ -100,7 +100,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> | |||
100 | let group = import_group_message(import_assets.import_candidate()); | 100 | let group = import_group_message(import_assets.import_candidate()); |
101 | let scope = ImportScope::find_insert_use_container(import_assets.syntax_under_caret(), ctx)?; | 101 | let scope = ImportScope::find_insert_use_container(import_assets.syntax_under_caret(), ctx)?; |
102 | let syntax = scope.as_syntax_node(); | 102 | let syntax = scope.as_syntax_node(); |
103 | for import in proposed_imports { | 103 | for (import, _) in proposed_imports { |
104 | acc.add_group( | 104 | acc.add_group( |
105 | &group, | 105 | &group, |
106 | AssistId("auto_import", AssistKind::QuickFix), | 106 | AssistId("auto_import", AssistKind::QuickFix), |
diff --git a/crates/assists/src/handlers/change_visibility.rs b/crates/assists/src/handlers/change_visibility.rs index 32dc05378..22d7c95d9 100644 --- a/crates/assists/src/handlers/change_visibility.rs +++ b/crates/assists/src/handlers/change_visibility.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | use syntax::{ | 1 | use syntax::{ |
2 | ast::{self, NameOwner, VisibilityOwner}, | 2 | ast::{self, NameOwner, VisibilityOwner}, |
3 | AstNode, | 3 | AstNode, |
4 | SyntaxKind::{CONST, ENUM, FN, MODULE, STATIC, STRUCT, TRAIT, VISIBILITY}, | 4 | SyntaxKind::{CONST, ENUM, FN, MODULE, STATIC, STRUCT, TRAIT, TYPE_ALIAS, VISIBILITY}, |
5 | T, | 5 | T, |
6 | }; | 6 | }; |
7 | use test_utils::mark; | 7 | use test_utils::mark; |
@@ -30,13 +30,20 @@ fn add_vis(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | |||
30 | let item_keyword = ctx.token_at_offset().find(|leaf| { | 30 | let item_keyword = ctx.token_at_offset().find(|leaf| { |
31 | matches!( | 31 | matches!( |
32 | leaf.kind(), | 32 | leaf.kind(), |
33 | T![const] | T![static] | T![fn] | T![mod] | T![struct] | T![enum] | T![trait] | 33 | T![const] |
34 | | T![static] | ||
35 | | T![fn] | ||
36 | | T![mod] | ||
37 | | T![struct] | ||
38 | | T![enum] | ||
39 | | T![trait] | ||
40 | | T![type] | ||
34 | ) | 41 | ) |
35 | }); | 42 | }); |
36 | 43 | ||
37 | let (offset, target) = if let Some(keyword) = item_keyword { | 44 | let (offset, target) = if let Some(keyword) = item_keyword { |
38 | let parent = keyword.parent(); | 45 | let parent = keyword.parent(); |
39 | let def_kws = vec![CONST, STATIC, FN, MODULE, STRUCT, ENUM, TRAIT]; | 46 | let def_kws = vec![CONST, STATIC, TYPE_ALIAS, FN, MODULE, STRUCT, ENUM, TRAIT]; |
40 | // Parent is not a definition, can't add visibility | 47 | // Parent is not a definition, can't add visibility |
41 | if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) { | 48 | if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) { |
42 | return None; | 49 | return None; |
@@ -160,6 +167,11 @@ mod tests { | |||
160 | } | 167 | } |
161 | 168 | ||
162 | #[test] | 169 | #[test] |
170 | fn change_visibility_type_alias() { | ||
171 | check_assist(change_visibility, "<|>type T = ();", "pub(crate) type T = ();"); | ||
172 | } | ||
173 | |||
174 | #[test] | ||
163 | fn change_visibility_handles_comment_attrs() { | 175 | fn change_visibility_handles_comment_attrs() { |
164 | check_assist( | 176 | check_assist( |
165 | change_visibility, | 177 | change_visibility, |
diff --git a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs index 756aa03a2..178718c5e 100644 --- a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs | |||
@@ -1,5 +1,5 @@ | |||
1 | use base_db::FileId; | ||
2 | use hir::{EnumVariant, Module, ModuleDef, Name}; | 1 | use hir::{EnumVariant, Module, ModuleDef, Name}; |
2 | use ide_db::base_db::FileId; | ||
3 | use ide_db::{defs::Definition, search::Reference, RootDatabase}; | 3 | use ide_db::{defs::Definition, search::Reference, RootDatabase}; |
4 | use itertools::Itertools; | 4 | use itertools::Itertools; |
5 | use rustc_hash::FxHashSet; | 5 | use rustc_hash::FxHashSet; |
diff --git a/crates/assists/src/handlers/fill_match_arms.rs b/crates/assists/src/handlers/fill_match_arms.rs index 676f5ad92..eda45f5b3 100644 --- a/crates/assists/src/handlers/fill_match_arms.rs +++ b/crates/assists/src/handlers/fill_match_arms.rs | |||
@@ -59,7 +59,7 @@ pub(crate) fn fill_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option< | |||
59 | .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat)) | 59 | .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat)) |
60 | .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block())) | 60 | .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block())) |
61 | .collect::<Vec<_>>(); | 61 | .collect::<Vec<_>>(); |
62 | if Some(enum_def) == FamousDefs(&ctx.sema, module.krate()).core_option_Option() { | 62 | if Some(enum_def) == FamousDefs(&ctx.sema, Some(module.krate())).core_option_Option() { |
63 | // Match `Some` variant first. | 63 | // Match `Some` variant first. |
64 | mark::hit!(option_order); | 64 | mark::hit!(option_order); |
65 | variants.reverse() | 65 | variants.reverse() |
diff --git a/crates/assists/src/handlers/fix_visibility.rs b/crates/assists/src/handlers/fix_visibility.rs index d505e9444..c86720787 100644 --- a/crates/assists/src/handlers/fix_visibility.rs +++ b/crates/assists/src/handlers/fix_visibility.rs | |||
@@ -1,9 +1,11 @@ | |||
1 | use base_db::FileId; | ||
2 | use hir::{db::HirDatabase, HasSource, HasVisibility, PathResolution}; | 1 | use hir::{db::HirDatabase, HasSource, HasVisibility, PathResolution}; |
3 | use syntax::{ast, AstNode, TextRange, TextSize}; | 2 | use ide_db::base_db::FileId; |
3 | use syntax::{ | ||
4 | ast::{self, VisibilityOwner}, | ||
5 | AstNode, TextRange, TextSize, | ||
6 | }; | ||
4 | 7 | ||
5 | use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists}; | 8 | use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists}; |
6 | use ast::VisibilityOwner; | ||
7 | 9 | ||
8 | // FIXME: this really should be a fix for diagnostic, rather than an assist. | 10 | // FIXME: this really should be a fix for diagnostic, rather than an assist. |
9 | 11 | ||
diff --git a/crates/assists/src/handlers/generate_from_impl_for_enum.rs b/crates/assists/src/handlers/generate_from_impl_for_enum.rs index 7f04b9572..674e5a175 100644 --- a/crates/assists/src/handlers/generate_from_impl_for_enum.rs +++ b/crates/assists/src/handlers/generate_from_impl_for_enum.rs | |||
@@ -75,7 +75,7 @@ fn existing_from_impl( | |||
75 | let enum_ = variant.parent_enum(sema.db); | 75 | let enum_ = variant.parent_enum(sema.db); |
76 | let krate = enum_.module(sema.db).krate(); | 76 | let krate = enum_.module(sema.db).krate(); |
77 | 77 | ||
78 | let from_trait = FamousDefs(sema, krate).core_convert_From()?; | 78 | let from_trait = FamousDefs(sema, Some(krate)).core_convert_From()?; |
79 | 79 | ||
80 | let enum_type = enum_.ty(sema.db); | 80 | let enum_type = enum_.ty(sema.db); |
81 | 81 | ||
diff --git a/crates/assists/src/handlers/generate_function.rs b/crates/assists/src/handlers/generate_function.rs index d23f4293b..758188a42 100644 --- a/crates/assists/src/handlers/generate_function.rs +++ b/crates/assists/src/handlers/generate_function.rs | |||
@@ -1,5 +1,5 @@ | |||
1 | use base_db::FileId; | ||
2 | use hir::HirDisplay; | 1 | use hir::HirDisplay; |
2 | use ide_db::base_db::FileId; | ||
3 | use rustc_hash::{FxHashMap, FxHashSet}; | 3 | use rustc_hash::{FxHashMap, FxHashSet}; |
4 | use syntax::{ | 4 | use syntax::{ |
5 | ast::{ | 5 | ast::{ |
diff --git a/crates/assists/src/handlers/generate_impl.rs b/crates/assists/src/handlers/generate_impl.rs index 9989109b5..114974465 100644 --- a/crates/assists/src/handlers/generate_impl.rs +++ b/crates/assists/src/handlers/generate_impl.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | use itertools::Itertools; | 1 | use itertools::Itertools; |
2 | use stdx::format_to; | 2 | use stdx::format_to; |
3 | use syntax::ast::{self, AstNode, GenericParamsOwner, NameOwner}; | 3 | use syntax::ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner}; |
4 | 4 | ||
5 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | 5 | use crate::{AssistContext, AssistId, AssistKind, Assists}; |
6 | 6 | ||
@@ -27,6 +27,7 @@ pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<() | |||
27 | let nominal = ctx.find_node_at_offset::<ast::AdtDef>()?; | 27 | let nominal = ctx.find_node_at_offset::<ast::AdtDef>()?; |
28 | let name = nominal.name()?; | 28 | let name = nominal.name()?; |
29 | let target = nominal.syntax().text_range(); | 29 | let target = nominal.syntax().text_range(); |
30 | |||
30 | acc.add( | 31 | acc.add( |
31 | AssistId("generate_impl", AssistKind::Generate), | 32 | AssistId("generate_impl", AssistKind::Generate), |
32 | format!("Generate impl for `{}`", name), | 33 | format!("Generate impl for `{}`", name), |
@@ -35,7 +36,15 @@ pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<() | |||
35 | let type_params = nominal.generic_param_list(); | 36 | let type_params = nominal.generic_param_list(); |
36 | let start_offset = nominal.syntax().text_range().end(); | 37 | let start_offset = nominal.syntax().text_range().end(); |
37 | let mut buf = String::new(); | 38 | let mut buf = String::new(); |
38 | buf.push_str("\n\nimpl"); | 39 | buf.push_str("\n\n"); |
40 | nominal | ||
41 | .attrs() | ||
42 | .filter(|attr| { | ||
43 | attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false) | ||
44 | }) | ||
45 | .for_each(|attr| buf.push_str(format!("{}\n", attr.to_string()).as_str())); | ||
46 | |||
47 | buf.push_str("impl"); | ||
39 | if let Some(type_params) = &type_params { | 48 | if let Some(type_params) = &type_params { |
40 | format_to!(buf, "{}", type_params.syntax()); | 49 | format_to!(buf, "{}", type_params.syntax()); |
41 | } | 50 | } |
@@ -91,6 +100,35 @@ mod tests { | |||
91 | "struct Foo<'a, T: Foo<'a>> {<|>}", | 100 | "struct Foo<'a, T: Foo<'a>> {<|>}", |
92 | "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n $0\n}", | 101 | "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n $0\n}", |
93 | ); | 102 | ); |
103 | check_assist( | ||
104 | generate_impl, | ||
105 | r#" | ||
106 | #[cfg(feature = "foo")] | ||
107 | struct Foo<'a, T: Foo<'a>> {<|>}"#, | ||
108 | r#" | ||
109 | #[cfg(feature = "foo")] | ||
110 | struct Foo<'a, T: Foo<'a>> {} | ||
111 | |||
112 | #[cfg(feature = "foo")] | ||
113 | impl<'a, T: Foo<'a>> Foo<'a, T> { | ||
114 | $0 | ||
115 | }"#, | ||
116 | ); | ||
117 | |||
118 | check_assist( | ||
119 | generate_impl, | ||
120 | r#" | ||
121 | #[cfg(not(feature = "foo"))] | ||
122 | struct Foo<'a, T: Foo<'a>> {<|>}"#, | ||
123 | r#" | ||
124 | #[cfg(not(feature = "foo"))] | ||
125 | struct Foo<'a, T: Foo<'a>> {} | ||
126 | |||
127 | #[cfg(not(feature = "foo"))] | ||
128 | impl<'a, T: Foo<'a>> Foo<'a, T> { | ||
129 | $0 | ||
130 | }"#, | ||
131 | ); | ||
94 | } | 132 | } |
95 | 133 | ||
96 | #[test] | 134 | #[test] |
diff --git a/crates/assists/src/handlers/move_guard.rs b/crates/assists/src/handlers/move_guard.rs index 452115fe6..e1855b63d 100644 --- a/crates/assists/src/handlers/move_guard.rs +++ b/crates/assists/src/handlers/move_guard.rs | |||
@@ -1,5 +1,5 @@ | |||
1 | use syntax::{ | 1 | use syntax::{ |
2 | ast::{edit::AstNodeEdit, make, AstNode, IfExpr, MatchArm}, | 2 | ast::{edit::AstNodeEdit, make, AstNode, BlockExpr, Expr, IfExpr, MatchArm}, |
3 | SyntaxKind::WHITESPACE, | 3 | SyntaxKind::WHITESPACE, |
4 | }; | 4 | }; |
5 | 5 | ||
@@ -92,9 +92,20 @@ pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext) -> | |||
92 | pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | 92 | pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { |
93 | let match_arm: MatchArm = ctx.find_node_at_offset::<MatchArm>()?; | 93 | let match_arm: MatchArm = ctx.find_node_at_offset::<MatchArm>()?; |
94 | let match_pat = match_arm.pat()?; | 94 | let match_pat = match_arm.pat()?; |
95 | |||
96 | let arm_body = match_arm.expr()?; | 95 | let arm_body = match_arm.expr()?; |
97 | let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone())?; | 96 | |
97 | let mut replace_node = None; | ||
98 | let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone()).or_else(|| { | ||
99 | let block_expr = BlockExpr::cast(arm_body.syntax().clone())?; | ||
100 | if let Expr::IfExpr(e) = block_expr.expr()? { | ||
101 | replace_node = Some(block_expr.syntax().clone()); | ||
102 | Some(e) | ||
103 | } else { | ||
104 | None | ||
105 | } | ||
106 | })?; | ||
107 | let replace_node = replace_node.unwrap_or_else(|| if_expr.syntax().clone()); | ||
108 | |||
98 | let cond = if_expr.condition()?; | 109 | let cond = if_expr.condition()?; |
99 | let then_block = if_expr.then_branch()?; | 110 | let then_block = if_expr.then_branch()?; |
100 | 111 | ||
@@ -109,19 +120,23 @@ pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContex | |||
109 | 120 | ||
110 | let buf = format!(" if {}", cond.syntax().text()); | 121 | let buf = format!(" if {}", cond.syntax().text()); |
111 | 122 | ||
112 | let target = if_expr.syntax().text_range(); | ||
113 | acc.add( | 123 | acc.add( |
114 | AssistId("move_arm_cond_to_match_guard", AssistKind::RefactorRewrite), | 124 | AssistId("move_arm_cond_to_match_guard", AssistKind::RefactorRewrite), |
115 | "Move condition to match guard", | 125 | "Move condition to match guard", |
116 | target, | 126 | replace_node.text_range(), |
117 | |edit| { | 127 | |edit| { |
118 | let then_only_expr = then_block.statements().next().is_none(); | 128 | let then_only_expr = then_block.statements().next().is_none(); |
119 | 129 | ||
120 | match &then_block.expr() { | 130 | match &then_block.expr() { |
121 | Some(then_expr) if then_only_expr => { | 131 | Some(then_expr) if then_only_expr => { |
122 | edit.replace(if_expr.syntax().text_range(), then_expr.syntax().text()) | 132 | edit.replace(replace_node.text_range(), then_expr.syntax().text()) |
123 | } | 133 | } |
124 | _ => edit.replace(if_expr.syntax().text_range(), then_block.syntax().text()), | 134 | _ if replace_node != *if_expr.syntax() => { |
135 | // Dedent because if_expr is in a BlockExpr | ||
136 | let replace_with = then_block.dedent(1.into()).syntax().text(); | ||
137 | edit.replace(replace_node.text_range(), replace_with) | ||
138 | } | ||
139 | _ => edit.replace(replace_node.text_range(), then_block.syntax().text()), | ||
125 | } | 140 | } |
126 | 141 | ||
127 | edit.insert(match_pat.syntax().text_range().end(), buf); | 142 | edit.insert(match_pat.syntax().text_range().end(), buf); |
@@ -225,6 +240,33 @@ fn main() { | |||
225 | } | 240 | } |
226 | 241 | ||
227 | #[test] | 242 | #[test] |
243 | fn move_arm_cond_in_block_to_match_guard_works() { | ||
244 | check_assist( | ||
245 | move_arm_cond_to_match_guard, | ||
246 | r#" | ||
247 | fn main() { | ||
248 | match 92 { | ||
249 | x => { | ||
250 | <|>if x > 10 { | ||
251 | false | ||
252 | } | ||
253 | }, | ||
254 | _ => true | ||
255 | } | ||
256 | } | ||
257 | "#, | ||
258 | r#" | ||
259 | fn main() { | ||
260 | match 92 { | ||
261 | x if x > 10 => false, | ||
262 | _ => true | ||
263 | } | ||
264 | } | ||
265 | "#, | ||
266 | ); | ||
267 | } | ||
268 | |||
269 | #[test] | ||
228 | fn move_arm_cond_to_match_guard_if_let_not_works() { | 270 | fn move_arm_cond_to_match_guard_if_let_not_works() { |
229 | check_assist_not_applicable( | 271 | check_assist_not_applicable( |
230 | move_arm_cond_to_match_guard, | 272 | move_arm_cond_to_match_guard, |
@@ -290,4 +332,35 @@ fn main() { | |||
290 | "#, | 332 | "#, |
291 | ); | 333 | ); |
292 | } | 334 | } |
335 | |||
336 | #[test] | ||
337 | fn move_arm_cond_in_block_to_match_guard_if_multiline_body_works() { | ||
338 | check_assist( | ||
339 | move_arm_cond_to_match_guard, | ||
340 | r#" | ||
341 | fn main() { | ||
342 | match 92 { | ||
343 | x => { | ||
344 | if x > 10 { | ||
345 | 92;<|> | ||
346 | false | ||
347 | } | ||
348 | } | ||
349 | _ => true | ||
350 | } | ||
351 | } | ||
352 | "#, | ||
353 | r#" | ||
354 | fn main() { | ||
355 | match 92 { | ||
356 | x if x > 10 => { | ||
357 | 92; | ||
358 | false | ||
359 | } | ||
360 | _ => true | ||
361 | } | ||
362 | } | ||
363 | "#, | ||
364 | ) | ||
365 | } | ||
293 | } | 366 | } |
diff --git a/crates/assists/src/handlers/qualify_path.rs b/crates/assists/src/handlers/qualify_path.rs new file mode 100644 index 000000000..f436bdbbf --- /dev/null +++ b/crates/assists/src/handlers/qualify_path.rs | |||
@@ -0,0 +1,1048 @@ | |||
1 | use std::iter; | ||
2 | |||
3 | use hir::AsName; | ||
4 | use ide_db::RootDatabase; | ||
5 | use syntax::{ | ||
6 | ast, | ||
7 | ast::{make, ArgListOwner}, | ||
8 | AstNode, | ||
9 | }; | ||
10 | use test_utils::mark; | ||
11 | |||
12 | use crate::{ | ||
13 | assist_context::{AssistContext, Assists}, | ||
14 | utils::import_assets::{ImportAssets, ImportCandidate}, | ||
15 | utils::mod_path_to_ast, | ||
16 | AssistId, AssistKind, GroupLabel, | ||
17 | }; | ||
18 | |||
19 | // Assist: qualify_path | ||
20 | // | ||
21 | // If the name is unresolved, provides all possible qualified paths for it. | ||
22 | // | ||
23 | // ``` | ||
24 | // fn main() { | ||
25 | // let map = HashMap<|>::new(); | ||
26 | // } | ||
27 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | ||
28 | // ``` | ||
29 | // -> | ||
30 | // ``` | ||
31 | // fn main() { | ||
32 | // let map = std::collections::HashMap::new(); | ||
33 | // } | ||
34 | // # pub mod std { pub mod collections { pub struct HashMap { } } } | ||
35 | // ``` | ||
36 | pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
37 | let import_assets = | ||
38 | if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() { | ||
39 | ImportAssets::for_regular_path(path_under_caret, &ctx.sema) | ||
40 | } else if let Some(method_under_caret) = | ||
41 | ctx.find_node_at_offset_with_descend::<ast::MethodCallExpr>() | ||
42 | { | ||
43 | ImportAssets::for_method_call(method_under_caret, &ctx.sema) | ||
44 | } else { | ||
45 | None | ||
46 | }?; | ||
47 | let proposed_imports = import_assets.search_for_relative_paths(&ctx.sema); | ||
48 | if proposed_imports.is_empty() { | ||
49 | return None; | ||
50 | } | ||
51 | |||
52 | let candidate = import_assets.import_candidate(); | ||
53 | let range = ctx.sema.original_range(import_assets.syntax_under_caret()).range; | ||
54 | |||
55 | let qualify_candidate = match candidate { | ||
56 | ImportCandidate::QualifierStart(_) => { | ||
57 | mark::hit!(qualify_path_qualifier_start); | ||
58 | let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?; | ||
59 | let segment = path.segment()?; | ||
60 | QualifyCandidate::QualifierStart(segment) | ||
61 | } | ||
62 | ImportCandidate::UnqualifiedName(_) => { | ||
63 | mark::hit!(qualify_path_unqualified_name); | ||
64 | QualifyCandidate::UnqualifiedName | ||
65 | } | ||
66 | ImportCandidate::TraitAssocItem(_) => { | ||
67 | mark::hit!(qualify_path_trait_assoc_item); | ||
68 | let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?; | ||
69 | let (qualifier, segment) = (path.qualifier()?, path.segment()?); | ||
70 | QualifyCandidate::TraitAssocItem(qualifier, segment) | ||
71 | } | ||
72 | ImportCandidate::TraitMethod(_) => { | ||
73 | mark::hit!(qualify_path_trait_method); | ||
74 | let mcall_expr = ast::MethodCallExpr::cast(import_assets.syntax_under_caret().clone())?; | ||
75 | QualifyCandidate::TraitMethod(ctx.sema.db, mcall_expr) | ||
76 | } | ||
77 | }; | ||
78 | |||
79 | let group_label = group_label(candidate); | ||
80 | for (import, item) in proposed_imports { | ||
81 | acc.add_group( | ||
82 | &group_label, | ||
83 | AssistId("qualify_path", AssistKind::QuickFix), | ||
84 | label(candidate, &import), | ||
85 | range, | ||
86 | |builder| { | ||
87 | qualify_candidate.qualify( | ||
88 | |replace_with: String| builder.replace(range, replace_with), | ||
89 | import, | ||
90 | item, | ||
91 | ) | ||
92 | }, | ||
93 | ); | ||
94 | } | ||
95 | Some(()) | ||
96 | } | ||
97 | |||
98 | enum QualifyCandidate<'db> { | ||
99 | QualifierStart(ast::PathSegment), | ||
100 | UnqualifiedName, | ||
101 | TraitAssocItem(ast::Path, ast::PathSegment), | ||
102 | TraitMethod(&'db RootDatabase, ast::MethodCallExpr), | ||
103 | } | ||
104 | |||
105 | impl QualifyCandidate<'_> { | ||
106 | fn qualify(&self, mut replacer: impl FnMut(String), import: hir::ModPath, item: hir::ItemInNs) { | ||
107 | match self { | ||
108 | QualifyCandidate::QualifierStart(segment) => { | ||
109 | let import = mod_path_to_ast(&import); | ||
110 | replacer(format!("{}::{}", import, segment)); | ||
111 | } | ||
112 | QualifyCandidate::UnqualifiedName => replacer(mod_path_to_ast(&import).to_string()), | ||
113 | QualifyCandidate::TraitAssocItem(qualifier, segment) => { | ||
114 | let import = mod_path_to_ast(&import); | ||
115 | replacer(format!("<{} as {}>::{}", qualifier, import, segment)); | ||
116 | } | ||
117 | &QualifyCandidate::TraitMethod(db, ref mcall_expr) => { | ||
118 | Self::qualify_trait_method(db, mcall_expr, replacer, import, item); | ||
119 | } | ||
120 | } | ||
121 | } | ||
122 | |||
123 | fn qualify_trait_method( | ||
124 | db: &RootDatabase, | ||
125 | mcall_expr: &ast::MethodCallExpr, | ||
126 | mut replacer: impl FnMut(String), | ||
127 | import: hir::ModPath, | ||
128 | item: hir::ItemInNs, | ||
129 | ) -> Option<()> { | ||
130 | let receiver = mcall_expr.receiver()?; | ||
131 | let trait_method_name = mcall_expr.name_ref()?; | ||
132 | let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args()); | ||
133 | let trait_ = item_as_trait(item)?; | ||
134 | let method = find_trait_method(db, trait_, &trait_method_name)?; | ||
135 | if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) { | ||
136 | let import = mod_path_to_ast(&import); | ||
137 | let receiver = match self_access { | ||
138 | hir::Access::Shared => make::expr_ref(receiver, false), | ||
139 | hir::Access::Exclusive => make::expr_ref(receiver, true), | ||
140 | hir::Access::Owned => receiver, | ||
141 | }; | ||
142 | replacer(format!( | ||
143 | "{}::{}{}", | ||
144 | import, | ||
145 | trait_method_name, | ||
146 | match arg_list.clone() { | ||
147 | Some(args) => make::arg_list(iter::once(receiver).chain(args)), | ||
148 | None => make::arg_list(iter::once(receiver)), | ||
149 | } | ||
150 | )); | ||
151 | } | ||
152 | Some(()) | ||
153 | } | ||
154 | } | ||
155 | |||
156 | fn find_trait_method( | ||
157 | db: &RootDatabase, | ||
158 | trait_: hir::Trait, | ||
159 | trait_method_name: &ast::NameRef, | ||
160 | ) -> Option<hir::Function> { | ||
161 | if let Some(hir::AssocItem::Function(method)) = | ||
162 | trait_.items(db).into_iter().find(|item: &hir::AssocItem| { | ||
163 | item.name(db).map(|name| name == trait_method_name.as_name()).unwrap_or(false) | ||
164 | }) | ||
165 | { | ||
166 | Some(method) | ||
167 | } else { | ||
168 | None | ||
169 | } | ||
170 | } | ||
171 | |||
172 | fn item_as_trait(item: hir::ItemInNs) -> Option<hir::Trait> { | ||
173 | if let hir::ModuleDef::Trait(trait_) = hir::ModuleDef::from(item.as_module_def_id()?) { | ||
174 | Some(trait_) | ||
175 | } else { | ||
176 | None | ||
177 | } | ||
178 | } | ||
179 | |||
180 | fn group_label(candidate: &ImportCandidate) -> GroupLabel { | ||
181 | let name = match candidate { | ||
182 | ImportCandidate::UnqualifiedName(it) | ImportCandidate::QualifierStart(it) => &it.name, | ||
183 | ImportCandidate::TraitAssocItem(it) | ImportCandidate::TraitMethod(it) => &it.name, | ||
184 | }; | ||
185 | GroupLabel(format!("Qualify {}", name)) | ||
186 | } | ||
187 | |||
188 | fn label(candidate: &ImportCandidate, import: &hir::ModPath) -> String { | ||
189 | match candidate { | ||
190 | ImportCandidate::UnqualifiedName(_) => format!("Qualify as `{}`", &import), | ||
191 | ImportCandidate::QualifierStart(_) => format!("Qualify with `{}`", &import), | ||
192 | ImportCandidate::TraitAssocItem(_) => format!("Qualify `{}`", &import), | ||
193 | ImportCandidate::TraitMethod(_) => format!("Qualify with cast as `{}`", &import), | ||
194 | } | ||
195 | } | ||
196 | |||
197 | #[cfg(test)] | ||
198 | mod tests { | ||
199 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
200 | |||
201 | use super::*; | ||
202 | |||
203 | #[test] | ||
204 | fn applicable_when_found_an_import_partial() { | ||
205 | mark::check!(qualify_path_unqualified_name); | ||
206 | check_assist( | ||
207 | qualify_path, | ||
208 | r" | ||
209 | mod std { | ||
210 | pub mod fmt { | ||
211 | pub struct Formatter; | ||
212 | } | ||
213 | } | ||
214 | |||
215 | use std::fmt; | ||
216 | |||
217 | <|>Formatter | ||
218 | ", | ||
219 | r" | ||
220 | mod std { | ||
221 | pub mod fmt { | ||
222 | pub struct Formatter; | ||
223 | } | ||
224 | } | ||
225 | |||
226 | use std::fmt; | ||
227 | |||
228 | fmt::Formatter | ||
229 | ", | ||
230 | ); | ||
231 | } | ||
232 | |||
233 | #[test] | ||
234 | fn applicable_when_found_an_import() { | ||
235 | check_assist( | ||
236 | qualify_path, | ||
237 | r" | ||
238 | <|>PubStruct | ||
239 | |||
240 | pub mod PubMod { | ||
241 | pub struct PubStruct; | ||
242 | } | ||
243 | ", | ||
244 | r" | ||
245 | PubMod::PubStruct | ||
246 | |||
247 | pub mod PubMod { | ||
248 | pub struct PubStruct; | ||
249 | } | ||
250 | ", | ||
251 | ); | ||
252 | } | ||
253 | |||
254 | #[test] | ||
255 | fn applicable_in_macros() { | ||
256 | check_assist( | ||
257 | qualify_path, | ||
258 | r" | ||
259 | macro_rules! foo { | ||
260 | ($i:ident) => { fn foo(a: $i) {} } | ||
261 | } | ||
262 | foo!(Pub<|>Struct); | ||
263 | |||
264 | pub mod PubMod { | ||
265 | pub struct PubStruct; | ||
266 | } | ||
267 | ", | ||
268 | r" | ||
269 | macro_rules! foo { | ||
270 | ($i:ident) => { fn foo(a: $i) {} } | ||
271 | } | ||
272 | foo!(PubMod::PubStruct); | ||
273 | |||
274 | pub mod PubMod { | ||
275 | pub struct PubStruct; | ||
276 | } | ||
277 | ", | ||
278 | ); | ||
279 | } | ||
280 | |||
281 | #[test] | ||
282 | fn applicable_when_found_multiple_imports() { | ||
283 | check_assist( | ||
284 | qualify_path, | ||
285 | r" | ||
286 | PubSt<|>ruct | ||
287 | |||
288 | pub mod PubMod1 { | ||
289 | pub struct PubStruct; | ||
290 | } | ||
291 | pub mod PubMod2 { | ||
292 | pub struct PubStruct; | ||
293 | } | ||
294 | pub mod PubMod3 { | ||
295 | pub struct PubStruct; | ||
296 | } | ||
297 | ", | ||
298 | r" | ||
299 | PubMod3::PubStruct | ||
300 | |||
301 | pub mod PubMod1 { | ||
302 | pub struct PubStruct; | ||
303 | } | ||
304 | pub mod PubMod2 { | ||
305 | pub struct PubStruct; | ||
306 | } | ||
307 | pub mod PubMod3 { | ||
308 | pub struct PubStruct; | ||
309 | } | ||
310 | ", | ||
311 | ); | ||
312 | } | ||
313 | |||
314 | #[test] | ||
315 | fn not_applicable_for_already_imported_types() { | ||
316 | check_assist_not_applicable( | ||
317 | qualify_path, | ||
318 | r" | ||
319 | use PubMod::PubStruct; | ||
320 | |||
321 | PubStruct<|> | ||
322 | |||
323 | pub mod PubMod { | ||
324 | pub struct PubStruct; | ||
325 | } | ||
326 | ", | ||
327 | ); | ||
328 | } | ||
329 | |||
330 | #[test] | ||
331 | fn not_applicable_for_types_with_private_paths() { | ||
332 | check_assist_not_applicable( | ||
333 | qualify_path, | ||
334 | r" | ||
335 | PrivateStruct<|> | ||
336 | |||
337 | pub mod PubMod { | ||
338 | struct PrivateStruct; | ||
339 | } | ||
340 | ", | ||
341 | ); | ||
342 | } | ||
343 | |||
344 | #[test] | ||
345 | fn not_applicable_when_no_imports_found() { | ||
346 | check_assist_not_applicable( | ||
347 | qualify_path, | ||
348 | " | ||
349 | PubStruct<|>", | ||
350 | ); | ||
351 | } | ||
352 | |||
353 | #[test] | ||
354 | fn not_applicable_in_import_statements() { | ||
355 | check_assist_not_applicable( | ||
356 | qualify_path, | ||
357 | r" | ||
358 | use PubStruct<|>; | ||
359 | |||
360 | pub mod PubMod { | ||
361 | pub struct PubStruct; | ||
362 | }", | ||
363 | ); | ||
364 | } | ||
365 | |||
366 | #[test] | ||
367 | fn qualify_function() { | ||
368 | check_assist( | ||
369 | qualify_path, | ||
370 | r" | ||
371 | test_function<|> | ||
372 | |||
373 | pub mod PubMod { | ||
374 | pub fn test_function() {}; | ||
375 | } | ||
376 | ", | ||
377 | r" | ||
378 | PubMod::test_function | ||
379 | |||
380 | pub mod PubMod { | ||
381 | pub fn test_function() {}; | ||
382 | } | ||
383 | ", | ||
384 | ); | ||
385 | } | ||
386 | |||
387 | #[test] | ||
388 | fn qualify_macro() { | ||
389 | check_assist( | ||
390 | qualify_path, | ||
391 | r" | ||
392 | //- /lib.rs crate:crate_with_macro | ||
393 | #[macro_export] | ||
394 | macro_rules! foo { | ||
395 | () => () | ||
396 | } | ||
397 | |||
398 | //- /main.rs crate:main deps:crate_with_macro | ||
399 | fn main() { | ||
400 | foo<|> | ||
401 | } | ||
402 | ", | ||
403 | r" | ||
404 | fn main() { | ||
405 | crate_with_macro::foo | ||
406 | } | ||
407 | ", | ||
408 | ); | ||
409 | } | ||
410 | |||
411 | #[test] | ||
412 | fn qualify_path_target() { | ||
413 | check_assist_target( | ||
414 | qualify_path, | ||
415 | r" | ||
416 | struct AssistInfo { | ||
417 | group_label: Option<<|>GroupLabel>, | ||
418 | } | ||
419 | |||
420 | mod m { pub struct GroupLabel; } | ||
421 | ", | ||
422 | "GroupLabel", | ||
423 | ) | ||
424 | } | ||
425 | |||
426 | #[test] | ||
427 | fn not_applicable_when_path_start_is_imported() { | ||
428 | check_assist_not_applicable( | ||
429 | qualify_path, | ||
430 | r" | ||
431 | pub mod mod1 { | ||
432 | pub mod mod2 { | ||
433 | pub mod mod3 { | ||
434 | pub struct TestStruct; | ||
435 | } | ||
436 | } | ||
437 | } | ||
438 | |||
439 | use mod1::mod2; | ||
440 | fn main() { | ||
441 | mod2::mod3::TestStruct<|> | ||
442 | } | ||
443 | ", | ||
444 | ); | ||
445 | } | ||
446 | |||
447 | #[test] | ||
448 | fn not_applicable_for_imported_function() { | ||
449 | check_assist_not_applicable( | ||
450 | qualify_path, | ||
451 | r" | ||
452 | pub mod test_mod { | ||
453 | pub fn test_function() {} | ||
454 | } | ||
455 | |||
456 | use test_mod::test_function; | ||
457 | fn main() { | ||
458 | test_function<|> | ||
459 | } | ||
460 | ", | ||
461 | ); | ||
462 | } | ||
463 | |||
464 | #[test] | ||
465 | fn associated_struct_function() { | ||
466 | check_assist( | ||
467 | qualify_path, | ||
468 | r" | ||
469 | mod test_mod { | ||
470 | pub struct TestStruct {} | ||
471 | impl TestStruct { | ||
472 | pub fn test_function() {} | ||
473 | } | ||
474 | } | ||
475 | |||
476 | fn main() { | ||
477 | TestStruct::test_function<|> | ||
478 | } | ||
479 | ", | ||
480 | r" | ||
481 | mod test_mod { | ||
482 | pub struct TestStruct {} | ||
483 | impl TestStruct { | ||
484 | pub fn test_function() {} | ||
485 | } | ||
486 | } | ||
487 | |||
488 | fn main() { | ||
489 | test_mod::TestStruct::test_function | ||
490 | } | ||
491 | ", | ||
492 | ); | ||
493 | } | ||
494 | |||
495 | #[test] | ||
496 | fn associated_struct_const() { | ||
497 | mark::check!(qualify_path_qualifier_start); | ||
498 | check_assist( | ||
499 | qualify_path, | ||
500 | r" | ||
501 | mod test_mod { | ||
502 | pub struct TestStruct {} | ||
503 | impl TestStruct { | ||
504 | const TEST_CONST: u8 = 42; | ||
505 | } | ||
506 | } | ||
507 | |||
508 | fn main() { | ||
509 | TestStruct::TEST_CONST<|> | ||
510 | } | ||
511 | ", | ||
512 | r" | ||
513 | mod test_mod { | ||
514 | pub struct TestStruct {} | ||
515 | impl TestStruct { | ||
516 | const TEST_CONST: u8 = 42; | ||
517 | } | ||
518 | } | ||
519 | |||
520 | fn main() { | ||
521 | test_mod::TestStruct::TEST_CONST | ||
522 | } | ||
523 | ", | ||
524 | ); | ||
525 | } | ||
526 | |||
527 | #[test] | ||
528 | fn associated_trait_function() { | ||
529 | check_assist( | ||
530 | qualify_path, | ||
531 | r" | ||
532 | mod test_mod { | ||
533 | pub trait TestTrait { | ||
534 | fn test_function(); | ||
535 | } | ||
536 | pub struct TestStruct {} | ||
537 | impl TestTrait for TestStruct { | ||
538 | fn test_function() {} | ||
539 | } | ||
540 | } | ||
541 | |||
542 | fn main() { | ||
543 | test_mod::TestStruct::test_function<|> | ||
544 | } | ||
545 | ", | ||
546 | r" | ||
547 | mod test_mod { | ||
548 | pub trait TestTrait { | ||
549 | fn test_function(); | ||
550 | } | ||
551 | pub struct TestStruct {} | ||
552 | impl TestTrait for TestStruct { | ||
553 | fn test_function() {} | ||
554 | } | ||
555 | } | ||
556 | |||
557 | fn main() { | ||
558 | <test_mod::TestStruct as test_mod::TestTrait>::test_function | ||
559 | } | ||
560 | ", | ||
561 | ); | ||
562 | } | ||
563 | |||
564 | #[test] | ||
565 | fn not_applicable_for_imported_trait_for_function() { | ||
566 | check_assist_not_applicable( | ||
567 | qualify_path, | ||
568 | r" | ||
569 | mod test_mod { | ||
570 | pub trait TestTrait { | ||
571 | fn test_function(); | ||
572 | } | ||
573 | pub trait TestTrait2 { | ||
574 | fn test_function(); | ||
575 | } | ||
576 | pub enum TestEnum { | ||
577 | One, | ||
578 | Two, | ||
579 | } | ||
580 | impl TestTrait2 for TestEnum { | ||
581 | fn test_function() {} | ||
582 | } | ||
583 | impl TestTrait for TestEnum { | ||
584 | fn test_function() {} | ||
585 | } | ||
586 | } | ||
587 | |||
588 | use test_mod::TestTrait2; | ||
589 | fn main() { | ||
590 | test_mod::TestEnum::test_function<|>; | ||
591 | } | ||
592 | ", | ||
593 | ) | ||
594 | } | ||
595 | |||
596 | #[test] | ||
597 | fn associated_trait_const() { | ||
598 | mark::check!(qualify_path_trait_assoc_item); | ||
599 | check_assist( | ||
600 | qualify_path, | ||
601 | r" | ||
602 | mod test_mod { | ||
603 | pub trait TestTrait { | ||
604 | const TEST_CONST: u8; | ||
605 | } | ||
606 | pub struct TestStruct {} | ||
607 | impl TestTrait for TestStruct { | ||
608 | const TEST_CONST: u8 = 42; | ||
609 | } | ||
610 | } | ||
611 | |||
612 | fn main() { | ||
613 | test_mod::TestStruct::TEST_CONST<|> | ||
614 | } | ||
615 | ", | ||
616 | r" | ||
617 | mod test_mod { | ||
618 | pub trait TestTrait { | ||
619 | const TEST_CONST: u8; | ||
620 | } | ||
621 | pub struct TestStruct {} | ||
622 | impl TestTrait for TestStruct { | ||
623 | const TEST_CONST: u8 = 42; | ||
624 | } | ||
625 | } | ||
626 | |||
627 | fn main() { | ||
628 | <test_mod::TestStruct as test_mod::TestTrait>::TEST_CONST | ||
629 | } | ||
630 | ", | ||
631 | ); | ||
632 | } | ||
633 | |||
634 | #[test] | ||
635 | fn not_applicable_for_imported_trait_for_const() { | ||
636 | check_assist_not_applicable( | ||
637 | qualify_path, | ||
638 | r" | ||
639 | mod test_mod { | ||
640 | pub trait TestTrait { | ||
641 | const TEST_CONST: u8; | ||
642 | } | ||
643 | pub trait TestTrait2 { | ||
644 | const TEST_CONST: f64; | ||
645 | } | ||
646 | pub enum TestEnum { | ||
647 | One, | ||
648 | Two, | ||
649 | } | ||
650 | impl TestTrait2 for TestEnum { | ||
651 | const TEST_CONST: f64 = 42.0; | ||
652 | } | ||
653 | impl TestTrait for TestEnum { | ||
654 | const TEST_CONST: u8 = 42; | ||
655 | } | ||
656 | } | ||
657 | |||
658 | use test_mod::TestTrait2; | ||
659 | fn main() { | ||
660 | test_mod::TestEnum::TEST_CONST<|>; | ||
661 | } | ||
662 | ", | ||
663 | ) | ||
664 | } | ||
665 | |||
666 | #[test] | ||
667 | fn trait_method() { | ||
668 | mark::check!(qualify_path_trait_method); | ||
669 | check_assist( | ||
670 | qualify_path, | ||
671 | r" | ||
672 | mod test_mod { | ||
673 | pub trait TestTrait { | ||
674 | fn test_method(&self); | ||
675 | } | ||
676 | pub struct TestStruct {} | ||
677 | impl TestTrait for TestStruct { | ||
678 | fn test_method(&self) {} | ||
679 | } | ||
680 | } | ||
681 | |||
682 | fn main() { | ||
683 | let test_struct = test_mod::TestStruct {}; | ||
684 | test_struct.test_meth<|>od() | ||
685 | } | ||
686 | ", | ||
687 | r" | ||
688 | mod test_mod { | ||
689 | pub trait TestTrait { | ||
690 | fn test_method(&self); | ||
691 | } | ||
692 | pub struct TestStruct {} | ||
693 | impl TestTrait for TestStruct { | ||
694 | fn test_method(&self) {} | ||
695 | } | ||
696 | } | ||
697 | |||
698 | fn main() { | ||
699 | let test_struct = test_mod::TestStruct {}; | ||
700 | test_mod::TestTrait::test_method(&test_struct) | ||
701 | } | ||
702 | ", | ||
703 | ); | ||
704 | } | ||
705 | |||
706 | #[test] | ||
707 | fn trait_method_multi_params() { | ||
708 | check_assist( | ||
709 | qualify_path, | ||
710 | r" | ||
711 | mod test_mod { | ||
712 | pub trait TestTrait { | ||
713 | fn test_method(&self, test: i32); | ||
714 | } | ||
715 | pub struct TestStruct {} | ||
716 | impl TestTrait for TestStruct { | ||
717 | fn test_method(&self, test: i32) {} | ||
718 | } | ||
719 | } | ||
720 | |||
721 | fn main() { | ||
722 | let test_struct = test_mod::TestStruct {}; | ||
723 | test_struct.test_meth<|>od(42) | ||
724 | } | ||
725 | ", | ||
726 | r" | ||
727 | mod test_mod { | ||
728 | pub trait TestTrait { | ||
729 | fn test_method(&self, test: i32); | ||
730 | } | ||
731 | pub struct TestStruct {} | ||
732 | impl TestTrait for TestStruct { | ||
733 | fn test_method(&self, test: i32) {} | ||
734 | } | ||
735 | } | ||
736 | |||
737 | fn main() { | ||
738 | let test_struct = test_mod::TestStruct {}; | ||
739 | test_mod::TestTrait::test_method(&test_struct, 42) | ||
740 | } | ||
741 | ", | ||
742 | ); | ||
743 | } | ||
744 | |||
745 | #[test] | ||
746 | fn trait_method_consume() { | ||
747 | check_assist( | ||
748 | qualify_path, | ||
749 | r" | ||
750 | mod test_mod { | ||
751 | pub trait TestTrait { | ||
752 | fn test_method(self); | ||
753 | } | ||
754 | pub struct TestStruct {} | ||
755 | impl TestTrait for TestStruct { | ||
756 | fn test_method(self) {} | ||
757 | } | ||
758 | } | ||
759 | |||
760 | fn main() { | ||
761 | let test_struct = test_mod::TestStruct {}; | ||
762 | test_struct.test_meth<|>od() | ||
763 | } | ||
764 | ", | ||
765 | r" | ||
766 | mod test_mod { | ||
767 | pub trait TestTrait { | ||
768 | fn test_method(self); | ||
769 | } | ||
770 | pub struct TestStruct {} | ||
771 | impl TestTrait for TestStruct { | ||
772 | fn test_method(self) {} | ||
773 | } | ||
774 | } | ||
775 | |||
776 | fn main() { | ||
777 | let test_struct = test_mod::TestStruct {}; | ||
778 | test_mod::TestTrait::test_method(test_struct) | ||
779 | } | ||
780 | ", | ||
781 | ); | ||
782 | } | ||
783 | |||
784 | #[test] | ||
785 | fn trait_method_cross_crate() { | ||
786 | check_assist( | ||
787 | qualify_path, | ||
788 | r" | ||
789 | //- /main.rs crate:main deps:dep | ||
790 | fn main() { | ||
791 | let test_struct = dep::test_mod::TestStruct {}; | ||
792 | test_struct.test_meth<|>od() | ||
793 | } | ||
794 | //- /dep.rs crate:dep | ||
795 | pub mod test_mod { | ||
796 | pub trait TestTrait { | ||
797 | fn test_method(&self); | ||
798 | } | ||
799 | pub struct TestStruct {} | ||
800 | impl TestTrait for TestStruct { | ||
801 | fn test_method(&self) {} | ||
802 | } | ||
803 | } | ||
804 | ", | ||
805 | r" | ||
806 | fn main() { | ||
807 | let test_struct = dep::test_mod::TestStruct {}; | ||
808 | dep::test_mod::TestTrait::test_method(&test_struct) | ||
809 | } | ||
810 | ", | ||
811 | ); | ||
812 | } | ||
813 | |||
814 | #[test] | ||
815 | fn assoc_fn_cross_crate() { | ||
816 | check_assist( | ||
817 | qualify_path, | ||
818 | r" | ||
819 | //- /main.rs crate:main deps:dep | ||
820 | fn main() { | ||
821 | dep::test_mod::TestStruct::test_func<|>tion | ||
822 | } | ||
823 | //- /dep.rs crate:dep | ||
824 | pub mod test_mod { | ||
825 | pub trait TestTrait { | ||
826 | fn test_function(); | ||
827 | } | ||
828 | pub struct TestStruct {} | ||
829 | impl TestTrait for TestStruct { | ||
830 | fn test_function() {} | ||
831 | } | ||
832 | } | ||
833 | ", | ||
834 | r" | ||
835 | fn main() { | ||
836 | <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::test_function | ||
837 | } | ||
838 | ", | ||
839 | ); | ||
840 | } | ||
841 | |||
842 | #[test] | ||
843 | fn assoc_const_cross_crate() { | ||
844 | check_assist( | ||
845 | qualify_path, | ||
846 | r" | ||
847 | //- /main.rs crate:main deps:dep | ||
848 | fn main() { | ||
849 | dep::test_mod::TestStruct::CONST<|> | ||
850 | } | ||
851 | //- /dep.rs crate:dep | ||
852 | pub mod test_mod { | ||
853 | pub trait TestTrait { | ||
854 | const CONST: bool; | ||
855 | } | ||
856 | pub struct TestStruct {} | ||
857 | impl TestTrait for TestStruct { | ||
858 | const CONST: bool = true; | ||
859 | } | ||
860 | } | ||
861 | ", | ||
862 | r" | ||
863 | fn main() { | ||
864 | <dep::test_mod::TestStruct as dep::test_mod::TestTrait>::CONST | ||
865 | } | ||
866 | ", | ||
867 | ); | ||
868 | } | ||
869 | |||
870 | #[test] | ||
871 | fn assoc_fn_as_method_cross_crate() { | ||
872 | check_assist_not_applicable( | ||
873 | qualify_path, | ||
874 | r" | ||
875 | //- /main.rs crate:main deps:dep | ||
876 | fn main() { | ||
877 | let test_struct = dep::test_mod::TestStruct {}; | ||
878 | test_struct.test_func<|>tion() | ||
879 | } | ||
880 | //- /dep.rs crate:dep | ||
881 | pub mod test_mod { | ||
882 | pub trait TestTrait { | ||
883 | fn test_function(); | ||
884 | } | ||
885 | pub struct TestStruct {} | ||
886 | impl TestTrait for TestStruct { | ||
887 | fn test_function() {} | ||
888 | } | ||
889 | } | ||
890 | ", | ||
891 | ); | ||
892 | } | ||
893 | |||
894 | #[test] | ||
895 | fn private_trait_cross_crate() { | ||
896 | check_assist_not_applicable( | ||
897 | qualify_path, | ||
898 | r" | ||
899 | //- /main.rs crate:main deps:dep | ||
900 | fn main() { | ||
901 | let test_struct = dep::test_mod::TestStruct {}; | ||
902 | test_struct.test_meth<|>od() | ||
903 | } | ||
904 | //- /dep.rs crate:dep | ||
905 | pub mod test_mod { | ||
906 | trait TestTrait { | ||
907 | fn test_method(&self); | ||
908 | } | ||
909 | pub struct TestStruct {} | ||
910 | impl TestTrait for TestStruct { | ||
911 | fn test_method(&self) {} | ||
912 | } | ||
913 | } | ||
914 | ", | ||
915 | ); | ||
916 | } | ||
917 | |||
918 | #[test] | ||
919 | fn not_applicable_for_imported_trait_for_method() { | ||
920 | check_assist_not_applicable( | ||
921 | qualify_path, | ||
922 | r" | ||
923 | mod test_mod { | ||
924 | pub trait TestTrait { | ||
925 | fn test_method(&self); | ||
926 | } | ||
927 | pub trait TestTrait2 { | ||
928 | fn test_method(&self); | ||
929 | } | ||
930 | pub enum TestEnum { | ||
931 | One, | ||
932 | Two, | ||
933 | } | ||
934 | impl TestTrait2 for TestEnum { | ||
935 | fn test_method(&self) {} | ||
936 | } | ||
937 | impl TestTrait for TestEnum { | ||
938 | fn test_method(&self) {} | ||
939 | } | ||
940 | } | ||
941 | |||
942 | use test_mod::TestTrait2; | ||
943 | fn main() { | ||
944 | let one = test_mod::TestEnum::One; | ||
945 | one.test<|>_method(); | ||
946 | } | ||
947 | ", | ||
948 | ) | ||
949 | } | ||
950 | |||
951 | #[test] | ||
952 | fn dep_import() { | ||
953 | check_assist( | ||
954 | qualify_path, | ||
955 | r" | ||
956 | //- /lib.rs crate:dep | ||
957 | pub struct Struct; | ||
958 | |||
959 | //- /main.rs crate:main deps:dep | ||
960 | fn main() { | ||
961 | Struct<|> | ||
962 | } | ||
963 | ", | ||
964 | r" | ||
965 | fn main() { | ||
966 | dep::Struct | ||
967 | } | ||
968 | ", | ||
969 | ); | ||
970 | } | ||
971 | |||
972 | #[test] | ||
973 | fn whole_segment() { | ||
974 | // Tests that only imports whose last segment matches the identifier get suggested. | ||
975 | check_assist( | ||
976 | qualify_path, | ||
977 | r" | ||
978 | //- /lib.rs crate:dep | ||
979 | pub mod fmt { | ||
980 | pub trait Display {} | ||
981 | } | ||
982 | |||
983 | pub fn panic_fmt() {} | ||
984 | |||
985 | //- /main.rs crate:main deps:dep | ||
986 | struct S; | ||
987 | |||
988 | impl f<|>mt::Display for S {} | ||
989 | ", | ||
990 | r" | ||
991 | struct S; | ||
992 | |||
993 | impl dep::fmt::Display for S {} | ||
994 | ", | ||
995 | ); | ||
996 | } | ||
997 | |||
998 | #[test] | ||
999 | fn macro_generated() { | ||
1000 | // Tests that macro-generated items are suggested from external crates. | ||
1001 | check_assist( | ||
1002 | qualify_path, | ||
1003 | r" | ||
1004 | //- /lib.rs crate:dep | ||
1005 | macro_rules! mac { | ||
1006 | () => { | ||
1007 | pub struct Cheese; | ||
1008 | }; | ||
1009 | } | ||
1010 | |||
1011 | mac!(); | ||
1012 | |||
1013 | //- /main.rs crate:main deps:dep | ||
1014 | fn main() { | ||
1015 | Cheese<|>; | ||
1016 | } | ||
1017 | ", | ||
1018 | r" | ||
1019 | fn main() { | ||
1020 | dep::Cheese; | ||
1021 | } | ||
1022 | ", | ||
1023 | ); | ||
1024 | } | ||
1025 | |||
1026 | #[test] | ||
1027 | fn casing() { | ||
1028 | // Tests that differently cased names don't interfere and we only suggest the matching one. | ||
1029 | check_assist( | ||
1030 | qualify_path, | ||
1031 | r" | ||
1032 | //- /lib.rs crate:dep | ||
1033 | pub struct FMT; | ||
1034 | pub struct fmt; | ||
1035 | |||
1036 | //- /main.rs crate:main deps:dep | ||
1037 | fn main() { | ||
1038 | FMT<|>; | ||
1039 | } | ||
1040 | ", | ||
1041 | r" | ||
1042 | fn main() { | ||
1043 | dep::FMT; | ||
1044 | } | ||
1045 | ", | ||
1046 | ); | ||
1047 | } | ||
1048 | } | ||
diff --git a/crates/assists/src/handlers/remove_dbg.rs b/crates/assists/src/handlers/remove_dbg.rs index e10616779..9731344b8 100644 --- a/crates/assists/src/handlers/remove_dbg.rs +++ b/crates/assists/src/handlers/remove_dbg.rs | |||
@@ -93,8 +93,9 @@ fn needs_parentheses_around_macro_contents(macro_contents: Vec<SyntaxElement>) - | |||
93 | if macro_contents.len() < 2 { | 93 | if macro_contents.len() < 2 { |
94 | return false; | 94 | return false; |
95 | } | 95 | } |
96 | let mut macro_contents = macro_contents.into_iter().peekable(); | ||
96 | let mut unpaired_brackets_in_contents = Vec::new(); | 97 | let mut unpaired_brackets_in_contents = Vec::new(); |
97 | for element in macro_contents { | 98 | while let Some(element) = macro_contents.next() { |
98 | match element.kind() { | 99 | match element.kind() { |
99 | T!['('] | T!['['] | T!['{'] => unpaired_brackets_in_contents.push(element), | 100 | T!['('] | T!['['] | T!['{'] => unpaired_brackets_in_contents.push(element), |
100 | T![')'] => { | 101 | T![')'] => { |
@@ -118,8 +119,14 @@ fn needs_parentheses_around_macro_contents(macro_contents: Vec<SyntaxElement>) - | |||
118 | symbol_kind => { | 119 | symbol_kind => { |
119 | let symbol_not_in_bracket = unpaired_brackets_in_contents.is_empty(); | 120 | let symbol_not_in_bracket = unpaired_brackets_in_contents.is_empty(); |
120 | if symbol_not_in_bracket | 121 | if symbol_not_in_bracket |
121 | && symbol_kind != SyntaxKind::COLON | 122 | && symbol_kind != SyntaxKind::COLON // paths |
122 | && symbol_kind.is_punct() | 123 | && (symbol_kind != SyntaxKind::DOT // field/method access |
124 | || macro_contents // range expressions consist of two SyntaxKind::Dot in macro invocations | ||
125 | .peek() | ||
126 | .map(|element| element.kind() == SyntaxKind::DOT) | ||
127 | .unwrap_or(false)) | ||
128 | && symbol_kind != SyntaxKind::QUESTION // try operator | ||
129 | && (symbol_kind.is_punct() || symbol_kind == SyntaxKind::AS_KW) | ||
123 | { | 130 | { |
124 | return true; | 131 | return true; |
125 | } | 132 | } |
@@ -243,6 +250,25 @@ fn main() { | |||
243 | } | 250 | } |
244 | 251 | ||
245 | #[test] | 252 | #[test] |
253 | fn test_remove_dbg_method_chaining() { | ||
254 | check_assist( | ||
255 | remove_dbg, | ||
256 | r#"let res = <|>dbg!(foo().bar()).baz();"#, | ||
257 | r#"let res = foo().bar().baz();"#, | ||
258 | ); | ||
259 | check_assist( | ||
260 | remove_dbg, | ||
261 | r#"let res = <|>dbg!(foo.bar()).baz();"#, | ||
262 | r#"let res = foo.bar().baz();"#, | ||
263 | ); | ||
264 | } | ||
265 | |||
266 | #[test] | ||
267 | fn test_remove_dbg_field_chaining() { | ||
268 | check_assist(remove_dbg, r#"let res = <|>dbg!(foo.bar).baz;"#, r#"let res = foo.bar.baz;"#); | ||
269 | } | ||
270 | |||
271 | #[test] | ||
246 | fn test_remove_dbg_from_inside_fn() { | 272 | fn test_remove_dbg_from_inside_fn() { |
247 | check_assist_target( | 273 | check_assist_target( |
248 | remove_dbg, | 274 | remove_dbg, |
@@ -280,4 +306,59 @@ fn main() { | |||
280 | }"#, | 306 | }"#, |
281 | ); | 307 | ); |
282 | } | 308 | } |
309 | |||
310 | #[test] | ||
311 | fn test_remove_dbg_try_expr() { | ||
312 | check_assist( | ||
313 | remove_dbg, | ||
314 | r#"let res = <|>dbg!(result?).foo();"#, | ||
315 | r#"let res = result?.foo();"#, | ||
316 | ); | ||
317 | } | ||
318 | |||
319 | #[test] | ||
320 | fn test_remove_dbg_await_expr() { | ||
321 | check_assist( | ||
322 | remove_dbg, | ||
323 | r#"let res = <|>dbg!(fut.await).foo();"#, | ||
324 | r#"let res = fut.await.foo();"#, | ||
325 | ); | ||
326 | } | ||
327 | |||
328 | #[test] | ||
329 | fn test_remove_dbg_as_cast() { | ||
330 | check_assist( | ||
331 | remove_dbg, | ||
332 | r#"let res = <|>dbg!(3 as usize).foo();"#, | ||
333 | r#"let res = (3 as usize).foo();"#, | ||
334 | ); | ||
335 | } | ||
336 | |||
337 | #[test] | ||
338 | fn test_remove_dbg_index_expr() { | ||
339 | check_assist( | ||
340 | remove_dbg, | ||
341 | r#"let res = <|>dbg!(array[3]).foo();"#, | ||
342 | r#"let res = array[3].foo();"#, | ||
343 | ); | ||
344 | check_assist( | ||
345 | remove_dbg, | ||
346 | r#"let res = <|>dbg!(tuple.3).foo();"#, | ||
347 | r#"let res = tuple.3.foo();"#, | ||
348 | ); | ||
349 | } | ||
350 | |||
351 | #[test] | ||
352 | fn test_remove_dbg_range_expr() { | ||
353 | check_assist( | ||
354 | remove_dbg, | ||
355 | r#"let res = <|>dbg!(foo..bar).foo();"#, | ||
356 | r#"let res = (foo..bar).foo();"#, | ||
357 | ); | ||
358 | check_assist( | ||
359 | remove_dbg, | ||
360 | r#"let res = <|>dbg!(foo..=bar).foo();"#, | ||
361 | r#"let res = (foo..=bar).foo();"#, | ||
362 | ); | ||
363 | } | ||
283 | } | 364 | } |
diff --git a/crates/assists/src/handlers/replace_if_let_with_match.rs b/crates/assists/src/handlers/replace_if_let_with_match.rs index 79097621e..9a49c48c1 100644 --- a/crates/assists/src/handlers/replace_if_let_with_match.rs +++ b/crates/assists/src/handlers/replace_if_let_with_match.rs | |||
@@ -7,10 +7,8 @@ use syntax::{ | |||
7 | AstNode, | 7 | AstNode, |
8 | }; | 8 | }; |
9 | 9 | ||
10 | use crate::{ | 10 | use crate::{utils::unwrap_trivial_block, AssistContext, AssistId, AssistKind, Assists}; |
11 | utils::{unwrap_trivial_block, TryEnum}, | 11 | use ide_db::ty_filter::TryEnum; |
12 | AssistContext, AssistId, AssistKind, Assists, | ||
13 | }; | ||
14 | 12 | ||
15 | // Assist: replace_if_let_with_match | 13 | // Assist: replace_if_let_with_match |
16 | // | 14 | // |
diff --git a/crates/assists/src/handlers/replace_let_with_if_let.rs b/crates/assists/src/handlers/replace_let_with_if_let.rs index ed6d0c29b..a5bcbda24 100644 --- a/crates/assists/src/handlers/replace_let_with_if_let.rs +++ b/crates/assists/src/handlers/replace_let_with_if_let.rs | |||
@@ -9,7 +9,8 @@ use syntax::{ | |||
9 | AstNode, T, | 9 | AstNode, T, |
10 | }; | 10 | }; |
11 | 11 | ||
12 | use crate::{utils::TryEnum, AssistContext, AssistId, AssistKind, Assists}; | 12 | use crate::{AssistContext, AssistId, AssistKind, Assists}; |
13 | use ide_db::ty_filter::TryEnum; | ||
13 | 14 | ||
14 | // Assist: replace_let_with_if_let | 15 | // Assist: replace_let_with_if_let |
15 | // | 16 | // |
diff --git a/crates/assists/src/handlers/replace_string_with_char.rs b/crates/assists/src/handlers/replace_string_with_char.rs new file mode 100644 index 000000000..4ca87a8ec --- /dev/null +++ b/crates/assists/src/handlers/replace_string_with_char.rs | |||
@@ -0,0 +1,141 @@ | |||
1 | use syntax::{ | ||
2 | ast::{self, HasStringValue}, | ||
3 | AstToken, | ||
4 | SyntaxKind::STRING, | ||
5 | }; | ||
6 | |||
7 | use crate::{AssistContext, AssistId, AssistKind, Assists}; | ||
8 | |||
9 | // Assist: replace_string_with_char | ||
10 | // | ||
11 | // Replace string with char. | ||
12 | // | ||
13 | // ``` | ||
14 | // fn main() { | ||
15 | // find("{<|>"); | ||
16 | // } | ||
17 | // ``` | ||
18 | // -> | ||
19 | // ``` | ||
20 | // fn main() { | ||
21 | // find('{'); | ||
22 | // } | ||
23 | // ``` | ||
24 | pub(crate) fn replace_string_with_char(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { | ||
25 | let token = ctx.find_token_at_offset(STRING).and_then(ast::String::cast)?; | ||
26 | let value = token.value()?; | ||
27 | let target = token.syntax().text_range(); | ||
28 | |||
29 | if value.chars().take(2).count() != 1 { | ||
30 | return None; | ||
31 | } | ||
32 | |||
33 | acc.add( | ||
34 | AssistId("replace_string_with_char", AssistKind::RefactorRewrite), | ||
35 | "Replace string with char", | ||
36 | target, | ||
37 | |edit| { | ||
38 | edit.replace(token.syntax().text_range(), format!("'{}'", value)); | ||
39 | }, | ||
40 | ) | ||
41 | } | ||
42 | |||
43 | #[cfg(test)] | ||
44 | mod tests { | ||
45 | use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target}; | ||
46 | |||
47 | use super::*; | ||
48 | |||
49 | #[test] | ||
50 | fn replace_string_with_char_target() { | ||
51 | check_assist_target( | ||
52 | replace_string_with_char, | ||
53 | r#" | ||
54 | fn f() { | ||
55 | let s = "<|>c"; | ||
56 | } | ||
57 | "#, | ||
58 | r#""c""#, | ||
59 | ); | ||
60 | } | ||
61 | |||
62 | #[test] | ||
63 | fn replace_string_with_char_assist() { | ||
64 | check_assist( | ||
65 | replace_string_with_char, | ||
66 | r#" | ||
67 | fn f() { | ||
68 | let s = "<|>c"; | ||
69 | } | ||
70 | "#, | ||
71 | r##" | ||
72 | fn f() { | ||
73 | let s = 'c'; | ||
74 | } | ||
75 | "##, | ||
76 | ) | ||
77 | } | ||
78 | |||
79 | #[test] | ||
80 | fn replace_string_with_char_assist_with_emoji() { | ||
81 | check_assist( | ||
82 | replace_string_with_char, | ||
83 | r#" | ||
84 | fn f() { | ||
85 | let s = "<|>😀"; | ||
86 | } | ||
87 | "#, | ||
88 | r##" | ||
89 | fn f() { | ||
90 | let s = '😀'; | ||
91 | } | ||
92 | "##, | ||
93 | ) | ||
94 | } | ||
95 | |||
96 | #[test] | ||
97 | fn replace_string_with_char_assist_not_applicable() { | ||
98 | check_assist_not_applicable( | ||
99 | replace_string_with_char, | ||
100 | r#" | ||
101 | fn f() { | ||
102 | let s = "<|>test"; | ||
103 | } | ||
104 | "#, | ||
105 | ) | ||
106 | } | ||
107 | |||
108 | #[test] | ||
109 | fn replace_string_with_char_works_inside_macros() { | ||
110 | check_assist( | ||
111 | replace_string_with_char, | ||
112 | r#" | ||
113 | fn f() { | ||
114 | format!(<|>"x", 92) | ||
115 | } | ||
116 | "#, | ||
117 | r##" | ||
118 | fn f() { | ||
119 | format!('x', 92) | ||
120 | } | ||
121 | "##, | ||
122 | ) | ||
123 | } | ||
124 | |||
125 | #[test] | ||
126 | fn replace_string_with_char_works_func_args() { | ||
127 | check_assist( | ||
128 | replace_string_with_char, | ||
129 | r#" | ||
130 | fn f() { | ||
131 | find(<|>"x"); | ||
132 | } | ||
133 | "#, | ||
134 | r##" | ||
135 | fn f() { | ||
136 | find('x'); | ||
137 | } | ||
138 | "##, | ||
139 | ) | ||
140 | } | ||
141 | } | ||
diff --git a/crates/assists/src/handlers/replace_unwrap_with_match.rs b/crates/assists/src/handlers/replace_unwrap_with_match.rs index 4043c219c..f547066f0 100644 --- a/crates/assists/src/handlers/replace_unwrap_with_match.rs +++ b/crates/assists/src/handlers/replace_unwrap_with_match.rs | |||
@@ -10,9 +10,10 @@ use syntax::{ | |||
10 | }; | 10 | }; |
11 | 11 | ||
12 | use crate::{ | 12 | use crate::{ |
13 | utils::{render_snippet, Cursor, TryEnum}, | 13 | utils::{render_snippet, Cursor}, |
14 | AssistContext, AssistId, AssistKind, Assists, | 14 | AssistContext, AssistId, AssistKind, Assists, |
15 | }; | 15 | }; |
16 | use ide_db::ty_filter::TryEnum; | ||
16 | 17 | ||
17 | // Assist: replace_unwrap_with_match | 18 | // Assist: replace_unwrap_with_match |
18 | // | 19 | // |
diff --git a/crates/assists/src/lib.rs b/crates/assists/src/lib.rs index a2bec818c..b804e495d 100644 --- a/crates/assists/src/lib.rs +++ b/crates/assists/src/lib.rs | |||
@@ -17,8 +17,8 @@ mod tests; | |||
17 | pub mod utils; | 17 | pub mod utils; |
18 | pub mod ast_transform; | 18 | pub mod ast_transform; |
19 | 19 | ||
20 | use base_db::FileRange; | ||
21 | use hir::Semantics; | 20 | use hir::Semantics; |
21 | use ide_db::base_db::FileRange; | ||
22 | use ide_db::{label::Label, source_change::SourceChange, RootDatabase}; | 22 | use ide_db::{label::Label, source_change::SourceChange, RootDatabase}; |
23 | use syntax::TextRange; | 23 | use syntax::TextRange; |
24 | 24 | ||
@@ -150,6 +150,7 @@ mod handlers { | |||
150 | mod merge_match_arms; | 150 | mod merge_match_arms; |
151 | mod move_bounds; | 151 | mod move_bounds; |
152 | mod move_guard; | 152 | mod move_guard; |
153 | mod qualify_path; | ||
153 | mod raw_string; | 154 | mod raw_string; |
154 | mod remove_dbg; | 155 | mod remove_dbg; |
155 | mod remove_mut; | 156 | mod remove_mut; |
@@ -159,6 +160,7 @@ mod handlers { | |||
159 | mod replace_impl_trait_with_generic; | 160 | mod replace_impl_trait_with_generic; |
160 | mod replace_let_with_if_let; | 161 | mod replace_let_with_if_let; |
161 | mod replace_qualified_name_with_use; | 162 | mod replace_qualified_name_with_use; |
163 | mod replace_string_with_char; | ||
162 | mod replace_unwrap_with_match; | 164 | mod replace_unwrap_with_match; |
163 | mod split_import; | 165 | mod split_import; |
164 | mod unwrap_block; | 166 | mod unwrap_block; |
@@ -196,8 +198,8 @@ mod handlers { | |||
196 | move_bounds::move_bounds_to_where_clause, | 198 | move_bounds::move_bounds_to_where_clause, |
197 | move_guard::move_arm_cond_to_match_guard, | 199 | move_guard::move_arm_cond_to_match_guard, |
198 | move_guard::move_guard_to_arm_body, | 200 | move_guard::move_guard_to_arm_body, |
201 | qualify_path::qualify_path, | ||
199 | raw_string::add_hash, | 202 | raw_string::add_hash, |
200 | raw_string::make_raw_string, | ||
201 | raw_string::make_usual_string, | 203 | raw_string::make_usual_string, |
202 | raw_string::remove_hash, | 204 | raw_string::remove_hash, |
203 | remove_dbg::remove_dbg, | 205 | remove_dbg::remove_dbg, |
@@ -214,6 +216,9 @@ mod handlers { | |||
214 | // These are manually sorted for better priorities | 216 | // These are manually sorted for better priorities |
215 | add_missing_impl_members::add_missing_impl_members, | 217 | add_missing_impl_members::add_missing_impl_members, |
216 | add_missing_impl_members::add_missing_default_members, | 218 | add_missing_impl_members::add_missing_default_members, |
219 | // | ||
220 | replace_string_with_char::replace_string_with_char, | ||
221 | raw_string::make_raw_string, | ||
217 | // Are you sure you want to add new assist here, and not to the | 222 | // Are you sure you want to add new assist here, and not to the |
218 | // sorted list above? | 223 | // sorted list above? |
219 | ] | 224 | ] |
diff --git a/crates/assists/src/tests.rs b/crates/assists/src/tests.rs index 2b687decf..849d85e76 100644 --- a/crates/assists/src/tests.rs +++ b/crates/assists/src/tests.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | mod generated; | 1 | mod generated; |
2 | 2 | ||
3 | use base_db::{fixture::WithFixture, FileId, FileRange, SourceDatabaseExt}; | ||
4 | use hir::Semantics; | 3 | use hir::Semantics; |
4 | use ide_db::base_db::{fixture::WithFixture, FileId, FileRange, SourceDatabaseExt}; | ||
5 | use ide_db::RootDatabase; | 5 | use ide_db::RootDatabase; |
6 | use syntax::TextRange; | 6 | use syntax::TextRange; |
7 | use test_utils::{assert_eq_text, extract_offset, extract_range}; | 7 | use test_utils::{assert_eq_text, extract_offset, extract_range}; |
diff --git a/crates/assists/src/tests/generated.rs b/crates/assists/src/tests/generated.rs index 41f536574..acbf5b652 100644 --- a/crates/assists/src/tests/generated.rs +++ b/crates/assists/src/tests/generated.rs | |||
@@ -713,6 +713,25 @@ fn handle(action: Action) { | |||
713 | } | 713 | } |
714 | 714 | ||
715 | #[test] | 715 | #[test] |
716 | fn doctest_qualify_path() { | ||
717 | check_doc_test( | ||
718 | "qualify_path", | ||
719 | r#####" | ||
720 | fn main() { | ||
721 | let map = HashMap<|>::new(); | ||
722 | } | ||
723 | pub mod std { pub mod collections { pub struct HashMap { } } } | ||
724 | "#####, | ||
725 | r#####" | ||
726 | fn main() { | ||
727 | let map = std::collections::HashMap::new(); | ||
728 | } | ||
729 | pub mod std { pub mod collections { pub struct HashMap { } } } | ||
730 | "#####, | ||
731 | ) | ||
732 | } | ||
733 | |||
734 | #[test] | ||
716 | fn doctest_remove_dbg() { | 735 | fn doctest_remove_dbg() { |
717 | check_doc_test( | 736 | check_doc_test( |
718 | "remove_dbg", | 737 | "remove_dbg", |
@@ -882,6 +901,23 @@ fn process(map: HashMap<String, String>) {} | |||
882 | } | 901 | } |
883 | 902 | ||
884 | #[test] | 903 | #[test] |
904 | fn doctest_replace_string_with_char() { | ||
905 | check_doc_test( | ||
906 | "replace_string_with_char", | ||
907 | r#####" | ||
908 | fn main() { | ||
909 | find("{<|>"); | ||
910 | } | ||
911 | "#####, | ||
912 | r#####" | ||
913 | fn main() { | ||
914 | find('{'); | ||
915 | } | ||
916 | "#####, | ||
917 | ) | ||
918 | } | ||
919 | |||
920 | #[test] | ||
885 | fn doctest_replace_unwrap_with_match() { | 921 | fn doctest_replace_unwrap_with_match() { |
886 | check_doc_test( | 922 | check_doc_test( |
887 | "replace_unwrap_with_match", | 923 | "replace_unwrap_with_match", |
diff --git a/crates/assists/src/utils.rs b/crates/assists/src/utils.rs index b37b0d2b6..56f925ee6 100644 --- a/crates/assists/src/utils.rs +++ b/crates/assists/src/utils.rs | |||
@@ -2,14 +2,13 @@ | |||
2 | pub(crate) mod insert_use; | 2 | pub(crate) mod insert_use; |
3 | pub(crate) mod import_assets; | 3 | pub(crate) mod import_assets; |
4 | 4 | ||
5 | use std::{iter, ops}; | 5 | use std::ops; |
6 | 6 | ||
7 | use hir::{Adt, Crate, Enum, Module, ScopeDef, Semantics, Trait, Type}; | 7 | use hir::{Crate, Enum, Module, ScopeDef, Semantics, Trait}; |
8 | use ide_db::RootDatabase; | 8 | use ide_db::RootDatabase; |
9 | use itertools::Itertools; | 9 | use itertools::Itertools; |
10 | use rustc_hash::FxHashSet; | ||
11 | use syntax::{ | 10 | use syntax::{ |
12 | ast::{self, make, ArgListOwner, NameOwner}, | 11 | ast::{self, make, ArgListOwner}, |
13 | AstNode, Direction, | 12 | AstNode, Direction, |
14 | SyntaxKind::*, | 13 | SyntaxKind::*, |
15 | SyntaxNode, TextSize, T, | 14 | SyntaxNode, TextSize, T, |
@@ -115,72 +114,6 @@ pub(crate) fn render_snippet(_cap: SnippetCap, node: &SyntaxNode, cursor: Cursor | |||
115 | } | 114 | } |
116 | } | 115 | } |
117 | 116 | ||
118 | pub fn get_missing_assoc_items( | ||
119 | sema: &Semantics<RootDatabase>, | ||
120 | impl_def: &ast::Impl, | ||
121 | ) -> Vec<hir::AssocItem> { | ||
122 | // Names must be unique between constants and functions. However, type aliases | ||
123 | // may share the same name as a function or constant. | ||
124 | let mut impl_fns_consts = FxHashSet::default(); | ||
125 | let mut impl_type = FxHashSet::default(); | ||
126 | |||
127 | if let Some(item_list) = impl_def.assoc_item_list() { | ||
128 | for item in item_list.assoc_items() { | ||
129 | match item { | ||
130 | ast::AssocItem::Fn(f) => { | ||
131 | if let Some(n) = f.name() { | ||
132 | impl_fns_consts.insert(n.syntax().to_string()); | ||
133 | } | ||
134 | } | ||
135 | |||
136 | ast::AssocItem::TypeAlias(t) => { | ||
137 | if let Some(n) = t.name() { | ||
138 | impl_type.insert(n.syntax().to_string()); | ||
139 | } | ||
140 | } | ||
141 | |||
142 | ast::AssocItem::Const(c) => { | ||
143 | if let Some(n) = c.name() { | ||
144 | impl_fns_consts.insert(n.syntax().to_string()); | ||
145 | } | ||
146 | } | ||
147 | ast::AssocItem::MacroCall(_) => (), | ||
148 | } | ||
149 | } | ||
150 | } | ||
151 | |||
152 | resolve_target_trait(sema, impl_def).map_or(vec![], |target_trait| { | ||
153 | target_trait | ||
154 | .items(sema.db) | ||
155 | .iter() | ||
156 | .filter(|i| match i { | ||
157 | hir::AssocItem::Function(f) => { | ||
158 | !impl_fns_consts.contains(&f.name(sema.db).to_string()) | ||
159 | } | ||
160 | hir::AssocItem::TypeAlias(t) => !impl_type.contains(&t.name(sema.db).to_string()), | ||
161 | hir::AssocItem::Const(c) => c | ||
162 | .name(sema.db) | ||
163 | .map(|n| !impl_fns_consts.contains(&n.to_string())) | ||
164 | .unwrap_or_default(), | ||
165 | }) | ||
166 | .cloned() | ||
167 | .collect() | ||
168 | }) | ||
169 | } | ||
170 | |||
171 | pub(crate) fn resolve_target_trait( | ||
172 | sema: &Semantics<RootDatabase>, | ||
173 | impl_def: &ast::Impl, | ||
174 | ) -> Option<hir::Trait> { | ||
175 | let ast_path = | ||
176 | impl_def.trait_().map(|it| it.syntax().clone()).and_then(ast::PathType::cast)?.path()?; | ||
177 | |||
178 | match sema.resolve_path(&ast_path) { | ||
179 | Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def), | ||
180 | _ => None, | ||
181 | } | ||
182 | } | ||
183 | |||
184 | pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize { | 117 | pub(crate) fn vis_offset(node: &SyntaxNode) -> TextSize { |
185 | node.children_with_tokens() | 118 | node.children_with_tokens() |
186 | .find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR)) | 119 | .find(|it| !matches!(it.kind(), WHITESPACE | COMMENT | ATTR)) |
@@ -223,59 +156,11 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> { | |||
223 | } | 156 | } |
224 | } | 157 | } |
225 | 158 | ||
226 | #[derive(Clone, Copy)] | ||
227 | pub enum TryEnum { | ||
228 | Result, | ||
229 | Option, | ||
230 | } | ||
231 | |||
232 | impl TryEnum { | ||
233 | const ALL: [TryEnum; 2] = [TryEnum::Option, TryEnum::Result]; | ||
234 | |||
235 | pub fn from_ty(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<TryEnum> { | ||
236 | let enum_ = match ty.as_adt() { | ||
237 | Some(Adt::Enum(it)) => it, | ||
238 | _ => return None, | ||
239 | }; | ||
240 | TryEnum::ALL.iter().find_map(|&var| { | ||
241 | if &enum_.name(sema.db).to_string() == var.type_name() { | ||
242 | return Some(var); | ||
243 | } | ||
244 | None | ||
245 | }) | ||
246 | } | ||
247 | |||
248 | pub(crate) fn happy_case(self) -> &'static str { | ||
249 | match self { | ||
250 | TryEnum::Result => "Ok", | ||
251 | TryEnum::Option => "Some", | ||
252 | } | ||
253 | } | ||
254 | |||
255 | pub(crate) fn sad_pattern(self) -> ast::Pat { | ||
256 | match self { | ||
257 | TryEnum::Result => make::tuple_struct_pat( | ||
258 | make::path_unqualified(make::path_segment(make::name_ref("Err"))), | ||
259 | iter::once(make::wildcard_pat().into()), | ||
260 | ) | ||
261 | .into(), | ||
262 | TryEnum::Option => make::ident_pat(make::name("None")).into(), | ||
263 | } | ||
264 | } | ||
265 | |||
266 | fn type_name(self) -> &'static str { | ||
267 | match self { | ||
268 | TryEnum::Result => "Result", | ||
269 | TryEnum::Option => "Option", | ||
270 | } | ||
271 | } | ||
272 | } | ||
273 | |||
274 | /// Helps with finding well-know things inside the standard library. This is | 159 | /// Helps with finding well-know things inside the standard library. This is |
275 | /// somewhat similar to the known paths infra inside hir, but it different; We | 160 | /// somewhat similar to the known paths infra inside hir, but it different; We |
276 | /// want to make sure that IDE specific paths don't become interesting inside | 161 | /// want to make sure that IDE specific paths don't become interesting inside |
277 | /// the compiler itself as well. | 162 | /// the compiler itself as well. |
278 | pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Crate); | 163 | pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Option<Crate>); |
279 | 164 | ||
280 | #[allow(non_snake_case)] | 165 | #[allow(non_snake_case)] |
281 | impl FamousDefs<'_, '_> { | 166 | impl FamousDefs<'_, '_> { |
@@ -362,6 +247,10 @@ pub mod prelude { | |||
362 | pub use prelude::*; | 247 | pub use prelude::*; |
363 | "#; | 248 | "#; |
364 | 249 | ||
250 | pub fn core(&self) -> Option<Crate> { | ||
251 | self.find_crate("core") | ||
252 | } | ||
253 | |||
365 | pub(crate) fn core_convert_From(&self) -> Option<Trait> { | 254 | pub(crate) fn core_convert_From(&self) -> Option<Trait> { |
366 | self.find_trait("core:convert:From") | 255 | self.find_trait("core:convert:From") |
367 | } | 256 | } |
@@ -399,21 +288,20 @@ pub use prelude::*; | |||
399 | } | 288 | } |
400 | } | 289 | } |
401 | 290 | ||
291 | fn find_crate(&self, name: &str) -> Option<Crate> { | ||
292 | let krate = self.1?; | ||
293 | let db = self.0.db; | ||
294 | let res = | ||
295 | krate.dependencies(db).into_iter().find(|dep| dep.name.to_string() == name)?.krate; | ||
296 | Some(res) | ||
297 | } | ||
298 | |||
402 | fn find_def(&self, path: &str) -> Option<ScopeDef> { | 299 | fn find_def(&self, path: &str) -> Option<ScopeDef> { |
403 | let db = self.0.db; | 300 | let db = self.0.db; |
404 | let mut path = path.split(':'); | 301 | let mut path = path.split(':'); |
405 | let trait_ = path.next_back()?; | 302 | let trait_ = path.next_back()?; |
406 | let std_crate = path.next()?; | 303 | let std_crate = path.next()?; |
407 | let std_crate = if self | 304 | let std_crate = self.find_crate(std_crate)?; |
408 | .1 | ||
409 | .declaration_name(db) | ||
410 | .map(|name| name.to_string() == std_crate) | ||
411 | .unwrap_or(false) | ||
412 | { | ||
413 | self.1 | ||
414 | } else { | ||
415 | self.1.dependencies(db).into_iter().find(|dep| dep.name.to_string() == std_crate)?.krate | ||
416 | }; | ||
417 | let mut module = std_crate.root_module(db); | 305 | let mut module = std_crate.root_module(db); |
418 | for segment in path { | 306 | for segment in path { |
419 | module = module.children(db).find_map(|child| { | 307 | module = module.children(db).find_map(|child| { |
diff --git a/crates/assists/src/utils/import_assets.rs b/crates/assists/src/utils/import_assets.rs index 601f51098..23db3a74b 100644 --- a/crates/assists/src/utils/import_assets.rs +++ b/crates/assists/src/utils/import_assets.rs | |||
@@ -1,6 +1,4 @@ | |||
1 | //! Look up accessible paths for items. | 1 | //! Look up accessible paths for items. |
2 | use std::collections::BTreeSet; | ||
3 | |||
4 | use either::Either; | 2 | use either::Either; |
5 | use hir::{AsAssocItem, AssocItemContainer, ModuleDef, Semantics}; | 3 | use hir::{AsAssocItem, AssocItemContainer, ModuleDef, Semantics}; |
6 | use ide_db::{imports_locator, RootDatabase}; | 4 | use ide_db::{imports_locator, RootDatabase}; |
@@ -29,12 +27,12 @@ pub(crate) enum ImportCandidate { | |||
29 | #[derive(Debug)] | 27 | #[derive(Debug)] |
30 | pub(crate) struct TraitImportCandidate { | 28 | pub(crate) struct TraitImportCandidate { |
31 | pub ty: hir::Type, | 29 | pub ty: hir::Type, |
32 | pub name: String, | 30 | pub name: ast::NameRef, |
33 | } | 31 | } |
34 | 32 | ||
35 | #[derive(Debug)] | 33 | #[derive(Debug)] |
36 | pub(crate) struct PathImportCandidate { | 34 | pub(crate) struct PathImportCandidate { |
37 | pub name: String, | 35 | pub name: ast::NameRef, |
38 | } | 36 | } |
39 | 37 | ||
40 | #[derive(Debug)] | 38 | #[derive(Debug)] |
@@ -86,9 +84,9 @@ impl ImportAssets { | |||
86 | fn get_search_query(&self) -> &str { | 84 | fn get_search_query(&self) -> &str { |
87 | match &self.import_candidate { | 85 | match &self.import_candidate { |
88 | ImportCandidate::UnqualifiedName(candidate) | 86 | ImportCandidate::UnqualifiedName(candidate) |
89 | | ImportCandidate::QualifierStart(candidate) => &candidate.name, | 87 | | ImportCandidate::QualifierStart(candidate) => candidate.name.text(), |
90 | ImportCandidate::TraitAssocItem(candidate) | 88 | ImportCandidate::TraitAssocItem(candidate) |
91 | | ImportCandidate::TraitMethod(candidate) => &candidate.name, | 89 | | ImportCandidate::TraitMethod(candidate) => candidate.name.text(), |
92 | } | 90 | } |
93 | } | 91 | } |
94 | 92 | ||
@@ -96,7 +94,7 @@ impl ImportAssets { | |||
96 | &self, | 94 | &self, |
97 | sema: &Semantics<RootDatabase>, | 95 | sema: &Semantics<RootDatabase>, |
98 | config: &InsertUseConfig, | 96 | config: &InsertUseConfig, |
99 | ) -> BTreeSet<hir::ModPath> { | 97 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { |
100 | let _p = profile::span("import_assists::search_for_imports"); | 98 | let _p = profile::span("import_assists::search_for_imports"); |
101 | self.search_for(sema, Some(config.prefix_kind)) | 99 | self.search_for(sema, Some(config.prefix_kind)) |
102 | } | 100 | } |
@@ -106,7 +104,7 @@ impl ImportAssets { | |||
106 | pub(crate) fn search_for_relative_paths( | 104 | pub(crate) fn search_for_relative_paths( |
107 | &self, | 105 | &self, |
108 | sema: &Semantics<RootDatabase>, | 106 | sema: &Semantics<RootDatabase>, |
109 | ) -> BTreeSet<hir::ModPath> { | 107 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { |
110 | let _p = profile::span("import_assists::search_for_relative_paths"); | 108 | let _p = profile::span("import_assists::search_for_relative_paths"); |
111 | self.search_for(sema, None) | 109 | self.search_for(sema, None) |
112 | } | 110 | } |
@@ -115,7 +113,7 @@ impl ImportAssets { | |||
115 | &self, | 113 | &self, |
116 | sema: &Semantics<RootDatabase>, | 114 | sema: &Semantics<RootDatabase>, |
117 | prefixed: Option<hir::PrefixKind>, | 115 | prefixed: Option<hir::PrefixKind>, |
118 | ) -> BTreeSet<hir::ModPath> { | 116 | ) -> Vec<(hir::ModPath, hir::ItemInNs)> { |
119 | let db = sema.db; | 117 | let db = sema.db; |
120 | let mut trait_candidates = FxHashSet::default(); | 118 | let mut trait_candidates = FxHashSet::default(); |
121 | let current_crate = self.module_with_name_to_import.krate(); | 119 | let current_crate = self.module_with_name_to_import.krate(); |
@@ -181,7 +179,7 @@ impl ImportAssets { | |||
181 | } | 179 | } |
182 | }; | 180 | }; |
183 | 181 | ||
184 | imports_locator::find_imports(sema, current_crate, &self.get_search_query()) | 182 | let mut res = imports_locator::find_imports(sema, current_crate, &self.get_search_query()) |
185 | .into_iter() | 183 | .into_iter() |
186 | .filter_map(filter) | 184 | .filter_map(filter) |
187 | .filter_map(|candidate| { | 185 | .filter_map(|candidate| { |
@@ -191,10 +189,13 @@ impl ImportAssets { | |||
191 | } else { | 189 | } else { |
192 | self.module_with_name_to_import.find_use_path(db, item) | 190 | self.module_with_name_to_import.find_use_path(db, item) |
193 | } | 191 | } |
192 | .map(|path| (path, item)) | ||
194 | }) | 193 | }) |
195 | .filter(|use_path| !use_path.segments.is_empty()) | 194 | .filter(|(use_path, _)| !use_path.segments.is_empty()) |
196 | .take(20) | 195 | .take(20) |
197 | .collect::<BTreeSet<_>>() | 196 | .collect::<Vec<_>>(); |
197 | res.sort_by_key(|(path, _)| path.clone()); | ||
198 | res | ||
198 | } | 199 | } |
199 | 200 | ||
200 | fn assoc_to_trait(assoc: AssocItemContainer) -> Option<hir::Trait> { | 201 | fn assoc_to_trait(assoc: AssocItemContainer) -> Option<hir::Trait> { |
@@ -215,7 +216,7 @@ impl ImportCandidate { | |||
215 | Some(_) => None, | 216 | Some(_) => None, |
216 | None => Some(Self::TraitMethod(TraitImportCandidate { | 217 | None => Some(Self::TraitMethod(TraitImportCandidate { |
217 | ty: sema.type_of_expr(&method_call.receiver()?)?, | 218 | ty: sema.type_of_expr(&method_call.receiver()?)?, |
218 | name: method_call.name_ref()?.syntax().to_string(), | 219 | name: method_call.name_ref()?, |
219 | })), | 220 | })), |
220 | } | 221 | } |
221 | } | 222 | } |
@@ -243,24 +244,17 @@ impl ImportCandidate { | |||
243 | hir::PathResolution::Def(hir::ModuleDef::Adt(assoc_item_path)) => { | 244 | hir::PathResolution::Def(hir::ModuleDef::Adt(assoc_item_path)) => { |
244 | ImportCandidate::TraitAssocItem(TraitImportCandidate { | 245 | ImportCandidate::TraitAssocItem(TraitImportCandidate { |
245 | ty: assoc_item_path.ty(sema.db), | 246 | ty: assoc_item_path.ty(sema.db), |
246 | name: segment.syntax().to_string(), | 247 | name: segment.name_ref()?, |
247 | }) | 248 | }) |
248 | } | 249 | } |
249 | _ => return None, | 250 | _ => return None, |
250 | } | 251 | } |
251 | } else { | 252 | } else { |
252 | ImportCandidate::QualifierStart(PathImportCandidate { | 253 | ImportCandidate::QualifierStart(PathImportCandidate { name: qualifier_start }) |
253 | name: qualifier_start.syntax().to_string(), | ||
254 | }) | ||
255 | } | 254 | } |
256 | } else { | 255 | } else { |
257 | ImportCandidate::UnqualifiedName(PathImportCandidate { | 256 | ImportCandidate::UnqualifiedName(PathImportCandidate { |
258 | name: segment | 257 | name: segment.syntax().descendants().find_map(ast::NameRef::cast)?, |
259 | .syntax() | ||
260 | .descendants() | ||
261 | .find_map(ast::NameRef::cast)? | ||
262 | .syntax() | ||
263 | .to_string(), | ||
264 | }) | 258 | }) |
265 | }; | 259 | }; |
266 | Some(candidate) | 260 | Some(candidate) |
diff --git a/crates/assists/src/utils/insert_use.rs b/crates/assists/src/utils/insert_use.rs index 409985b3b..033fbcedc 100644 --- a/crates/assists/src/utils/insert_use.rs +++ b/crates/assists/src/utils/insert_use.rs | |||
@@ -14,6 +14,7 @@ use syntax::{ | |||
14 | }, | 14 | }, |
15 | InsertPosition, SyntaxElement, SyntaxNode, | 15 | InsertPosition, SyntaxElement, SyntaxNode, |
16 | }; | 16 | }; |
17 | use test_utils::mark; | ||
17 | 18 | ||
18 | #[derive(Debug)] | 19 | #[derive(Debug)] |
19 | pub enum ImportScope { | 20 | pub enum ImportScope { |
@@ -109,6 +110,12 @@ pub(crate) fn insert_use( | |||
109 | // so look for the place we have to insert to | 110 | // so look for the place we have to insert to |
110 | let (insert_position, add_blank) = find_insert_position(scope, path); | 111 | let (insert_position, add_blank) = find_insert_position(scope, path); |
111 | 112 | ||
113 | let indent = if let ident_level @ 1..=usize::MAX = scope.indent_level().0 as usize { | ||
114 | Some(make::tokens::whitespace(&" ".repeat(4 * ident_level)).into()) | ||
115 | } else { | ||
116 | None | ||
117 | }; | ||
118 | |||
112 | let to_insert: Vec<SyntaxElement> = { | 119 | let to_insert: Vec<SyntaxElement> = { |
113 | let mut buf = Vec::new(); | 120 | let mut buf = Vec::new(); |
114 | 121 | ||
@@ -120,9 +127,13 @@ pub(crate) fn insert_use( | |||
120 | _ => (), | 127 | _ => (), |
121 | } | 128 | } |
122 | 129 | ||
123 | if let ident_level @ 1..=usize::MAX = scope.indent_level().0 as usize { | 130 | if add_blank.has_before() { |
124 | buf.push(make::tokens::whitespace(&" ".repeat(4 * ident_level)).into()); | 131 | if let Some(indent) = indent.clone() { |
132 | mark::hit!(insert_use_indent_before); | ||
133 | buf.push(indent); | ||
134 | } | ||
125 | } | 135 | } |
136 | |||
126 | buf.push(use_item.syntax().clone().into()); | 137 | buf.push(use_item.syntax().clone().into()); |
127 | 138 | ||
128 | match add_blank { | 139 | match add_blank { |
@@ -133,6 +144,16 @@ pub(crate) fn insert_use( | |||
133 | _ => (), | 144 | _ => (), |
134 | } | 145 | } |
135 | 146 | ||
147 | // only add indentation *after* our stuff if there's another node directly after it | ||
148 | if add_blank.has_after() && matches!(insert_position, InsertPosition::Before(_)) { | ||
149 | if let Some(indent) = indent { | ||
150 | mark::hit!(insert_use_indent_after); | ||
151 | buf.push(indent); | ||
152 | } | ||
153 | } else if add_blank.has_after() && matches!(insert_position, InsertPosition::After(_)) { | ||
154 | mark::hit!(insert_use_no_indent_after); | ||
155 | } | ||
156 | |||
136 | buf | 157 | buf |
137 | }; | 158 | }; |
138 | 159 | ||
@@ -470,6 +491,15 @@ enum AddBlankLine { | |||
470 | AfterTwice, | 491 | AfterTwice, |
471 | } | 492 | } |
472 | 493 | ||
494 | impl AddBlankLine { | ||
495 | fn has_before(&self) -> bool { | ||
496 | matches!(self, AddBlankLine::Before | AddBlankLine::BeforeTwice | AddBlankLine::Around) | ||
497 | } | ||
498 | fn has_after(&self) -> bool { | ||
499 | matches!(self, AddBlankLine::After | AddBlankLine::AfterTwice | AddBlankLine::Around) | ||
500 | } | ||
501 | } | ||
502 | |||
473 | fn find_insert_position( | 503 | fn find_insert_position( |
474 | scope: &ImportScope, | 504 | scope: &ImportScope, |
475 | insert_path: ast::Path, | 505 | insert_path: ast::Path, |
@@ -562,6 +592,21 @@ use std::bar::G;", | |||
562 | } | 592 | } |
563 | 593 | ||
564 | #[test] | 594 | #[test] |
595 | fn insert_start_indent() { | ||
596 | mark::check!(insert_use_indent_after); | ||
597 | check_none( | ||
598 | "std::bar::AA", | ||
599 | r" | ||
600 | use std::bar::B; | ||
601 | use std::bar::D;", | ||
602 | r" | ||
603 | use std::bar::AA; | ||
604 | use std::bar::B; | ||
605 | use std::bar::D;", | ||
606 | ) | ||
607 | } | ||
608 | |||
609 | #[test] | ||
565 | fn insert_middle() { | 610 | fn insert_middle() { |
566 | check_none( | 611 | check_none( |
567 | "std::bar::EE", | 612 | "std::bar::EE", |
@@ -580,6 +625,24 @@ use std::bar::G;", | |||
580 | } | 625 | } |
581 | 626 | ||
582 | #[test] | 627 | #[test] |
628 | fn insert_middle_indent() { | ||
629 | check_none( | ||
630 | "std::bar::EE", | ||
631 | r" | ||
632 | use std::bar::A; | ||
633 | use std::bar::D; | ||
634 | use std::bar::F; | ||
635 | use std::bar::G;", | ||
636 | r" | ||
637 | use std::bar::A; | ||
638 | use std::bar::D; | ||
639 | use std::bar::EE; | ||
640 | use std::bar::F; | ||
641 | use std::bar::G;", | ||
642 | ) | ||
643 | } | ||
644 | |||
645 | #[test] | ||
583 | fn insert_end() { | 646 | fn insert_end() { |
584 | check_none( | 647 | check_none( |
585 | "std::bar::ZZ", | 648 | "std::bar::ZZ", |
@@ -598,6 +661,25 @@ use std::bar::ZZ;", | |||
598 | } | 661 | } |
599 | 662 | ||
600 | #[test] | 663 | #[test] |
664 | fn insert_end_indent() { | ||
665 | mark::check!(insert_use_indent_before); | ||
666 | check_none( | ||
667 | "std::bar::ZZ", | ||
668 | r" | ||
669 | use std::bar::A; | ||
670 | use std::bar::D; | ||
671 | use std::bar::F; | ||
672 | use std::bar::G;", | ||
673 | r" | ||
674 | use std::bar::A; | ||
675 | use std::bar::D; | ||
676 | use std::bar::F; | ||
677 | use std::bar::G; | ||
678 | use std::bar::ZZ;", | ||
679 | ) | ||
680 | } | ||
681 | |||
682 | #[test] | ||
601 | fn insert_middle_nested() { | 683 | fn insert_middle_nested() { |
602 | check_none( | 684 | check_none( |
603 | "std::bar::EE", | 685 | "std::bar::EE", |
@@ -620,18 +702,18 @@ use std::bar::G;", | |||
620 | check_none( | 702 | check_none( |
621 | "foo::bar::GG", | 703 | "foo::bar::GG", |
622 | r" | 704 | r" |
623 | use std::bar::A; | 705 | use std::bar::A; |
624 | use std::bar::D; | 706 | use std::bar::D; |
625 | 707 | ||
626 | use foo::bar::F; | 708 | use foo::bar::F; |
627 | use foo::bar::H;", | 709 | use foo::bar::H;", |
628 | r" | 710 | r" |
629 | use std::bar::A; | 711 | use std::bar::A; |
630 | use std::bar::D; | 712 | use std::bar::D; |
631 | 713 | ||
632 | use foo::bar::F; | 714 | use foo::bar::F; |
633 | use foo::bar::GG; | 715 | use foo::bar::GG; |
634 | use foo::bar::H;", | 716 | use foo::bar::H;", |
635 | ) | 717 | ) |
636 | } | 718 | } |
637 | 719 | ||
@@ -640,22 +722,22 @@ use foo::bar::H;", | |||
640 | check_none( | 722 | check_none( |
641 | "foo::bar::GG", | 723 | "foo::bar::GG", |
642 | r" | 724 | r" |
643 | use foo::bar::A; | 725 | use foo::bar::A; |
644 | use foo::bar::D; | 726 | use foo::bar::D; |
645 | 727 | ||
646 | use std; | 728 | use std; |
647 | 729 | ||
648 | use foo::bar::F; | 730 | use foo::bar::F; |
649 | use foo::bar::H;", | 731 | use foo::bar::H;", |
650 | r" | 732 | r" |
651 | use foo::bar::A; | 733 | use foo::bar::A; |
652 | use foo::bar::D; | 734 | use foo::bar::D; |
653 | use foo::bar::GG; | 735 | use foo::bar::GG; |
654 | 736 | ||
655 | use std; | 737 | use std; |
656 | 738 | ||
657 | use foo::bar::F; | 739 | use foo::bar::F; |
658 | use foo::bar::H;", | 740 | use foo::bar::H;", |
659 | ) | 741 | ) |
660 | } | 742 | } |
661 | 743 | ||
@@ -664,13 +746,13 @@ use foo::bar::H;", | |||
664 | check_none( | 746 | check_none( |
665 | "std::fmt", | 747 | "std::fmt", |
666 | r" | 748 | r" |
667 | use foo::bar::A; | 749 | use foo::bar::A; |
668 | use foo::bar::D;", | 750 | use foo::bar::D;", |
669 | r" | 751 | r" |
670 | use std::fmt; | 752 | use std::fmt; |
671 | 753 | ||
672 | use foo::bar::A; | 754 | use foo::bar::A; |
673 | use foo::bar::D;", | 755 | use foo::bar::D;", |
674 | ) | 756 | ) |
675 | } | 757 | } |
676 | 758 | ||
@@ -714,6 +796,20 @@ fn main() {}", | |||
714 | } | 796 | } |
715 | 797 | ||
716 | #[test] | 798 | #[test] |
799 | fn insert_empty_module() { | ||
800 | mark::check!(insert_use_no_indent_after); | ||
801 | check( | ||
802 | "foo::bar", | ||
803 | "mod x {}", | ||
804 | r"{ | ||
805 | use foo::bar; | ||
806 | }", | ||
807 | None, | ||
808 | true, | ||
809 | ) | ||
810 | } | ||
811 | |||
812 | #[test] | ||
717 | fn insert_after_inner_attr() { | 813 | fn insert_after_inner_attr() { |
718 | check_full( | 814 | check_full( |
719 | "foo::bar", | 815 | "foo::bar", |
@@ -991,11 +1087,13 @@ use foo::bar::baz::Qux;", | |||
991 | ra_fixture_before: &str, | 1087 | ra_fixture_before: &str, |
992 | ra_fixture_after: &str, | 1088 | ra_fixture_after: &str, |
993 | mb: Option<MergeBehaviour>, | 1089 | mb: Option<MergeBehaviour>, |
1090 | module: bool, | ||
994 | ) { | 1091 | ) { |
995 | let file = super::ImportScope::from( | 1092 | let mut syntax = ast::SourceFile::parse(ra_fixture_before).tree().syntax().clone(); |
996 | ast::SourceFile::parse(ra_fixture_before).tree().syntax().clone(), | 1093 | if module { |
997 | ) | 1094 | syntax = syntax.descendants().find_map(ast::Module::cast).unwrap().syntax().clone(); |
998 | .unwrap(); | 1095 | } |
1096 | let file = super::ImportScope::from(syntax).unwrap(); | ||
999 | let path = ast::SourceFile::parse(&format!("use {};", path)) | 1097 | let path = ast::SourceFile::parse(&format!("use {};", path)) |
1000 | .tree() | 1098 | .tree() |
1001 | .syntax() | 1099 | .syntax() |
@@ -1008,15 +1106,15 @@ use foo::bar::baz::Qux;", | |||
1008 | } | 1106 | } |
1009 | 1107 | ||
1010 | fn check_full(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { | 1108 | fn check_full(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { |
1011 | check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Full)) | 1109 | check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Full), false) |
1012 | } | 1110 | } |
1013 | 1111 | ||
1014 | fn check_last(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { | 1112 | fn check_last(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { |
1015 | check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Last)) | 1113 | check(path, ra_fixture_before, ra_fixture_after, Some(MergeBehaviour::Last), false) |
1016 | } | 1114 | } |
1017 | 1115 | ||
1018 | fn check_none(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { | 1116 | fn check_none(path: &str, ra_fixture_before: &str, ra_fixture_after: &str) { |
1019 | check(path, ra_fixture_before, ra_fixture_after, None) | 1117 | check(path, ra_fixture_before, ra_fixture_after, None, false) |
1020 | } | 1118 | } |
1021 | 1119 | ||
1022 | fn check_merge_only_fail(ra_fixture0: &str, ra_fixture1: &str, mb: MergeBehaviour) { | 1120 | fn check_merge_only_fail(ra_fixture0: &str, ra_fixture1: &str, mb: MergeBehaviour) { |
diff --git a/crates/base_db/src/fixture.rs b/crates/base_db/src/fixture.rs index 72f1fd667..66e6443cb 100644 --- a/crates/base_db/src/fixture.rs +++ b/crates/base_db/src/fixture.rs | |||
@@ -158,7 +158,7 @@ impl ChangeFixture { | |||
158 | let crate_id = crate_graph.add_crate_root( | 158 | let crate_id = crate_graph.add_crate_root( |
159 | file_id, | 159 | file_id, |
160 | meta.edition, | 160 | meta.edition, |
161 | Some(crate_name.clone()), | 161 | Some(crate_name.clone().into()), |
162 | meta.cfg, | 162 | meta.cfg, |
163 | meta.env, | 163 | meta.env, |
164 | Default::default(), | 164 | Default::default(), |
@@ -187,7 +187,7 @@ impl ChangeFixture { | |||
187 | crate_graph.add_crate_root( | 187 | crate_graph.add_crate_root( |
188 | crate_root, | 188 | crate_root, |
189 | Edition::Edition2018, | 189 | Edition::Edition2018, |
190 | Some(CrateName::new("test").unwrap()), | 190 | Some(CrateName::new("test").unwrap().into()), |
191 | default_cfg, | 191 | default_cfg, |
192 | Env::default(), | 192 | Env::default(), |
193 | Default::default(), | 193 | Default::default(), |
diff --git a/crates/base_db/src/input.rs b/crates/base_db/src/input.rs index 215ac4b41..87f0a0ce5 100644 --- a/crates/base_db/src/input.rs +++ b/crates/base_db/src/input.rs | |||
@@ -102,11 +102,46 @@ impl fmt::Display for CrateName { | |||
102 | 102 | ||
103 | impl ops::Deref for CrateName { | 103 | impl ops::Deref for CrateName { |
104 | type Target = str; | 104 | type Target = str; |
105 | fn deref(&self) -> &Self::Target { | 105 | fn deref(&self) -> &str { |
106 | &*self.0 | 106 | &*self.0 |
107 | } | 107 | } |
108 | } | 108 | } |
109 | 109 | ||
110 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
111 | pub struct CrateDisplayName { | ||
112 | // The name we use to display various paths (with `_`). | ||
113 | crate_name: CrateName, | ||
114 | // The name as specified in Cargo.toml (with `-`). | ||
115 | canonical_name: String, | ||
116 | } | ||
117 | |||
118 | impl From<CrateName> for CrateDisplayName { | ||
119 | fn from(crate_name: CrateName) -> CrateDisplayName { | ||
120 | let canonical_name = crate_name.to_string(); | ||
121 | CrateDisplayName { crate_name, canonical_name } | ||
122 | } | ||
123 | } | ||
124 | |||
125 | impl fmt::Display for CrateDisplayName { | ||
126 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
127 | write!(f, "{}", self.crate_name) | ||
128 | } | ||
129 | } | ||
130 | |||
131 | impl ops::Deref for CrateDisplayName { | ||
132 | type Target = str; | ||
133 | fn deref(&self) -> &str { | ||
134 | &*self.crate_name | ||
135 | } | ||
136 | } | ||
137 | |||
138 | impl CrateDisplayName { | ||
139 | pub fn from_canonical_name(canonical_name: String) -> CrateDisplayName { | ||
140 | let crate_name = CrateName::normalize_dashes(&canonical_name); | ||
141 | CrateDisplayName { crate_name, canonical_name } | ||
142 | } | ||
143 | } | ||
144 | |||
110 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | 145 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] |
111 | pub struct ProcMacroId(pub u32); | 146 | pub struct ProcMacroId(pub u32); |
112 | 147 | ||
@@ -127,11 +162,13 @@ impl PartialEq for ProcMacro { | |||
127 | pub struct CrateData { | 162 | pub struct CrateData { |
128 | pub root_file_id: FileId, | 163 | pub root_file_id: FileId, |
129 | pub edition: Edition, | 164 | pub edition: Edition, |
130 | /// A name used in the package's project declaration: for Cargo projects, it's [package].name, | 165 | /// A name used in the package's project declaration: for Cargo projects, |
131 | /// can be different for other project types or even absent (a dummy crate for the code snippet, for example). | 166 | /// it's [package].name, can be different for other project types or even |
132 | /// NOTE: The crate can be referenced as a dependency under a different name, | 167 | /// absent (a dummy crate for the code snippet, for example). |
133 | /// this one should be used when working with crate hierarchies. | 168 | /// |
134 | pub declaration_name: Option<CrateName>, | 169 | /// For purposes of analysis, crates are anonymous (only names in |
170 | /// `Dependency` matters), this name should only be used for UI. | ||
171 | pub display_name: Option<CrateDisplayName>, | ||
135 | pub cfg_options: CfgOptions, | 172 | pub cfg_options: CfgOptions, |
136 | pub env: Env, | 173 | pub env: Env, |
137 | pub dependencies: Vec<Dependency>, | 174 | pub dependencies: Vec<Dependency>, |
@@ -160,7 +197,7 @@ impl CrateGraph { | |||
160 | &mut self, | 197 | &mut self, |
161 | file_id: FileId, | 198 | file_id: FileId, |
162 | edition: Edition, | 199 | edition: Edition, |
163 | declaration_name: Option<CrateName>, | 200 | display_name: Option<CrateDisplayName>, |
164 | cfg_options: CfgOptions, | 201 | cfg_options: CfgOptions, |
165 | env: Env, | 202 | env: Env, |
166 | proc_macro: Vec<(SmolStr, Arc<dyn tt::TokenExpander>)>, | 203 | proc_macro: Vec<(SmolStr, Arc<dyn tt::TokenExpander>)>, |
@@ -171,7 +208,7 @@ impl CrateGraph { | |||
171 | let data = CrateData { | 208 | let data = CrateData { |
172 | root_file_id: file_id, | 209 | root_file_id: file_id, |
173 | edition, | 210 | edition, |
174 | declaration_name, | 211 | display_name, |
175 | cfg_options, | 212 | cfg_options, |
176 | env, | 213 | env, |
177 | proc_macro, | 214 | proc_macro, |
@@ -290,6 +327,29 @@ impl CrateGraph { | |||
290 | } | 327 | } |
291 | false | 328 | false |
292 | } | 329 | } |
330 | |||
331 | // Work around for https://github.com/rust-analyzer/rust-analyzer/issues/6038. | ||
332 | // As hacky as it gets. | ||
333 | pub fn patch_cfg_if(&mut self) -> bool { | ||
334 | let cfg_if = self.hacky_find_crate("cfg_if"); | ||
335 | let std = self.hacky_find_crate("std"); | ||
336 | match (cfg_if, std) { | ||
337 | (Some(cfg_if), Some(std)) => { | ||
338 | self.arena.get_mut(&cfg_if).unwrap().dependencies.clear(); | ||
339 | self.arena | ||
340 | .get_mut(&std) | ||
341 | .unwrap() | ||
342 | .dependencies | ||
343 | .push(Dependency { crate_id: cfg_if, name: CrateName::new("cfg_if").unwrap() }); | ||
344 | true | ||
345 | } | ||
346 | _ => false, | ||
347 | } | ||
348 | } | ||
349 | |||
350 | fn hacky_find_crate(&self, display_name: &str) -> Option<CrateId> { | ||
351 | self.iter().find(|it| self[*it].display_name.as_deref() == Some(display_name)) | ||
352 | } | ||
293 | } | 353 | } |
294 | 354 | ||
295 | impl ops::Index<CrateId> for CrateGraph { | 355 | impl ops::Index<CrateId> for CrateGraph { |
diff --git a/crates/base_db/src/lib.rs b/crates/base_db/src/lib.rs index e38aa7257..0804202d6 100644 --- a/crates/base_db/src/lib.rs +++ b/crates/base_db/src/lib.rs | |||
@@ -13,8 +13,8 @@ pub use crate::{ | |||
13 | cancellation::Canceled, | 13 | cancellation::Canceled, |
14 | change::Change, | 14 | change::Change, |
15 | input::{ | 15 | input::{ |
16 | CrateData, CrateGraph, CrateId, CrateName, Dependency, Edition, Env, FileId, ProcMacroId, | 16 | CrateData, CrateDisplayName, CrateGraph, CrateId, CrateName, Dependency, Edition, Env, |
17 | SourceRoot, SourceRootId, | 17 | FileId, ProcMacroId, SourceRoot, SourceRootId, |
18 | }, | 18 | }, |
19 | }; | 19 | }; |
20 | pub use salsa; | 20 | pub use salsa; |
diff --git a/crates/cfg/Cargo.toml b/crates/cfg/Cargo.toml index a6785ee8e..c68e391c1 100644 --- a/crates/cfg/Cargo.toml +++ b/crates/cfg/Cargo.toml | |||
@@ -17,3 +17,4 @@ tt = { path = "../tt", version = "0.0.0" } | |||
17 | [dev-dependencies] | 17 | [dev-dependencies] |
18 | mbe = { path = "../mbe" } | 18 | mbe = { path = "../mbe" } |
19 | syntax = { path = "../syntax" } | 19 | syntax = { path = "../syntax" } |
20 | expect-test = "1.0" | ||
diff --git a/crates/cfg/src/cfg_expr.rs b/crates/cfg/src/cfg_expr.rs index 336fe25bc..42327f1e1 100644 --- a/crates/cfg/src/cfg_expr.rs +++ b/crates/cfg/src/cfg_expr.rs | |||
@@ -2,30 +2,77 @@ | |||
2 | //! | 2 | //! |
3 | //! See: https://doc.rust-lang.org/reference/conditional-compilation.html#conditional-compilation | 3 | //! See: https://doc.rust-lang.org/reference/conditional-compilation.html#conditional-compilation |
4 | 4 | ||
5 | use std::slice::Iter as SliceIter; | 5 | use std::{fmt, slice::Iter as SliceIter}; |
6 | 6 | ||
7 | use tt::SmolStr; | 7 | use tt::SmolStr; |
8 | 8 | ||
9 | /// A simple configuration value passed in from the outside. | ||
10 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] | ||
11 | pub enum CfgAtom { | ||
12 | /// eg. `#[cfg(test)]` | ||
13 | Flag(SmolStr), | ||
14 | /// eg. `#[cfg(target_os = "linux")]` | ||
15 | /// | ||
16 | /// Note that a key can have multiple values that are all considered "active" at the same time. | ||
17 | /// For example, `#[cfg(target_feature = "sse")]` and `#[cfg(target_feature = "sse2")]`. | ||
18 | KeyValue { key: SmolStr, value: SmolStr }, | ||
19 | } | ||
20 | |||
21 | impl CfgAtom { | ||
22 | /// Returns `true` when the atom comes from the target specification. | ||
23 | /// | ||
24 | /// If this returns `true`, then changing this atom requires changing the compilation target. If | ||
25 | /// it returns `false`, the atom might come from a build script or the build system. | ||
26 | pub fn is_target_defined(&self) -> bool { | ||
27 | match self { | ||
28 | CfgAtom::Flag(flag) => matches!(&**flag, "unix" | "windows"), | ||
29 | CfgAtom::KeyValue { key, value: _ } => matches!( | ||
30 | &**key, | ||
31 | "target_arch" | ||
32 | | "target_os" | ||
33 | | "target_env" | ||
34 | | "target_family" | ||
35 | | "target_endian" | ||
36 | | "target_pointer_width" | ||
37 | | "target_vendor" // NOTE: `target_feature` is left out since it can be configured via `-Ctarget-feature` | ||
38 | ), | ||
39 | } | ||
40 | } | ||
41 | } | ||
42 | |||
43 | impl fmt::Display for CfgAtom { | ||
44 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
45 | match self { | ||
46 | CfgAtom::Flag(name) => write!(f, "{}", name), | ||
47 | CfgAtom::KeyValue { key, value } => write!(f, "{} = {:?}", key, value), | ||
48 | } | ||
49 | } | ||
50 | } | ||
51 | |||
9 | #[derive(Debug, Clone, PartialEq, Eq)] | 52 | #[derive(Debug, Clone, PartialEq, Eq)] |
10 | pub enum CfgExpr { | 53 | pub enum CfgExpr { |
11 | Invalid, | 54 | Invalid, |
12 | Atom(SmolStr), | 55 | Atom(CfgAtom), |
13 | KeyValue { key: SmolStr, value: SmolStr }, | ||
14 | All(Vec<CfgExpr>), | 56 | All(Vec<CfgExpr>), |
15 | Any(Vec<CfgExpr>), | 57 | Any(Vec<CfgExpr>), |
16 | Not(Box<CfgExpr>), | 58 | Not(Box<CfgExpr>), |
17 | } | 59 | } |
18 | 60 | ||
61 | impl From<CfgAtom> for CfgExpr { | ||
62 | fn from(atom: CfgAtom) -> Self { | ||
63 | CfgExpr::Atom(atom) | ||
64 | } | ||
65 | } | ||
66 | |||
19 | impl CfgExpr { | 67 | impl CfgExpr { |
20 | pub fn parse(tt: &tt::Subtree) -> CfgExpr { | 68 | pub fn parse(tt: &tt::Subtree) -> CfgExpr { |
21 | next_cfg_expr(&mut tt.token_trees.iter()).unwrap_or(CfgExpr::Invalid) | 69 | next_cfg_expr(&mut tt.token_trees.iter()).unwrap_or(CfgExpr::Invalid) |
22 | } | 70 | } |
23 | /// Fold the cfg by querying all basic `Atom` and `KeyValue` predicates. | 71 | /// Fold the cfg by querying all basic `Atom` and `KeyValue` predicates. |
24 | pub fn fold(&self, query: &dyn Fn(&SmolStr, Option<&SmolStr>) -> bool) -> Option<bool> { | 72 | pub fn fold(&self, query: &dyn Fn(&CfgAtom) -> bool) -> Option<bool> { |
25 | match self { | 73 | match self { |
26 | CfgExpr::Invalid => None, | 74 | CfgExpr::Invalid => None, |
27 | CfgExpr::Atom(name) => Some(query(name, None)), | 75 | CfgExpr::Atom(atom) => Some(query(atom)), |
28 | CfgExpr::KeyValue { key, value } => Some(query(key, Some(value))), | ||
29 | CfgExpr::All(preds) => { | 76 | CfgExpr::All(preds) => { |
30 | preds.iter().try_fold(true, |s, pred| Some(s && pred.fold(query)?)) | 77 | preds.iter().try_fold(true, |s, pred| Some(s && pred.fold(query)?)) |
31 | } | 78 | } |
@@ -54,7 +101,7 @@ fn next_cfg_expr(it: &mut SliceIter<tt::TokenTree>) -> Option<CfgExpr> { | |||
54 | // FIXME: escape? raw string? | 101 | // FIXME: escape? raw string? |
55 | let value = | 102 | let value = |
56 | SmolStr::new(literal.text.trim_start_matches('"').trim_end_matches('"')); | 103 | SmolStr::new(literal.text.trim_start_matches('"').trim_end_matches('"')); |
57 | CfgExpr::KeyValue { key: name, value } | 104 | CfgAtom::KeyValue { key: name, value }.into() |
58 | } | 105 | } |
59 | _ => return Some(CfgExpr::Invalid), | 106 | _ => return Some(CfgExpr::Invalid), |
60 | } | 107 | } |
@@ -70,7 +117,7 @@ fn next_cfg_expr(it: &mut SliceIter<tt::TokenTree>) -> Option<CfgExpr> { | |||
70 | _ => CfgExpr::Invalid, | 117 | _ => CfgExpr::Invalid, |
71 | } | 118 | } |
72 | } | 119 | } |
73 | _ => CfgExpr::Atom(name), | 120 | _ => CfgAtom::Flag(name).into(), |
74 | }; | 121 | }; |
75 | 122 | ||
76 | // Eat comma separator | 123 | // Eat comma separator |
@@ -81,53 +128,3 @@ fn next_cfg_expr(it: &mut SliceIter<tt::TokenTree>) -> Option<CfgExpr> { | |||
81 | } | 128 | } |
82 | Some(ret) | 129 | Some(ret) |
83 | } | 130 | } |
84 | |||
85 | #[cfg(test)] | ||
86 | mod tests { | ||
87 | use super::*; | ||
88 | |||
89 | use mbe::ast_to_token_tree; | ||
90 | use syntax::ast::{self, AstNode}; | ||
91 | |||
92 | fn assert_parse_result(input: &str, expected: CfgExpr) { | ||
93 | let (tt, _) = { | ||
94 | let source_file = ast::SourceFile::parse(input).ok().unwrap(); | ||
95 | let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); | ||
96 | ast_to_token_tree(&tt).unwrap() | ||
97 | }; | ||
98 | let cfg = CfgExpr::parse(&tt); | ||
99 | assert_eq!(cfg, expected); | ||
100 | } | ||
101 | |||
102 | #[test] | ||
103 | fn test_cfg_expr_parser() { | ||
104 | assert_parse_result("#![cfg(foo)]", CfgExpr::Atom("foo".into())); | ||
105 | assert_parse_result("#![cfg(foo,)]", CfgExpr::Atom("foo".into())); | ||
106 | assert_parse_result( | ||
107 | "#![cfg(not(foo))]", | ||
108 | CfgExpr::Not(Box::new(CfgExpr::Atom("foo".into()))), | ||
109 | ); | ||
110 | assert_parse_result("#![cfg(foo(bar))]", CfgExpr::Invalid); | ||
111 | |||
112 | // Only take the first | ||
113 | assert_parse_result(r#"#![cfg(foo, bar = "baz")]"#, CfgExpr::Atom("foo".into())); | ||
114 | |||
115 | assert_parse_result( | ||
116 | r#"#![cfg(all(foo, bar = "baz"))]"#, | ||
117 | CfgExpr::All(vec![ | ||
118 | CfgExpr::Atom("foo".into()), | ||
119 | CfgExpr::KeyValue { key: "bar".into(), value: "baz".into() }, | ||
120 | ]), | ||
121 | ); | ||
122 | |||
123 | assert_parse_result( | ||
124 | r#"#![cfg(any(not(), all(), , bar = "baz",))]"#, | ||
125 | CfgExpr::Any(vec![ | ||
126 | CfgExpr::Not(Box::new(CfgExpr::Invalid)), | ||
127 | CfgExpr::All(vec![]), | ||
128 | CfgExpr::Invalid, | ||
129 | CfgExpr::KeyValue { key: "bar".into(), value: "baz".into() }, | ||
130 | ]), | ||
131 | ); | ||
132 | } | ||
133 | } | ||
diff --git a/crates/cfg/src/dnf.rs b/crates/cfg/src/dnf.rs new file mode 100644 index 000000000..580c9a9a2 --- /dev/null +++ b/crates/cfg/src/dnf.rs | |||
@@ -0,0 +1,320 @@ | |||
1 | //! Disjunctive Normal Form construction. | ||
2 | //! | ||
3 | //! Algorithm from <https://www.cs.drexel.edu/~jjohnson/2015-16/fall/CS270/Lectures/3/dnf.pdf>, | ||
4 | //! which would have been much easier to read if it used pattern matching. It's also missing the | ||
5 | //! entire "distribute ANDs over ORs" part, which is not trivial. Oh well. | ||
6 | //! | ||
7 | //! This is currently both messy and inefficient. Feel free to improve, there are unit tests. | ||
8 | |||
9 | use std::fmt; | ||
10 | |||
11 | use rustc_hash::FxHashSet; | ||
12 | |||
13 | use crate::{CfgAtom, CfgDiff, CfgExpr, CfgOptions, InactiveReason}; | ||
14 | |||
15 | /// A `#[cfg]` directive in Disjunctive Normal Form (DNF). | ||
16 | pub struct DnfExpr { | ||
17 | conjunctions: Vec<Conjunction>, | ||
18 | } | ||
19 | |||
20 | struct Conjunction { | ||
21 | literals: Vec<Literal>, | ||
22 | } | ||
23 | |||
24 | struct Literal { | ||
25 | negate: bool, | ||
26 | var: Option<CfgAtom>, // None = Invalid | ||
27 | } | ||
28 | |||
29 | impl DnfExpr { | ||
30 | pub fn new(expr: CfgExpr) -> Self { | ||
31 | let builder = Builder { expr: DnfExpr { conjunctions: Vec::new() } }; | ||
32 | |||
33 | builder.lower(expr.clone()) | ||
34 | } | ||
35 | |||
36 | /// Computes a list of present or absent atoms in `opts` that cause this expression to evaluate | ||
37 | /// to `false`. | ||
38 | /// | ||
39 | /// Note that flipping a subset of these atoms might be sufficient to make the whole expression | ||
40 | /// evaluate to `true`. For that, see `compute_enable_hints`. | ||
41 | /// | ||
42 | /// Returns `None` when `self` is already true, or contains errors. | ||
43 | pub fn why_inactive(&self, opts: &CfgOptions) -> Option<InactiveReason> { | ||
44 | let mut res = InactiveReason { enabled: Vec::new(), disabled: Vec::new() }; | ||
45 | |||
46 | for conj in &self.conjunctions { | ||
47 | let mut conj_is_true = true; | ||
48 | for lit in &conj.literals { | ||
49 | let atom = lit.var.as_ref()?; | ||
50 | let enabled = opts.enabled.contains(atom); | ||
51 | if lit.negate == enabled { | ||
52 | // Literal is false, but needs to be true for this conjunction. | ||
53 | conj_is_true = false; | ||
54 | |||
55 | if enabled { | ||
56 | res.enabled.push(atom.clone()); | ||
57 | } else { | ||
58 | res.disabled.push(atom.clone()); | ||
59 | } | ||
60 | } | ||
61 | } | ||
62 | |||
63 | if conj_is_true { | ||
64 | // This expression is not actually inactive. | ||
65 | return None; | ||
66 | } | ||
67 | } | ||
68 | |||
69 | res.enabled.sort_unstable(); | ||
70 | res.enabled.dedup(); | ||
71 | res.disabled.sort_unstable(); | ||
72 | res.disabled.dedup(); | ||
73 | Some(res) | ||
74 | } | ||
75 | |||
76 | /// Returns `CfgDiff` objects that would enable this directive if applied to `opts`. | ||
77 | pub fn compute_enable_hints<'a>( | ||
78 | &'a self, | ||
79 | opts: &'a CfgOptions, | ||
80 | ) -> impl Iterator<Item = CfgDiff> + 'a { | ||
81 | // A cfg is enabled if any of `self.conjunctions` evaluate to `true`. | ||
82 | |||
83 | self.conjunctions.iter().filter_map(move |conj| { | ||
84 | let mut enable = FxHashSet::default(); | ||
85 | let mut disable = FxHashSet::default(); | ||
86 | for lit in &conj.literals { | ||
87 | let atom = lit.var.as_ref()?; | ||
88 | let enabled = opts.enabled.contains(atom); | ||
89 | if lit.negate && enabled { | ||
90 | disable.insert(atom.clone()); | ||
91 | } | ||
92 | if !lit.negate && !enabled { | ||
93 | enable.insert(atom.clone()); | ||
94 | } | ||
95 | } | ||
96 | |||
97 | // Check that this actually makes `conj` true. | ||
98 | for lit in &conj.literals { | ||
99 | let atom = lit.var.as_ref()?; | ||
100 | let enabled = enable.contains(atom) | ||
101 | || (opts.enabled.contains(atom) && !disable.contains(atom)); | ||
102 | if enabled == lit.negate { | ||
103 | return None; | ||
104 | } | ||
105 | } | ||
106 | |||
107 | if enable.is_empty() && disable.is_empty() { | ||
108 | return None; | ||
109 | } | ||
110 | |||
111 | let mut diff = CfgDiff { | ||
112 | enable: enable.into_iter().collect(), | ||
113 | disable: disable.into_iter().collect(), | ||
114 | }; | ||
115 | |||
116 | // Undo the FxHashMap randomization for consistent output. | ||
117 | diff.enable.sort_unstable(); | ||
118 | diff.disable.sort_unstable(); | ||
119 | |||
120 | Some(diff) | ||
121 | }) | ||
122 | } | ||
123 | } | ||
124 | |||
125 | impl fmt::Display for DnfExpr { | ||
126 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
127 | if self.conjunctions.len() != 1 { | ||
128 | write!(f, "any(")?; | ||
129 | } | ||
130 | for (i, conj) in self.conjunctions.iter().enumerate() { | ||
131 | if i != 0 { | ||
132 | f.write_str(", ")?; | ||
133 | } | ||
134 | |||
135 | write!(f, "{}", conj)?; | ||
136 | } | ||
137 | if self.conjunctions.len() != 1 { | ||
138 | write!(f, ")")?; | ||
139 | } | ||
140 | |||
141 | Ok(()) | ||
142 | } | ||
143 | } | ||
144 | |||
145 | impl Conjunction { | ||
146 | fn new(parts: Vec<CfgExpr>) -> Self { | ||
147 | let mut literals = Vec::new(); | ||
148 | for part in parts { | ||
149 | match part { | ||
150 | CfgExpr::Invalid | CfgExpr::Atom(_) | CfgExpr::Not(_) => { | ||
151 | literals.push(Literal::new(part)); | ||
152 | } | ||
153 | CfgExpr::All(conj) => { | ||
154 | // Flatten. | ||
155 | literals.extend(Conjunction::new(conj).literals); | ||
156 | } | ||
157 | CfgExpr::Any(_) => unreachable!("disjunction in conjunction"), | ||
158 | } | ||
159 | } | ||
160 | |||
161 | Self { literals } | ||
162 | } | ||
163 | } | ||
164 | |||
165 | impl fmt::Display for Conjunction { | ||
166 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
167 | if self.literals.len() != 1 { | ||
168 | write!(f, "all(")?; | ||
169 | } | ||
170 | for (i, lit) in self.literals.iter().enumerate() { | ||
171 | if i != 0 { | ||
172 | f.write_str(", ")?; | ||
173 | } | ||
174 | |||
175 | write!(f, "{}", lit)?; | ||
176 | } | ||
177 | if self.literals.len() != 1 { | ||
178 | write!(f, ")")?; | ||
179 | } | ||
180 | |||
181 | Ok(()) | ||
182 | } | ||
183 | } | ||
184 | |||
185 | impl Literal { | ||
186 | fn new(expr: CfgExpr) -> Self { | ||
187 | match expr { | ||
188 | CfgExpr::Invalid => Self { negate: false, var: None }, | ||
189 | CfgExpr::Atom(atom) => Self { negate: false, var: Some(atom) }, | ||
190 | CfgExpr::Not(expr) => match *expr { | ||
191 | CfgExpr::Invalid => Self { negate: true, var: None }, | ||
192 | CfgExpr::Atom(atom) => Self { negate: true, var: Some(atom) }, | ||
193 | _ => unreachable!("non-atom {:?}", expr), | ||
194 | }, | ||
195 | CfgExpr::Any(_) | CfgExpr::All(_) => unreachable!("non-literal {:?}", expr), | ||
196 | } | ||
197 | } | ||
198 | } | ||
199 | |||
200 | impl fmt::Display for Literal { | ||
201 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
202 | if self.negate { | ||
203 | write!(f, "not(")?; | ||
204 | } | ||
205 | |||
206 | match &self.var { | ||
207 | Some(var) => write!(f, "{}", var)?, | ||
208 | None => f.write_str("<invalid>")?, | ||
209 | } | ||
210 | |||
211 | if self.negate { | ||
212 | write!(f, ")")?; | ||
213 | } | ||
214 | |||
215 | Ok(()) | ||
216 | } | ||
217 | } | ||
218 | |||
219 | struct Builder { | ||
220 | expr: DnfExpr, | ||
221 | } | ||
222 | |||
223 | impl Builder { | ||
224 | fn lower(mut self, expr: CfgExpr) -> DnfExpr { | ||
225 | let expr = make_nnf(expr); | ||
226 | let expr = make_dnf(expr); | ||
227 | |||
228 | match expr { | ||
229 | CfgExpr::Invalid | CfgExpr::Atom(_) | CfgExpr::Not(_) => { | ||
230 | self.expr.conjunctions.push(Conjunction::new(vec![expr])); | ||
231 | } | ||
232 | CfgExpr::All(conj) => { | ||
233 | self.expr.conjunctions.push(Conjunction::new(conj)); | ||
234 | } | ||
235 | CfgExpr::Any(mut disj) => { | ||
236 | disj.reverse(); | ||
237 | while let Some(conj) = disj.pop() { | ||
238 | match conj { | ||
239 | CfgExpr::Invalid | CfgExpr::Atom(_) | CfgExpr::All(_) | CfgExpr::Not(_) => { | ||
240 | self.expr.conjunctions.push(Conjunction::new(vec![conj])); | ||
241 | } | ||
242 | CfgExpr::Any(inner_disj) => { | ||
243 | // Flatten. | ||
244 | disj.extend(inner_disj.into_iter().rev()); | ||
245 | } | ||
246 | } | ||
247 | } | ||
248 | } | ||
249 | } | ||
250 | |||
251 | self.expr | ||
252 | } | ||
253 | } | ||
254 | |||
255 | fn make_dnf(expr: CfgExpr) -> CfgExpr { | ||
256 | match expr { | ||
257 | CfgExpr::Invalid | CfgExpr::Atom(_) | CfgExpr::Not(_) => expr, | ||
258 | CfgExpr::Any(e) => CfgExpr::Any(e.into_iter().map(|expr| make_dnf(expr)).collect()), | ||
259 | CfgExpr::All(e) => { | ||
260 | let e = e.into_iter().map(|expr| make_nnf(expr)).collect::<Vec<_>>(); | ||
261 | |||
262 | CfgExpr::Any(distribute_conj(&e)) | ||
263 | } | ||
264 | } | ||
265 | } | ||
266 | |||
267 | /// Turns a conjunction of expressions into a disjunction of expressions. | ||
268 | fn distribute_conj(conj: &[CfgExpr]) -> Vec<CfgExpr> { | ||
269 | fn go(out: &mut Vec<CfgExpr>, with: &mut Vec<CfgExpr>, rest: &[CfgExpr]) { | ||
270 | match rest { | ||
271 | [head, tail @ ..] => match head { | ||
272 | CfgExpr::Any(disj) => { | ||
273 | for part in disj { | ||
274 | with.push(part.clone()); | ||
275 | go(out, with, tail); | ||
276 | with.pop(); | ||
277 | } | ||
278 | } | ||
279 | _ => { | ||
280 | with.push(head.clone()); | ||
281 | go(out, with, tail); | ||
282 | with.pop(); | ||
283 | } | ||
284 | }, | ||
285 | _ => { | ||
286 | // Turn accumulated parts into a new conjunction. | ||
287 | out.push(CfgExpr::All(with.clone())); | ||
288 | } | ||
289 | } | ||
290 | } | ||
291 | |||
292 | let mut out = Vec::new(); | ||
293 | let mut with = Vec::new(); | ||
294 | |||
295 | go(&mut out, &mut with, conj); | ||
296 | |||
297 | out | ||
298 | } | ||
299 | |||
300 | fn make_nnf(expr: CfgExpr) -> CfgExpr { | ||
301 | match expr { | ||
302 | CfgExpr::Invalid | CfgExpr::Atom(_) => expr, | ||
303 | CfgExpr::Any(expr) => CfgExpr::Any(expr.into_iter().map(|expr| make_nnf(expr)).collect()), | ||
304 | CfgExpr::All(expr) => CfgExpr::All(expr.into_iter().map(|expr| make_nnf(expr)).collect()), | ||
305 | CfgExpr::Not(operand) => match *operand { | ||
306 | CfgExpr::Invalid | CfgExpr::Atom(_) => CfgExpr::Not(operand.clone()), // Original negated expr | ||
307 | CfgExpr::Not(expr) => { | ||
308 | // Remove double negation. | ||
309 | make_nnf(*expr) | ||
310 | } | ||
311 | // Convert negated conjunction/disjunction using DeMorgan's Law. | ||
312 | CfgExpr::Any(inner) => CfgExpr::All( | ||
313 | inner.into_iter().map(|expr| make_nnf(CfgExpr::Not(Box::new(expr)))).collect(), | ||
314 | ), | ||
315 | CfgExpr::All(inner) => CfgExpr::Any( | ||
316 | inner.into_iter().map(|expr| make_nnf(CfgExpr::Not(Box::new(expr)))).collect(), | ||
317 | ), | ||
318 | }, | ||
319 | } | ||
320 | } | ||
diff --git a/crates/cfg/src/lib.rs b/crates/cfg/src/lib.rs index a9d50e698..d0e08cf5f 100644 --- a/crates/cfg/src/lib.rs +++ b/crates/cfg/src/lib.rs | |||
@@ -1,11 +1,17 @@ | |||
1 | //! cfg defines conditional compiling options, `cfg` attibute parser and evaluator | 1 | //! cfg defines conditional compiling options, `cfg` attibute parser and evaluator |
2 | 2 | ||
3 | mod cfg_expr; | 3 | mod cfg_expr; |
4 | mod dnf; | ||
5 | #[cfg(test)] | ||
6 | mod tests; | ||
7 | |||
8 | use std::fmt; | ||
4 | 9 | ||
5 | use rustc_hash::FxHashSet; | 10 | use rustc_hash::FxHashSet; |
6 | use tt::SmolStr; | 11 | use tt::SmolStr; |
7 | 12 | ||
8 | pub use cfg_expr::CfgExpr; | 13 | pub use cfg_expr::{CfgAtom, CfgExpr}; |
14 | pub use dnf::DnfExpr; | ||
9 | 15 | ||
10 | /// Configuration options used for conditional compilition on items with `cfg` attributes. | 16 | /// Configuration options used for conditional compilition on items with `cfg` attributes. |
11 | /// We have two kind of options in different namespaces: atomic options like `unix`, and | 17 | /// We have two kind of options in different namespaces: atomic options like `unix`, and |
@@ -19,33 +25,131 @@ pub use cfg_expr::CfgExpr; | |||
19 | /// See: https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options | 25 | /// See: https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options |
20 | #[derive(Debug, Clone, PartialEq, Eq, Default)] | 26 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
21 | pub struct CfgOptions { | 27 | pub struct CfgOptions { |
22 | atoms: FxHashSet<SmolStr>, | 28 | enabled: FxHashSet<CfgAtom>, |
23 | key_values: FxHashSet<(SmolStr, SmolStr)>, | ||
24 | } | 29 | } |
25 | 30 | ||
26 | impl CfgOptions { | 31 | impl CfgOptions { |
27 | pub fn check(&self, cfg: &CfgExpr) -> Option<bool> { | 32 | pub fn check(&self, cfg: &CfgExpr) -> Option<bool> { |
28 | cfg.fold(&|key, value| match value { | 33 | cfg.fold(&|atom| self.enabled.contains(atom)) |
29 | None => self.atoms.contains(key), | ||
30 | Some(value) => self.key_values.contains(&(key.clone(), value.clone())), | ||
31 | }) | ||
32 | } | 34 | } |
33 | 35 | ||
34 | pub fn insert_atom(&mut self, key: SmolStr) { | 36 | pub fn insert_atom(&mut self, key: SmolStr) { |
35 | self.atoms.insert(key); | 37 | self.enabled.insert(CfgAtom::Flag(key)); |
36 | } | 38 | } |
37 | 39 | ||
38 | pub fn insert_key_value(&mut self, key: SmolStr, value: SmolStr) { | 40 | pub fn insert_key_value(&mut self, key: SmolStr, value: SmolStr) { |
39 | self.key_values.insert((key, value)); | 41 | self.enabled.insert(CfgAtom::KeyValue { key, value }); |
40 | } | 42 | } |
41 | 43 | ||
42 | pub fn append(&mut self, other: &CfgOptions) { | 44 | pub fn append(&mut self, other: &CfgOptions) { |
43 | for atom in &other.atoms { | 45 | for atom in &other.enabled { |
44 | self.atoms.insert(atom.clone()); | 46 | self.enabled.insert(atom.clone()); |
47 | } | ||
48 | } | ||
49 | |||
50 | pub fn apply_diff(&mut self, diff: CfgDiff) { | ||
51 | for atom in diff.enable { | ||
52 | self.enabled.insert(atom); | ||
45 | } | 53 | } |
46 | 54 | ||
47 | for (key, value) in &other.key_values { | 55 | for atom in diff.disable { |
48 | self.key_values.insert((key.clone(), value.clone())); | 56 | self.enabled.remove(&atom); |
57 | } | ||
58 | } | ||
59 | } | ||
60 | |||
61 | pub struct CfgDiff { | ||
62 | // Invariants: No duplicates, no atom that's both in `enable` and `disable`. | ||
63 | enable: Vec<CfgAtom>, | ||
64 | disable: Vec<CfgAtom>, | ||
65 | } | ||
66 | |||
67 | impl CfgDiff { | ||
68 | /// Returns the total number of atoms changed by this diff. | ||
69 | pub fn len(&self) -> usize { | ||
70 | self.enable.len() + self.disable.len() | ||
71 | } | ||
72 | } | ||
73 | |||
74 | impl fmt::Display for CfgDiff { | ||
75 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
76 | if !self.enable.is_empty() { | ||
77 | f.write_str("enable ")?; | ||
78 | for (i, atom) in self.enable.iter().enumerate() { | ||
79 | let sep = match i { | ||
80 | 0 => "", | ||
81 | _ if i == self.enable.len() - 1 => " and ", | ||
82 | _ => ", ", | ||
83 | }; | ||
84 | f.write_str(sep)?; | ||
85 | |||
86 | write!(f, "{}", atom)?; | ||
87 | } | ||
88 | |||
89 | if !self.disable.is_empty() { | ||
90 | f.write_str("; ")?; | ||
91 | } | ||
49 | } | 92 | } |
93 | |||
94 | if !self.disable.is_empty() { | ||
95 | f.write_str("disable ")?; | ||
96 | for (i, atom) in self.disable.iter().enumerate() { | ||
97 | let sep = match i { | ||
98 | 0 => "", | ||
99 | _ if i == self.enable.len() - 1 => " and ", | ||
100 | _ => ", ", | ||
101 | }; | ||
102 | f.write_str(sep)?; | ||
103 | |||
104 | write!(f, "{}", atom)?; | ||
105 | } | ||
106 | } | ||
107 | |||
108 | Ok(()) | ||
109 | } | ||
110 | } | ||
111 | |||
112 | pub struct InactiveReason { | ||
113 | enabled: Vec<CfgAtom>, | ||
114 | disabled: Vec<CfgAtom>, | ||
115 | } | ||
116 | |||
117 | impl fmt::Display for InactiveReason { | ||
118 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
119 | if !self.enabled.is_empty() { | ||
120 | for (i, atom) in self.enabled.iter().enumerate() { | ||
121 | let sep = match i { | ||
122 | 0 => "", | ||
123 | _ if i == self.enabled.len() - 1 => " and ", | ||
124 | _ => ", ", | ||
125 | }; | ||
126 | f.write_str(sep)?; | ||
127 | |||
128 | write!(f, "{}", atom)?; | ||
129 | } | ||
130 | let is_are = if self.enabled.len() == 1 { "is" } else { "are" }; | ||
131 | write!(f, " {} enabled", is_are)?; | ||
132 | |||
133 | if !self.disabled.is_empty() { | ||
134 | f.write_str(" and ")?; | ||
135 | } | ||
136 | } | ||
137 | |||
138 | if !self.disabled.is_empty() { | ||
139 | for (i, atom) in self.disabled.iter().enumerate() { | ||
140 | let sep = match i { | ||
141 | 0 => "", | ||
142 | _ if i == self.disabled.len() - 1 => " and ", | ||
143 | _ => ", ", | ||
144 | }; | ||
145 | f.write_str(sep)?; | ||
146 | |||
147 | write!(f, "{}", atom)?; | ||
148 | } | ||
149 | let is_are = if self.disabled.len() == 1 { "is" } else { "are" }; | ||
150 | write!(f, " {} disabled", is_are)?; | ||
151 | } | ||
152 | |||
153 | Ok(()) | ||
50 | } | 154 | } |
51 | } | 155 | } |
diff --git a/crates/cfg/src/tests.rs b/crates/cfg/src/tests.rs new file mode 100644 index 000000000..bd0f9ec48 --- /dev/null +++ b/crates/cfg/src/tests.rs | |||
@@ -0,0 +1,193 @@ | |||
1 | use expect_test::{expect, Expect}; | ||
2 | use mbe::ast_to_token_tree; | ||
3 | use syntax::{ast, AstNode}; | ||
4 | |||
5 | use crate::{CfgAtom, CfgExpr, CfgOptions, DnfExpr}; | ||
6 | |||
7 | fn assert_parse_result(input: &str, expected: CfgExpr) { | ||
8 | let (tt, _) = { | ||
9 | let source_file = ast::SourceFile::parse(input).ok().unwrap(); | ||
10 | let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); | ||
11 | ast_to_token_tree(&tt).unwrap() | ||
12 | }; | ||
13 | let cfg = CfgExpr::parse(&tt); | ||
14 | assert_eq!(cfg, expected); | ||
15 | } | ||
16 | |||
17 | fn check_dnf(input: &str, expect: Expect) { | ||
18 | let (tt, _) = { | ||
19 | let source_file = ast::SourceFile::parse(input).ok().unwrap(); | ||
20 | let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); | ||
21 | ast_to_token_tree(&tt).unwrap() | ||
22 | }; | ||
23 | let cfg = CfgExpr::parse(&tt); | ||
24 | let actual = format!("#![cfg({})]", DnfExpr::new(cfg)); | ||
25 | expect.assert_eq(&actual); | ||
26 | } | ||
27 | |||
28 | fn check_why_inactive(input: &str, opts: &CfgOptions, expect: Expect) { | ||
29 | let (tt, _) = { | ||
30 | let source_file = ast::SourceFile::parse(input).ok().unwrap(); | ||
31 | let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); | ||
32 | ast_to_token_tree(&tt).unwrap() | ||
33 | }; | ||
34 | let cfg = CfgExpr::parse(&tt); | ||
35 | let dnf = DnfExpr::new(cfg); | ||
36 | let why_inactive = dnf.why_inactive(opts).unwrap().to_string(); | ||
37 | expect.assert_eq(&why_inactive); | ||
38 | } | ||
39 | |||
40 | #[track_caller] | ||
41 | fn check_enable_hints(input: &str, opts: &CfgOptions, expected_hints: &[&str]) { | ||
42 | let (tt, _) = { | ||
43 | let source_file = ast::SourceFile::parse(input).ok().unwrap(); | ||
44 | let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); | ||
45 | ast_to_token_tree(&tt).unwrap() | ||
46 | }; | ||
47 | let cfg = CfgExpr::parse(&tt); | ||
48 | let dnf = DnfExpr::new(cfg); | ||
49 | let hints = dnf.compute_enable_hints(opts).map(|diff| diff.to_string()).collect::<Vec<_>>(); | ||
50 | assert_eq!(hints, expected_hints); | ||
51 | } | ||
52 | |||
53 | #[test] | ||
54 | fn test_cfg_expr_parser() { | ||
55 | assert_parse_result("#![cfg(foo)]", CfgAtom::Flag("foo".into()).into()); | ||
56 | assert_parse_result("#![cfg(foo,)]", CfgAtom::Flag("foo".into()).into()); | ||
57 | assert_parse_result( | ||
58 | "#![cfg(not(foo))]", | ||
59 | CfgExpr::Not(Box::new(CfgAtom::Flag("foo".into()).into())), | ||
60 | ); | ||
61 | assert_parse_result("#![cfg(foo(bar))]", CfgExpr::Invalid); | ||
62 | |||
63 | // Only take the first | ||
64 | assert_parse_result(r#"#![cfg(foo, bar = "baz")]"#, CfgAtom::Flag("foo".into()).into()); | ||
65 | |||
66 | assert_parse_result( | ||
67 | r#"#![cfg(all(foo, bar = "baz"))]"#, | ||
68 | CfgExpr::All(vec![ | ||
69 | CfgAtom::Flag("foo".into()).into(), | ||
70 | CfgAtom::KeyValue { key: "bar".into(), value: "baz".into() }.into(), | ||
71 | ]), | ||
72 | ); | ||
73 | |||
74 | assert_parse_result( | ||
75 | r#"#![cfg(any(not(), all(), , bar = "baz",))]"#, | ||
76 | CfgExpr::Any(vec![ | ||
77 | CfgExpr::Not(Box::new(CfgExpr::Invalid)), | ||
78 | CfgExpr::All(vec![]), | ||
79 | CfgExpr::Invalid, | ||
80 | CfgAtom::KeyValue { key: "bar".into(), value: "baz".into() }.into(), | ||
81 | ]), | ||
82 | ); | ||
83 | } | ||
84 | |||
85 | #[test] | ||
86 | fn smoke() { | ||
87 | check_dnf("#![cfg(test)]", expect![[r#"#![cfg(test)]"#]]); | ||
88 | check_dnf("#![cfg(not(test))]", expect![[r#"#![cfg(not(test))]"#]]); | ||
89 | check_dnf("#![cfg(not(not(test)))]", expect![[r#"#![cfg(test)]"#]]); | ||
90 | |||
91 | check_dnf("#![cfg(all(a, b))]", expect![[r#"#![cfg(all(a, b))]"#]]); | ||
92 | check_dnf("#![cfg(any(a, b))]", expect![[r#"#![cfg(any(a, b))]"#]]); | ||
93 | |||
94 | check_dnf("#![cfg(not(a))]", expect![[r#"#![cfg(not(a))]"#]]); | ||
95 | } | ||
96 | |||
97 | #[test] | ||
98 | fn distribute() { | ||
99 | check_dnf("#![cfg(all(any(a, b), c))]", expect![[r#"#![cfg(any(all(a, c), all(b, c)))]"#]]); | ||
100 | check_dnf("#![cfg(all(c, any(a, b)))]", expect![[r#"#![cfg(any(all(c, a), all(c, b)))]"#]]); | ||
101 | check_dnf( | ||
102 | "#![cfg(all(any(a, b), any(c, d)))]", | ||
103 | expect![[r#"#![cfg(any(all(a, c), all(a, d), all(b, c), all(b, d)))]"#]], | ||
104 | ); | ||
105 | |||
106 | check_dnf( | ||
107 | "#![cfg(all(any(a, b, c), any(d, e, f), g))]", | ||
108 | expect![[ | ||
109 | r#"#![cfg(any(all(a, d, g), all(a, e, g), all(a, f, g), all(b, d, g), all(b, e, g), all(b, f, g), all(c, d, g), all(c, e, g), all(c, f, g)))]"# | ||
110 | ]], | ||
111 | ); | ||
112 | } | ||
113 | |||
114 | #[test] | ||
115 | fn demorgan() { | ||
116 | check_dnf("#![cfg(not(all(a, b)))]", expect![[r#"#![cfg(any(not(a), not(b)))]"#]]); | ||
117 | check_dnf("#![cfg(not(any(a, b)))]", expect![[r#"#![cfg(all(not(a), not(b)))]"#]]); | ||
118 | |||
119 | check_dnf("#![cfg(not(all(not(a), b)))]", expect![[r#"#![cfg(any(a, not(b)))]"#]]); | ||
120 | check_dnf("#![cfg(not(any(a, not(b))))]", expect![[r#"#![cfg(all(not(a), b))]"#]]); | ||
121 | } | ||
122 | |||
123 | #[test] | ||
124 | fn nested() { | ||
125 | check_dnf("#![cfg(all(any(a), not(all(any(b)))))]", expect![[r#"#![cfg(all(a, not(b)))]"#]]); | ||
126 | |||
127 | check_dnf("#![cfg(any(any(a, b)))]", expect![[r#"#![cfg(any(a, b))]"#]]); | ||
128 | check_dnf("#![cfg(not(any(any(a, b))))]", expect![[r#"#![cfg(all(not(a), not(b)))]"#]]); | ||
129 | check_dnf("#![cfg(all(all(a, b)))]", expect![[r#"#![cfg(all(a, b))]"#]]); | ||
130 | check_dnf("#![cfg(not(all(all(a, b))))]", expect![[r#"#![cfg(any(not(a), not(b)))]"#]]); | ||
131 | } | ||
132 | |||
133 | #[test] | ||
134 | fn hints() { | ||
135 | let mut opts = CfgOptions::default(); | ||
136 | |||
137 | check_enable_hints("#![cfg(test)]", &opts, &["enable test"]); | ||
138 | check_enable_hints("#![cfg(not(test))]", &opts, &[]); | ||
139 | |||
140 | check_enable_hints("#![cfg(any(a, b))]", &opts, &["enable a", "enable b"]); | ||
141 | check_enable_hints("#![cfg(any(b, a))]", &opts, &["enable b", "enable a"]); | ||
142 | |||
143 | check_enable_hints("#![cfg(all(a, b))]", &opts, &["enable a and b"]); | ||
144 | |||
145 | opts.insert_atom("test".into()); | ||
146 | |||
147 | check_enable_hints("#![cfg(test)]", &opts, &[]); | ||
148 | check_enable_hints("#![cfg(not(test))]", &opts, &["disable test"]); | ||
149 | } | ||
150 | |||
151 | /// Tests that we don't suggest hints for cfgs that express an inconsistent formula. | ||
152 | #[test] | ||
153 | fn hints_impossible() { | ||
154 | let mut opts = CfgOptions::default(); | ||
155 | |||
156 | check_enable_hints("#![cfg(all(test, not(test)))]", &opts, &[]); | ||
157 | |||
158 | opts.insert_atom("test".into()); | ||
159 | |||
160 | check_enable_hints("#![cfg(all(test, not(test)))]", &opts, &[]); | ||
161 | } | ||
162 | |||
163 | #[test] | ||
164 | fn why_inactive() { | ||
165 | let mut opts = CfgOptions::default(); | ||
166 | opts.insert_atom("test".into()); | ||
167 | opts.insert_atom("test2".into()); | ||
168 | |||
169 | check_why_inactive("#![cfg(a)]", &opts, expect![["a is disabled"]]); | ||
170 | check_why_inactive("#![cfg(not(test))]", &opts, expect![["test is enabled"]]); | ||
171 | |||
172 | check_why_inactive( | ||
173 | "#![cfg(all(not(test), not(test2)))]", | ||
174 | &opts, | ||
175 | expect![["test and test2 are enabled"]], | ||
176 | ); | ||
177 | check_why_inactive("#![cfg(all(a, b))]", &opts, expect![["a and b are disabled"]]); | ||
178 | check_why_inactive( | ||
179 | "#![cfg(all(not(test), a))]", | ||
180 | &opts, | ||
181 | expect![["test is enabled and a is disabled"]], | ||
182 | ); | ||
183 | check_why_inactive( | ||
184 | "#![cfg(all(not(test), test2, a))]", | ||
185 | &opts, | ||
186 | expect![["test is enabled and a is disabled"]], | ||
187 | ); | ||
188 | check_why_inactive( | ||
189 | "#![cfg(all(not(test), not(test2), a))]", | ||
190 | &opts, | ||
191 | expect![["test and test2 are enabled and a is disabled"]], | ||
192 | ); | ||
193 | } | ||
diff --git a/crates/completion/Cargo.toml b/crates/completion/Cargo.toml new file mode 100644 index 000000000..b79ee33f7 --- /dev/null +++ b/crates/completion/Cargo.toml | |||
@@ -0,0 +1,30 @@ | |||
1 | [package] | ||
2 | name = "completion" | ||
3 | version = "0.0.0" | ||
4 | description = "TBD" | ||
5 | license = "MIT OR Apache-2.0" | ||
6 | authors = ["rust-analyzer developers"] | ||
7 | edition = "2018" | ||
8 | |||
9 | [lib] | ||
10 | doctest = false | ||
11 | |||
12 | [dependencies] | ||
13 | itertools = "0.9.0" | ||
14 | log = "0.4.8" | ||
15 | rustc-hash = "1.1.0" | ||
16 | |||
17 | stdx = { path = "../stdx", version = "0.0.0" } | ||
18 | syntax = { path = "../syntax", version = "0.0.0" } | ||
19 | text_edit = { path = "../text_edit", version = "0.0.0" } | ||
20 | base_db = { path = "../base_db", version = "0.0.0" } | ||
21 | ide_db = { path = "../ide_db", version = "0.0.0" } | ||
22 | profile = { path = "../profile", version = "0.0.0" } | ||
23 | test_utils = { path = "../test_utils", version = "0.0.0" } | ||
24 | |||
25 | # completions crate should depend only on the top-level `hir` package. if you need | ||
26 | # something from some `hir_xxx` subpackage, reexport the API via `hir`. | ||
27 | hir = { path = "../hir", version = "0.0.0" } | ||
28 | |||
29 | [dev-dependencies] | ||
30 | expect-test = "1.0" | ||
diff --git a/crates/ide/src/completion/presentation.rs b/crates/completion/src/completions.rs index a5172b87e..d5fb85b79 100644 --- a/crates/ide/src/completion/presentation.rs +++ b/crates/completion/src/completions.rs | |||
@@ -1,25 +1,66 @@ | |||
1 | //! This modules takes care of rendering various definitions as completion items. | 1 | //! This module defines an accumulator for completions which are going to be presented to user. |
2 | //! It also handles scoring (sorting) completions. | 2 | |
3 | 3 | pub(crate) mod attribute; | |
4 | use hir::{HasAttrs, HasSource, HirDisplay, ModPath, ScopeDef, StructKind, Type}; | 4 | pub(crate) mod dot; |
5 | pub(crate) mod record; | ||
6 | pub(crate) mod pattern; | ||
7 | pub(crate) mod fn_param; | ||
8 | pub(crate) mod keyword; | ||
9 | pub(crate) mod snippet; | ||
10 | pub(crate) mod qualified_path; | ||
11 | pub(crate) mod unqualified_path; | ||
12 | pub(crate) mod postfix; | ||
13 | pub(crate) mod macro_in_item_position; | ||
14 | pub(crate) mod trait_impl; | ||
15 | pub(crate) mod mod_; | ||
16 | |||
17 | use hir::{HasAttrs, HasSource, HirDisplay, ModPath, Mutability, ScopeDef, StructKind, Type}; | ||
5 | use itertools::Itertools; | 18 | use itertools::Itertools; |
6 | use syntax::ast::NameOwner; | 19 | use syntax::{ast::NameOwner, display::*}; |
7 | use test_utils::mark; | 20 | use test_utils::mark; |
8 | 21 | ||
9 | use crate::{ | 22 | use crate::{ |
10 | completion::{ | 23 | item::Builder, CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, |
11 | completion_item::Builder, CompletionContext, CompletionItem, CompletionItemKind, | ||
12 | CompletionKind, Completions, | ||
13 | }, | ||
14 | display::{const_label, function_declaration, macro_label, type_label}, | ||
15 | CompletionScore, RootDatabase, | 24 | CompletionScore, RootDatabase, |
16 | }; | 25 | }; |
17 | 26 | ||
27 | /// Represents an in-progress set of completions being built. | ||
28 | #[derive(Debug, Default)] | ||
29 | pub struct Completions { | ||
30 | buf: Vec<CompletionItem>, | ||
31 | } | ||
32 | |||
33 | impl Into<Vec<CompletionItem>> for Completions { | ||
34 | fn into(self) -> Vec<CompletionItem> { | ||
35 | self.buf | ||
36 | } | ||
37 | } | ||
38 | |||
39 | impl Builder { | ||
40 | /// Convenience method, which allows to add a freshly created completion into accumulator | ||
41 | /// without binding it to the variable. | ||
42 | pub(crate) fn add_to(self, acc: &mut Completions) { | ||
43 | acc.add(self.build()) | ||
44 | } | ||
45 | } | ||
46 | |||
18 | impl Completions { | 47 | impl Completions { |
48 | pub(crate) fn add(&mut self, item: CompletionItem) { | ||
49 | self.buf.push(item.into()) | ||
50 | } | ||
51 | |||
52 | pub(crate) fn add_all<I>(&mut self, items: I) | ||
53 | where | ||
54 | I: IntoIterator, | ||
55 | I::Item: Into<CompletionItem>, | ||
56 | { | ||
57 | items.into_iter().for_each(|item| self.add(item.into())) | ||
58 | } | ||
59 | |||
19 | pub(crate) fn add_field(&mut self, ctx: &CompletionContext, field: hir::Field, ty: &Type) { | 60 | pub(crate) fn add_field(&mut self, ctx: &CompletionContext, field: hir::Field, ty: &Type) { |
20 | let is_deprecated = is_deprecated(field, ctx.db); | 61 | let is_deprecated = is_deprecated(field, ctx.db); |
21 | let name = field.name(ctx.db); | 62 | let name = field.name(ctx.db); |
22 | let mut completion_item = | 63 | let mut item = |
23 | CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string()) | 64 | CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string()) |
24 | .kind(CompletionItemKind::Field) | 65 | .kind(CompletionItemKind::Field) |
25 | .detail(ty.display(ctx.db).to_string()) | 66 | .detail(ty.display(ctx.db).to_string()) |
@@ -27,10 +68,10 @@ impl Completions { | |||
27 | .set_deprecated(is_deprecated); | 68 | .set_deprecated(is_deprecated); |
28 | 69 | ||
29 | if let Some(score) = compute_score(ctx, &ty, &name.to_string()) { | 70 | if let Some(score) = compute_score(ctx, &ty, &name.to_string()) { |
30 | completion_item = completion_item.set_score(score); | 71 | item = item.set_score(score); |
31 | } | 72 | } |
32 | 73 | ||
33 | completion_item.add_to(self); | 74 | item.add_to(self); |
34 | } | 75 | } |
35 | 76 | ||
36 | pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) { | 77 | pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) { |
@@ -56,7 +97,8 @@ impl Completions { | |||
56 | let kind = match resolution { | 97 | let kind = match resolution { |
57 | ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::Module, | 98 | ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::Module, |
58 | ScopeDef::ModuleDef(Function(func)) => { | 99 | ScopeDef::ModuleDef(Function(func)) => { |
59 | return self.add_function(ctx, *func, Some(local_name)); | 100 | self.add_function(ctx, *func, Some(local_name)); |
101 | return; | ||
60 | } | 102 | } |
61 | ScopeDef::ModuleDef(Adt(hir::Adt::Struct(_))) => CompletionItemKind::Struct, | 103 | ScopeDef::ModuleDef(Adt(hir::Adt::Struct(_))) => CompletionItemKind::Struct, |
62 | // FIXME: add CompletionItemKind::Union | 104 | // FIXME: add CompletionItemKind::Union |
@@ -64,7 +106,8 @@ impl Completions { | |||
64 | ScopeDef::ModuleDef(Adt(hir::Adt::Enum(_))) => CompletionItemKind::Enum, | 106 | ScopeDef::ModuleDef(Adt(hir::Adt::Enum(_))) => CompletionItemKind::Enum, |
65 | 107 | ||
66 | ScopeDef::ModuleDef(EnumVariant(var)) => { | 108 | ScopeDef::ModuleDef(EnumVariant(var)) => { |
67 | return self.add_enum_variant(ctx, *var, Some(local_name)); | 109 | self.add_enum_variant(ctx, *var, Some(local_name)); |
110 | return; | ||
68 | } | 111 | } |
69 | ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::Const, | 112 | ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::Const, |
70 | ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::Static, | 113 | ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::Static, |
@@ -76,13 +119,14 @@ impl Completions { | |||
76 | // (does this need its own kind?) | 119 | // (does this need its own kind?) |
77 | ScopeDef::AdtSelfType(..) | ScopeDef::ImplSelfType(..) => CompletionItemKind::TypeParam, | 120 | ScopeDef::AdtSelfType(..) | ScopeDef::ImplSelfType(..) => CompletionItemKind::TypeParam, |
78 | ScopeDef::MacroDef(mac) => { | 121 | ScopeDef::MacroDef(mac) => { |
79 | return self.add_macro(ctx, Some(local_name), *mac); | 122 | self.add_macro(ctx, Some(local_name), *mac); |
123 | return; | ||
80 | } | 124 | } |
81 | ScopeDef::Unknown => { | 125 | ScopeDef::Unknown => { |
82 | return self.add( | 126 | CompletionItem::new(CompletionKind::Reference, ctx.source_range(), local_name) |
83 | CompletionItem::new(CompletionKind::Reference, ctx.source_range(), local_name) | 127 | .kind(CompletionItemKind::UnresolvedReference) |
84 | .kind(CompletionItemKind::UnresolvedReference), | 128 | .add_to(self); |
85 | ); | 129 | return; |
86 | } | 130 | } |
87 | }; | 131 | }; |
88 | 132 | ||
@@ -97,18 +141,24 @@ impl Completions { | |||
97 | _ => None, | 141 | _ => None, |
98 | }; | 142 | }; |
99 | 143 | ||
100 | let mut completion_item = | 144 | let mut item = CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone()); |
101 | CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone()); | ||
102 | if let ScopeDef::Local(local) = resolution { | 145 | if let ScopeDef::Local(local) = resolution { |
103 | let ty = local.ty(ctx.db); | 146 | let ty = local.ty(ctx.db); |
104 | if !ty.is_unknown() { | 147 | if !ty.is_unknown() { |
105 | completion_item = completion_item.detail(ty.display(ctx.db).to_string()); | 148 | item = item.detail(ty.display(ctx.db).to_string()); |
106 | } | 149 | } |
107 | }; | 150 | }; |
108 | 151 | ||
152 | let mut ref_match = None; | ||
109 | if let ScopeDef::Local(local) = resolution { | 153 | if let ScopeDef::Local(local) = resolution { |
110 | if let Some(score) = compute_score(ctx, &local.ty(ctx.db), &local_name) { | 154 | if let Some((active_name, active_type)) = ctx.active_name_and_type() { |
111 | completion_item = completion_item.set_score(score); | 155 | let ty = local.ty(ctx.db); |
156 | if let Some(score) = | ||
157 | compute_score_from_active(&active_type, &active_name, &ty, &local_name) | ||
158 | { | ||
159 | item = item.set_score(score); | ||
160 | } | ||
161 | ref_match = refed_type_matches(&active_type, &active_name, &ty, &local_name); | ||
112 | } | 162 | } |
113 | } | 163 | } |
114 | 164 | ||
@@ -122,7 +172,7 @@ impl Completions { | |||
122 | }; | 172 | }; |
123 | if has_non_default_type_params { | 173 | if has_non_default_type_params { |
124 | mark::hit!(inserts_angle_brackets_for_generics); | 174 | mark::hit!(inserts_angle_brackets_for_generics); |
125 | completion_item = completion_item | 175 | item = item |
126 | .lookup_by(local_name.clone()) | 176 | .lookup_by(local_name.clone()) |
127 | .label(format!("{}<…>", local_name)) | 177 | .label(format!("{}<…>", local_name)) |
128 | .insert_snippet(cap, format!("{}<$0>", local_name)); | 178 | .insert_snippet(cap, format!("{}<$0>", local_name)); |
@@ -130,7 +180,7 @@ impl Completions { | |||
130 | } | 180 | } |
131 | } | 181 | } |
132 | 182 | ||
133 | completion_item.kind(kind).set_documentation(docs).add_to(self) | 183 | item.kind(kind).set_documentation(docs).set_ref_match(ref_match).add_to(self) |
134 | } | 184 | } |
135 | 185 | ||
136 | pub(crate) fn add_macro( | 186 | pub(crate) fn add_macro( |
@@ -182,7 +232,7 @@ impl Completions { | |||
182 | } | 232 | } |
183 | }; | 233 | }; |
184 | 234 | ||
185 | self.add(builder); | 235 | self.add(builder.build()); |
186 | } | 236 | } |
187 | 237 | ||
188 | pub(crate) fn add_function( | 238 | pub(crate) fn add_function( |
@@ -234,7 +284,7 @@ impl Completions { | |||
234 | 284 | ||
235 | builder = builder.add_call_parens(ctx, name, Params::Named(params)); | 285 | builder = builder.add_call_parens(ctx, name, Params::Named(params)); |
236 | 286 | ||
237 | self.add(builder) | 287 | self.add(builder.build()) |
238 | } | 288 | } |
239 | 289 | ||
240 | pub(crate) fn add_const(&mut self, ctx: &CompletionContext, constant: hir::Const) { | 290 | pub(crate) fn add_const(&mut self, ctx: &CompletionContext, constant: hir::Const) { |
@@ -296,9 +346,14 @@ impl Completions { | |||
296 | ) { | 346 | ) { |
297 | let is_deprecated = is_deprecated(variant, ctx.db); | 347 | let is_deprecated = is_deprecated(variant, ctx.db); |
298 | let name = local_name.unwrap_or_else(|| variant.name(ctx.db).to_string()); | 348 | let name = local_name.unwrap_or_else(|| variant.name(ctx.db).to_string()); |
299 | let qualified_name = match &path { | 349 | let (qualified_name, short_qualified_name) = match &path { |
300 | Some(it) => it.to_string(), | 350 | Some(path) => { |
301 | None => name.to_string(), | 351 | let full = path.to_string(); |
352 | let short = | ||
353 | path.segments[path.segments.len().saturating_sub(2)..].iter().join("::"); | ||
354 | (full, short) | ||
355 | } | ||
356 | None => (name.to_string(), name.to_string()), | ||
302 | }; | 357 | }; |
303 | let detail_types = variant | 358 | let detail_types = variant |
304 | .fields(ctx.db) | 359 | .fields(ctx.db) |
@@ -327,39 +382,27 @@ impl Completions { | |||
327 | .set_deprecated(is_deprecated) | 382 | .set_deprecated(is_deprecated) |
328 | .detail(detail); | 383 | .detail(detail); |
329 | 384 | ||
330 | if path.is_some() { | ||
331 | res = res.lookup_by(name); | ||
332 | } | ||
333 | |||
334 | if variant_kind == StructKind::Tuple { | 385 | if variant_kind == StructKind::Tuple { |
335 | mark::hit!(inserts_parens_for_tuple_enums); | 386 | mark::hit!(inserts_parens_for_tuple_enums); |
336 | let params = Params::Anonymous(variant.fields(ctx.db).len()); | 387 | let params = Params::Anonymous(variant.fields(ctx.db).len()); |
337 | res = res.add_call_parens(ctx, qualified_name, params) | 388 | res = res.add_call_parens(ctx, short_qualified_name, params) |
389 | } else if path.is_some() { | ||
390 | res = res.lookup_by(short_qualified_name); | ||
338 | } | 391 | } |
339 | 392 | ||
340 | res.add_to(self); | 393 | res.add_to(self); |
341 | } | 394 | } |
342 | } | 395 | } |
343 | 396 | ||
344 | pub(crate) fn compute_score( | 397 | fn compute_score_from_active( |
345 | ctx: &CompletionContext, | 398 | active_type: &Type, |
399 | active_name: &str, | ||
346 | ty: &Type, | 400 | ty: &Type, |
347 | name: &str, | 401 | name: &str, |
348 | ) -> Option<CompletionScore> { | 402 | ) -> Option<CompletionScore> { |
349 | let (active_name, active_type) = if let Some(record_field) = &ctx.record_field_syntax { | ||
350 | mark::hit!(record_field_type_match); | ||
351 | let (struct_field, _local) = ctx.sema.resolve_record_field(record_field)?; | ||
352 | (struct_field.name(ctx.db).to_string(), struct_field.signature_ty(ctx.db)) | ||
353 | } else if let Some(active_parameter) = &ctx.active_parameter { | ||
354 | mark::hit!(active_param_type_match); | ||
355 | (active_parameter.name.clone(), active_parameter.ty.clone()) | ||
356 | } else { | ||
357 | return None; | ||
358 | }; | ||
359 | |||
360 | // Compute score | 403 | // Compute score |
361 | // For the same type | 404 | // For the same type |
362 | if &active_type != ty { | 405 | if active_type != ty { |
363 | return None; | 406 | return None; |
364 | } | 407 | } |
365 | 408 | ||
@@ -372,6 +415,24 @@ pub(crate) fn compute_score( | |||
372 | 415 | ||
373 | Some(res) | 416 | Some(res) |
374 | } | 417 | } |
418 | fn refed_type_matches( | ||
419 | active_type: &Type, | ||
420 | active_name: &str, | ||
421 | ty: &Type, | ||
422 | name: &str, | ||
423 | ) -> Option<(Mutability, CompletionScore)> { | ||
424 | let derefed_active = active_type.remove_ref()?; | ||
425 | let score = compute_score_from_active(&derefed_active, &active_name, &ty, &name)?; | ||
426 | Some(( | ||
427 | if active_type.is_mutable_reference() { Mutability::Mut } else { Mutability::Shared }, | ||
428 | score, | ||
429 | )) | ||
430 | } | ||
431 | |||
432 | fn compute_score(ctx: &CompletionContext, ty: &Type, name: &str) -> Option<CompletionScore> { | ||
433 | let (active_name, active_type) = ctx.active_name_and_type()?; | ||
434 | compute_score_from_active(&active_type, &active_name, ty, name) | ||
435 | } | ||
375 | 436 | ||
376 | enum Params { | 437 | enum Params { |
377 | Named(Vec<String>), | 438 | Named(Vec<String>), |
@@ -487,13 +548,8 @@ mod tests { | |||
487 | use test_utils::mark; | 548 | use test_utils::mark; |
488 | 549 | ||
489 | use crate::{ | 550 | use crate::{ |
490 | completion::{ | 551 | test_utils::{check_edit, check_edit_with_config, do_completion, get_all_items}, |
491 | test_utils::{ | 552 | CompletionConfig, CompletionKind, CompletionScore, |
492 | check_edit, check_edit_with_config, do_completion, get_all_completion_items, | ||
493 | }, | ||
494 | CompletionConfig, CompletionKind, | ||
495 | }, | ||
496 | CompletionScore, | ||
497 | }; | 553 | }; |
498 | 554 | ||
499 | fn check(ra_fixture: &str, expect: Expect) { | 555 | fn check(ra_fixture: &str, expect: Expect) { |
@@ -510,7 +566,7 @@ mod tests { | |||
510 | } | 566 | } |
511 | } | 567 | } |
512 | 568 | ||
513 | let mut completions = get_all_completion_items(CompletionConfig::default(), ra_fixture); | 569 | let mut completions = get_all_items(CompletionConfig::default(), ra_fixture); |
514 | completions.sort_by_key(|it| (Reverse(it.score()), it.label().to_string())); | 570 | completions.sort_by_key(|it| (Reverse(it.score()), it.label().to_string())); |
515 | let actual = completions | 571 | let actual = completions |
516 | .into_iter() | 572 | .into_iter() |
@@ -596,7 +652,58 @@ fn main() { Foo::Fo<|> } | |||
596 | } | 652 | } |
597 | 653 | ||
598 | #[test] | 654 | #[test] |
599 | fn sets_deprecated_flag_in_completion_items() { | 655 | fn lookup_enums_by_two_qualifiers() { |
656 | check( | ||
657 | r#" | ||
658 | mod m { | ||
659 | pub enum Spam { Foo, Bar(i32) } | ||
660 | } | ||
661 | fn main() { let _: m::Spam = S<|> } | ||
662 | "#, | ||
663 | expect![[r#" | ||
664 | [ | ||
665 | CompletionItem { | ||
666 | label: "Spam::Bar(…)", | ||
667 | source_range: 75..76, | ||
668 | delete: 75..76, | ||
669 | insert: "Spam::Bar($0)", | ||
670 | kind: EnumVariant, | ||
671 | lookup: "Spam::Bar", | ||
672 | detail: "(i32)", | ||
673 | trigger_call_info: true, | ||
674 | }, | ||
675 | CompletionItem { | ||
676 | label: "m", | ||
677 | source_range: 75..76, | ||
678 | delete: 75..76, | ||
679 | insert: "m", | ||
680 | kind: Module, | ||
681 | }, | ||
682 | CompletionItem { | ||
683 | label: "m::Spam::Foo", | ||
684 | source_range: 75..76, | ||
685 | delete: 75..76, | ||
686 | insert: "m::Spam::Foo", | ||
687 | kind: EnumVariant, | ||
688 | lookup: "Spam::Foo", | ||
689 | detail: "()", | ||
690 | }, | ||
691 | CompletionItem { | ||
692 | label: "main()", | ||
693 | source_range: 75..76, | ||
694 | delete: 75..76, | ||
695 | insert: "main()$0", | ||
696 | kind: Function, | ||
697 | lookup: "main", | ||
698 | detail: "fn main()", | ||
699 | }, | ||
700 | ] | ||
701 | "#]], | ||
702 | ) | ||
703 | } | ||
704 | |||
705 | #[test] | ||
706 | fn sets_deprecated_flag_in_items() { | ||
600 | check( | 707 | check( |
601 | r#" | 708 | r#" |
602 | #[deprecated] | 709 | #[deprecated] |
@@ -1277,7 +1384,6 @@ fn go(world: &WorldSnapshot) { go(w<|>) } | |||
1277 | 1384 | ||
1278 | #[test] | 1385 | #[test] |
1279 | fn too_many_arguments() { | 1386 | fn too_many_arguments() { |
1280 | mark::check!(too_many_arguments); | ||
1281 | check_scores( | 1387 | check_scores( |
1282 | r#" | 1388 | r#" |
1283 | struct Foo; | 1389 | struct Foo; |
diff --git a/crates/ide/src/completion/complete_attribute.rs b/crates/completion/src/completions/attribute.rs index f4a9864d1..f3d669458 100644 --- a/crates/ide/src/completion/complete_attribute.rs +++ b/crates/completion/src/completions/attribute.rs | |||
@@ -6,13 +6,14 @@ | |||
6 | use rustc_hash::FxHashSet; | 6 | use rustc_hash::FxHashSet; |
7 | use syntax::{ast, AstNode, SyntaxKind}; | 7 | use syntax::{ast, AstNode, SyntaxKind}; |
8 | 8 | ||
9 | use crate::completion::{ | 9 | use crate::{ |
10 | completion_context::CompletionContext, | 10 | context::CompletionContext, |
11 | completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions}, | 11 | generated_lint_completions::{CLIPPY_LINTS, FEATURES}, |
12 | generated_features::FEATURES, | 12 | item::{CompletionItem, CompletionItemKind, CompletionKind}, |
13 | Completions, | ||
13 | }; | 14 | }; |
14 | 15 | ||
15 | pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { | 16 | pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { |
16 | if ctx.mod_declaration_under_caret.is_some() { | 17 | if ctx.mod_declaration_under_caret.is_some() { |
17 | return None; | 18 | return None; |
18 | } | 19 | } |
@@ -23,14 +24,15 @@ pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) | |||
23 | complete_derive(acc, ctx, token_tree) | 24 | complete_derive(acc, ctx, token_tree) |
24 | } | 25 | } |
25 | (Some(path), Some(token_tree)) if path.to_string() == "feature" => { | 26 | (Some(path), Some(token_tree)) if path.to_string() == "feature" => { |
26 | complete_lint(acc, ctx, token_tree, FEATURES) | 27 | complete_lint(acc, ctx, token_tree, FEATURES); |
27 | } | 28 | } |
28 | (Some(path), Some(token_tree)) | 29 | (Some(path), Some(token_tree)) |
29 | if ["allow", "warn", "deny", "forbid"] | 30 | if ["allow", "warn", "deny", "forbid"] |
30 | .iter() | 31 | .iter() |
31 | .any(|lint_level| lint_level == &path.to_string()) => | 32 | .any(|lint_level| lint_level == &path.to_string()) => |
32 | { | 33 | { |
33 | complete_lint(acc, ctx, token_tree, DEFAULT_LINT_COMPLETIONS) | 34 | complete_lint(acc, ctx, token_tree.clone(), DEFAULT_LINT_COMPLETIONS); |
35 | complete_lint(acc, ctx, token_tree, CLIPPY_LINTS); | ||
34 | } | 36 | } |
35 | (_, Some(_token_tree)) => {} | 37 | (_, Some(_token_tree)) => {} |
36 | _ => complete_attribute_start(acc, ctx, attribute), | 38 | _ => complete_attribute_start(acc, ctx, attribute), |
@@ -59,7 +61,7 @@ fn complete_attribute_start(acc: &mut Completions, ctx: &CompletionContext, attr | |||
59 | } | 61 | } |
60 | 62 | ||
61 | if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner { | 63 | if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner { |
62 | acc.add(item); | 64 | acc.add(item.build()); |
63 | } | 65 | } |
64 | } | 66 | } |
65 | } | 67 | } |
@@ -151,21 +153,15 @@ fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: | |||
151 | label.push_str(", "); | 153 | label.push_str(", "); |
152 | label.push_str(dependency); | 154 | label.push_str(dependency); |
153 | } | 155 | } |
154 | acc.add( | 156 | CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label) |
155 | CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label) | 157 | .kind(CompletionItemKind::Attribute) |
156 | .kind(CompletionItemKind::Attribute), | 158 | .add_to(acc) |
157 | ); | ||
158 | } | 159 | } |
159 | 160 | ||
160 | for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) { | 161 | for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) { |
161 | acc.add( | 162 | CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), custom_derive_name) |
162 | CompletionItem::new( | 163 | .kind(CompletionItemKind::Attribute) |
163 | CompletionKind::Attribute, | 164 | .add_to(acc) |
164 | ctx.source_range(), | ||
165 | custom_derive_name, | ||
166 | ) | ||
167 | .kind(CompletionItemKind::Attribute), | ||
168 | ); | ||
169 | } | 165 | } |
170 | } | 166 | } |
171 | } | 167 | } |
@@ -181,15 +177,14 @@ fn complete_lint( | |||
181 | .into_iter() | 177 | .into_iter() |
182 | .filter(|completion| !existing_lints.contains(completion.label)) | 178 | .filter(|completion| !existing_lints.contains(completion.label)) |
183 | { | 179 | { |
184 | acc.add( | 180 | CompletionItem::new( |
185 | CompletionItem::new( | 181 | CompletionKind::Attribute, |
186 | CompletionKind::Attribute, | 182 | ctx.source_range(), |
187 | ctx.source_range(), | 183 | lint_completion.label, |
188 | lint_completion.label, | 184 | ) |
189 | ) | 185 | .kind(CompletionItemKind::Attribute) |
190 | .kind(CompletionItemKind::Attribute) | 186 | .detail(lint_completion.description) |
191 | .detail(lint_completion.description), | 187 | .add_to(acc) |
192 | ); | ||
193 | } | 188 | } |
194 | } | 189 | } |
195 | } | 190 | } |
@@ -261,9 +256,9 @@ const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[ | |||
261 | DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, | 256 | DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, |
262 | ]; | 257 | ]; |
263 | 258 | ||
264 | pub(super) struct LintCompletion { | 259 | pub(crate) struct LintCompletion { |
265 | pub(super) label: &'static str, | 260 | pub(crate) label: &'static str, |
266 | pub(super) description: &'static str, | 261 | pub(crate) description: &'static str, |
267 | } | 262 | } |
268 | 263 | ||
269 | #[rustfmt::skip] | 264 | #[rustfmt::skip] |
@@ -389,7 +384,7 @@ const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[ | |||
389 | mod tests { | 384 | mod tests { |
390 | use expect_test::{expect, Expect}; | 385 | use expect_test::{expect, Expect}; |
391 | 386 | ||
392 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 387 | use crate::{test_utils::completion_list, CompletionKind}; |
393 | 388 | ||
394 | fn check(ra_fixture: &str, expect: Expect) { | 389 | fn check(ra_fixture: &str, expect: Expect) { |
395 | let actual = completion_list(ra_fixture, CompletionKind::Attribute); | 390 | let actual = completion_list(ra_fixture, CompletionKind::Attribute); |
@@ -418,130 +413,6 @@ struct Test {} | |||
418 | } | 413 | } |
419 | 414 | ||
420 | #[test] | 415 | #[test] |
421 | fn empty_lint_completion() { | ||
422 | check( | ||
423 | r#"#[allow(<|>)]"#, | ||
424 | expect![[r#" | ||
425 | at absolute_paths_not_starting_with_crate fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name | ||
426 | at ambiguous_associated_items ambiguous associated items | ||
427 | at anonymous_parameters detects anonymous parameters | ||
428 | at arithmetic_overflow arithmetic operation overflows | ||
429 | at array_into_iter detects calling `into_iter` on arrays | ||
430 | at asm_sub_register using only a subset of a register for inline asm inputs | ||
431 | at bare_trait_objects suggest using `dyn Trait` for trait objects | ||
432 | at bindings_with_variant_name detects pattern bindings with the same name as one of the matched variants | ||
433 | at box_pointers use of owned (Box type) heap memory | ||
434 | at cenum_impl_drop_cast a C-like enum implementing Drop is cast | ||
435 | at clashing_extern_declarations detects when an extern fn has been declared with the same name but different types | ||
436 | at coherence_leak_check distinct impls distinguished only by the leak-check code | ||
437 | at conflicting_repr_hints conflicts between `#[repr(..)]` hints that were previously accepted and used in practice | ||
438 | at confusable_idents detects visually confusable pairs between identifiers | ||
439 | at const_err constant evaluation detected erroneous expression | ||
440 | at dead_code detect unused, unexported items | ||
441 | at deprecated detects use of deprecated items | ||
442 | at deprecated_in_future detects use of items that will be deprecated in a future version | ||
443 | at elided_lifetimes_in_paths hidden lifetime parameters in types are deprecated | ||
444 | at ellipsis_inclusive_range_patterns `...` range patterns are deprecated | ||
445 | at explicit_outlives_requirements outlives requirements can be inferred | ||
446 | at exported_private_dependencies public interface leaks type from a private dependency | ||
447 | at ill_formed_attribute_input ill-formed attribute inputs that were previously accepted and used in practice | ||
448 | at illegal_floating_point_literal_pattern floating-point literals cannot be used in patterns | ||
449 | at improper_ctypes proper use of libc types in foreign modules | ||
450 | at improper_ctypes_definitions proper use of libc types in foreign item definitions | ||
451 | at incomplete_features incomplete features that may function improperly in some or all cases | ||
452 | at incomplete_include trailing content in included file | ||
453 | at indirect_structural_match pattern with const indirectly referencing non-structural-match type | ||
454 | at inline_no_sanitize detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]` | ||
455 | at intra_doc_link_resolution_failure failures in resolving intra-doc link targets | ||
456 | at invalid_codeblock_attributes codeblock attribute looks a lot like a known one | ||
457 | at invalid_type_param_default type parameter default erroneously allowed in invalid location | ||
458 | at invalid_value an invalid value is being created (such as a NULL reference) | ||
459 | at irrefutable_let_patterns detects irrefutable patterns in if-let and while-let statements | ||
460 | at keyword_idents detects edition keywords being used as an identifier | ||
461 | at late_bound_lifetime_arguments detects generic lifetime arguments in path segments with late bound lifetime parameters | ||
462 | at macro_expanded_macro_exports_accessed_by_absolute_paths macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths | ||
463 | at macro_use_extern_crate the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system | ||
464 | at meta_variable_misuse possible meta-variable misuse at macro definition | ||
465 | at missing_copy_implementations detects potentially-forgotten implementations of `Copy` | ||
466 | at missing_crate_level_docs detects crates with no crate-level documentation | ||
467 | at missing_debug_implementations detects missing implementations of Debug | ||
468 | at missing_doc_code_examples detects publicly-exported items without code samples in their documentation | ||
469 | at missing_docs detects missing documentation for public members | ||
470 | at missing_fragment_specifier detects missing fragment specifiers in unused `macro_rules!` patterns | ||
471 | at mixed_script_confusables detects Unicode scripts whose mixed script confusables codepoints are solely used | ||
472 | at mutable_borrow_reservation_conflict reservation of a two-phased borrow conflicts with other shared borrows | ||
473 | at mutable_transmutes mutating transmuted &mut T from &T may cause undefined behavior | ||
474 | at no_mangle_const_items const items will not have their symbols exported | ||
475 | at no_mangle_generic_items generic items must be mangled | ||
476 | at non_ascii_idents detects non-ASCII identifiers | ||
477 | at non_camel_case_types types, variants, traits and type parameters should have camel case names | ||
478 | at non_shorthand_field_patterns using `Struct { x: x }` instead of `Struct { x }` in a pattern | ||
479 | at non_snake_case variables, methods, functions, lifetime parameters and modules should have snake case names | ||
480 | at non_upper_case_globals static constants should have uppercase identifiers | ||
481 | at order_dependent_trait_objects trait-object types were treated as different depending on marker-trait order | ||
482 | at overflowing_literals literal out of range for its type | ||
483 | at overlapping_patterns detects overlapping patterns | ||
484 | at path_statements path statements with no effect | ||
485 | at patterns_in_fns_without_body patterns in functions without body were erroneously allowed | ||
486 | at private_doc_tests detects code samples in docs of private items not documented by rustdoc | ||
487 | at private_in_public detect private items in public interfaces not caught by the old implementation | ||
488 | at proc_macro_derive_resolution_fallback detects proc macro derives using inaccessible names from parent modules | ||
489 | at pub_use_of_private_extern_crate detect public re-exports of private extern crates | ||
490 | at redundant_semicolons detects unnecessary trailing semicolons | ||
491 | at renamed_and_removed_lints lints that have been renamed or removed | ||
492 | at safe_packed_borrows safe borrows of fields of packed structs were erroneously allowed | ||
493 | at single_use_lifetimes detects lifetime parameters that are only used once | ||
494 | at soft_unstable a feature gate that doesn't break dependent crates | ||
495 | at stable_features stable features found in `#[feature]` directive | ||
496 | at trivial_bounds these bounds don't depend on an type parameters | ||
497 | at trivial_casts detects trivial casts which could be removed | ||
498 | at trivial_numeric_casts detects trivial casts of numeric types which could be removed | ||
499 | at type_alias_bounds bounds in type aliases are not enforced | ||
500 | at tyvar_behind_raw_pointer raw pointer to an inference variable | ||
501 | at unaligned_references detects unaligned references to fields of packed structs | ||
502 | at uncommon_codepoints detects uncommon Unicode codepoints in identifiers | ||
503 | at unconditional_panic operation will cause a panic at runtime | ||
504 | at unconditional_recursion functions that cannot return without calling themselves | ||
505 | at unknown_crate_types unknown crate type found in `#[crate_type]` directive | ||
506 | at unknown_lints unrecognized lint attribute | ||
507 | at unnameable_test_items detects an item that cannot be named being marked as `#[test_case]` | ||
508 | at unreachable_code detects unreachable code paths | ||
509 | at unreachable_patterns detects unreachable patterns | ||
510 | at unreachable_pub `pub` items not reachable from crate root | ||
511 | at unsafe_code usage of `unsafe` code | ||
512 | at unsafe_op_in_unsafe_fn unsafe operations in unsafe functions without an explicit unsafe block are deprecated | ||
513 | at unstable_features enabling unstable features (deprecated. do not use) | ||
514 | at unstable_name_collisions detects name collision with an existing but unstable method | ||
515 | at unused_allocation detects unnecessary allocations that can be eliminated | ||
516 | at unused_assignments detect assignments that will never be read | ||
517 | at unused_attributes detects attributes that were not used by the compiler | ||
518 | at unused_braces unnecessary braces around an expression | ||
519 | at unused_comparisons comparisons made useless by limits of the types involved | ||
520 | at unused_crate_dependencies crate dependencies that are never used | ||
521 | at unused_doc_comments detects doc comments that aren't used by rustdoc | ||
522 | at unused_extern_crates extern crates that are never used | ||
523 | at unused_features unused features found in crate-level `#[feature]` directives | ||
524 | at unused_import_braces unnecessary braces around an imported item | ||
525 | at unused_imports imports that are never used | ||
526 | at unused_labels detects labels that are never used | ||
527 | at unused_lifetimes detects lifetime parameters that are never used | ||
528 | at unused_macros detects macros that were not used | ||
529 | at unused_must_use unused result of a type flagged as `#[must_use]` | ||
530 | at unused_mut detect mut variables which don't need to be mutable | ||
531 | at unused_parens `if`, `match`, `while` and `return` do not need parentheses | ||
532 | at unused_qualifications detects unnecessarily qualified names | ||
533 | at unused_results unused result of an expression in a statement | ||
534 | at unused_unsafe unnecessary use of an `unsafe` block | ||
535 | at unused_variables detect variables which are not used in any way | ||
536 | at variant_size_differences detects enums with widely varying variant sizes | ||
537 | at warnings mass-change the level for lints which produce warnings | ||
538 | at where_clauses_object_safety checks the object safety of where clauses | ||
539 | at while_true suggest using `loop { }` instead of `while true { }` | ||
540 | "#]], | ||
541 | ) | ||
542 | } | ||
543 | |||
544 | #[test] | ||
545 | fn no_completion_for_incorrect_derive() { | 416 | fn no_completion_for_incorrect_derive() { |
546 | check( | 417 | check( |
547 | r#" | 418 | r#" |
diff --git a/crates/ide/src/completion/complete_dot.rs b/crates/completion/src/completions/dot.rs index 0b9f1798a..c9875045a 100644 --- a/crates/ide/src/completion/complete_dot.rs +++ b/crates/completion/src/completions/dot.rs | |||
@@ -4,10 +4,10 @@ use hir::{HasVisibility, Type}; | |||
4 | use rustc_hash::FxHashSet; | 4 | use rustc_hash::FxHashSet; |
5 | use test_utils::mark; | 5 | use test_utils::mark; |
6 | 6 | ||
7 | use crate::completion::{completion_context::CompletionContext, completion_item::Completions}; | 7 | use crate::{context::CompletionContext, Completions}; |
8 | 8 | ||
9 | /// Complete dot accesses, i.e. fields or methods. | 9 | /// Complete dot accesses, i.e. fields or methods. |
10 | pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) { | 10 | pub(crate) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) { |
11 | let dot_receiver = match &ctx.dot_receiver { | 11 | let dot_receiver = match &ctx.dot_receiver { |
12 | Some(expr) => expr, | 12 | Some(expr) => expr, |
13 | _ => return, | 13 | _ => return, |
@@ -64,7 +64,7 @@ mod tests { | |||
64 | use expect_test::{expect, Expect}; | 64 | use expect_test::{expect, Expect}; |
65 | use test_utils::mark; | 65 | use test_utils::mark; |
66 | 66 | ||
67 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 67 | use crate::{test_utils::completion_list, CompletionKind}; |
68 | 68 | ||
69 | fn check(ra_fixture: &str, expect: Expect) { | 69 | fn check(ra_fixture: &str, expect: Expect) { |
70 | let actual = completion_list(ra_fixture, CompletionKind::Reference); | 70 | let actual = completion_list(ra_fixture, CompletionKind::Reference); |
@@ -141,7 +141,7 @@ mod inner { | |||
141 | private_field: u32, | 141 | private_field: u32, |
142 | pub pub_field: u32, | 142 | pub pub_field: u32, |
143 | pub(crate) crate_field: u32, | 143 | pub(crate) crate_field: u32, |
144 | pub(super) super_field: u32, | 144 | pub(crate) super_field: u32, |
145 | } | 145 | } |
146 | } | 146 | } |
147 | fn foo(a: inner::A) { a.<|> } | 147 | fn foo(a: inner::A) { a.<|> } |
@@ -159,13 +159,13 @@ struct A {} | |||
159 | mod m { | 159 | mod m { |
160 | impl super::A { | 160 | impl super::A { |
161 | fn private_method(&self) {} | 161 | fn private_method(&self) {} |
162 | pub(super) fn the_method(&self) {} | 162 | pub(crate) fn the_method(&self) {} |
163 | } | 163 | } |
164 | } | 164 | } |
165 | fn foo(a: A) { a.<|> } | 165 | fn foo(a: A) { a.<|> } |
166 | "#, | 166 | "#, |
167 | expect![[r#" | 167 | expect![[r#" |
168 | me the_method() pub(super) fn the_method(&self) | 168 | me the_method() pub(crate) fn the_method(&self) |
169 | "#]], | 169 | "#]], |
170 | ); | 170 | ); |
171 | } | 171 | } |
@@ -413,4 +413,19 @@ fn foo() { | |||
413 | "#]], | 413 | "#]], |
414 | ); | 414 | ); |
415 | } | 415 | } |
416 | |||
417 | #[test] | ||
418 | fn completes_method_call_when_receiver_is_a_macro_call() { | ||
419 | check( | ||
420 | r#" | ||
421 | struct S; | ||
422 | impl S { fn foo(&self) {} } | ||
423 | macro_rules! make_s { () => { S }; } | ||
424 | fn main() { make_s!().f<|>; } | ||
425 | "#, | ||
426 | expect![[r#" | ||
427 | me foo() fn foo(&self) | ||
428 | "#]], | ||
429 | ) | ||
430 | } | ||
416 | } | 431 | } |
diff --git a/crates/ide/src/completion/complete_fn_param.rs b/crates/completion/src/completions/fn_param.rs index 9efe25461..e777a53c1 100644 --- a/crates/ide/src/completion/complete_fn_param.rs +++ b/crates/completion/src/completions/fn_param.rs | |||
@@ -6,13 +6,13 @@ use syntax::{ | |||
6 | match_ast, AstNode, | 6 | match_ast, AstNode, |
7 | }; | 7 | }; |
8 | 8 | ||
9 | use crate::completion::{CompletionContext, CompletionItem, CompletionKind, Completions}; | 9 | use crate::{CompletionContext, CompletionItem, CompletionKind, Completions}; |
10 | 10 | ||
11 | /// Complete repeated parameters, both name and type. For example, if all | 11 | /// Complete repeated parameters, both name and type. For example, if all |
12 | /// functions in a file have a `spam: &mut Spam` parameter, a completion with | 12 | /// functions in a file have a `spam: &mut Spam` parameter, a completion with |
13 | /// `spam: &mut Spam` insert text/label and `spam` lookup string will be | 13 | /// `spam: &mut Spam` insert text/label and `spam` lookup string will be |
14 | /// suggested. | 14 | /// suggested. |
15 | pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) { | 15 | pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) { |
16 | if !ctx.is_param { | 16 | if !ctx.is_param { |
17 | return; | 17 | return; |
18 | } | 18 | } |
@@ -68,7 +68,7 @@ pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) | |||
68 | mod tests { | 68 | mod tests { |
69 | use expect_test::{expect, Expect}; | 69 | use expect_test::{expect, Expect}; |
70 | 70 | ||
71 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 71 | use crate::{test_utils::completion_list, CompletionKind}; |
72 | 72 | ||
73 | fn check(ra_fixture: &str, expect: Expect) { | 73 | fn check(ra_fixture: &str, expect: Expect) { |
74 | let actual = completion_list(ra_fixture, CompletionKind::Magic); | 74 | let actual = completion_list(ra_fixture, CompletionKind::Magic); |
diff --git a/crates/ide/src/completion/complete_keyword.rs b/crates/completion/src/completions/keyword.rs index e59747095..c7df15900 100644 --- a/crates/ide/src/completion/complete_keyword.rs +++ b/crates/completion/src/completions/keyword.rs | |||
@@ -1,13 +1,11 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! Completes keywords. |
2 | 2 | ||
3 | use syntax::{ast, SyntaxKind}; | 3 | use syntax::{ast, SyntaxKind}; |
4 | use test_utils::mark; | 4 | use test_utils::mark; |
5 | 5 | ||
6 | use crate::completion::{ | 6 | use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions}; |
7 | CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions, | ||
8 | }; | ||
9 | 7 | ||
10 | pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionContext) { | 8 | pub(crate) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionContext) { |
11 | // complete keyword "crate" in use stmt | 9 | // complete keyword "crate" in use stmt |
12 | let source_range = ctx.source_range(); | 10 | let source_range = ctx.source_range(); |
13 | 11 | ||
@@ -41,7 +39,7 @@ pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionC | |||
41 | } | 39 | } |
42 | } | 40 | } |
43 | 41 | ||
44 | pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) { | 42 | pub(crate) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) { |
45 | if ctx.token.kind() == SyntaxKind::COMMENT { | 43 | if ctx.token.kind() == SyntaxKind::COMMENT { |
46 | mark::hit!(no_keyword_completion_in_comments); | 44 | mark::hit!(no_keyword_completion_in_comments); |
47 | return; | 45 | return; |
@@ -177,7 +175,7 @@ fn complete_return( | |||
177 | mod tests { | 175 | mod tests { |
178 | use expect_test::{expect, Expect}; | 176 | use expect_test::{expect, Expect}; |
179 | 177 | ||
180 | use crate::completion::{ | 178 | use crate::{ |
181 | test_utils::{check_edit, completion_list}, | 179 | test_utils::{check_edit, completion_list}, |
182 | CompletionKind, | 180 | CompletionKind, |
183 | }; | 181 | }; |
diff --git a/crates/ide/src/completion/complete_macro_in_item_position.rs b/crates/completion/src/completions/macro_in_item_position.rs index fc8625d8e..82884a181 100644 --- a/crates/ide/src/completion/complete_macro_in_item_position.rs +++ b/crates/completion/src/completions/macro_in_item_position.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! Completes macro invocations used in item position. |
2 | 2 | ||
3 | use crate::completion::{CompletionContext, Completions}; | 3 | use crate::{CompletionContext, Completions}; |
4 | 4 | ||
5 | pub(super) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &CompletionContext) { | 5 | pub(crate) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &CompletionContext) { |
6 | // Show only macros in top level. | 6 | // Show only macros in top level. |
7 | if ctx.is_new_item { | 7 | if ctx.is_new_item { |
8 | ctx.scope.process_all_names(&mut |name, res| { | 8 | ctx.scope.process_all_names(&mut |name, res| { |
@@ -17,7 +17,7 @@ pub(super) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &Compl | |||
17 | mod tests { | 17 | mod tests { |
18 | use expect_test::{expect, Expect}; | 18 | use expect_test::{expect, Expect}; |
19 | 19 | ||
20 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 20 | use crate::{test_utils::completion_list, CompletionKind}; |
21 | 21 | ||
22 | fn check(ra_fixture: &str, expect: Expect) { | 22 | fn check(ra_fixture: &str, expect: Expect) { |
23 | let actual = completion_list(ra_fixture, CompletionKind::Reference); | 23 | let actual = completion_list(ra_fixture, CompletionKind::Reference); |
diff --git a/crates/ide/src/completion/complete_mod.rs b/crates/completion/src/completions/mod_.rs index c7a99bdc3..c96f84171 100644 --- a/crates/ide/src/completion/complete_mod.rs +++ b/crates/completion/src/completions/mod_.rs | |||
@@ -1,19 +1,16 @@ | |||
1 | //! Completes mod declarations. | 1 | //! Completes mod declarations. |
2 | 2 | ||
3 | use base_db::{SourceDatabaseExt, VfsPath}; | ||
4 | use hir::{Module, ModuleSource}; | 3 | use hir::{Module, ModuleSource}; |
4 | use ide_db::base_db::{SourceDatabaseExt, VfsPath}; | ||
5 | use ide_db::RootDatabase; | 5 | use ide_db::RootDatabase; |
6 | use rustc_hash::FxHashSet; | 6 | use rustc_hash::FxHashSet; |
7 | 7 | ||
8 | use crate::{CompletionItem, CompletionItemKind}; | 8 | use crate::{CompletionItem, CompletionItemKind}; |
9 | 9 | ||
10 | use super::{ | 10 | use crate::{context::CompletionContext, item::CompletionKind, Completions}; |
11 | completion_context::CompletionContext, completion_item::CompletionKind, | ||
12 | completion_item::Completions, | ||
13 | }; | ||
14 | 11 | ||
15 | /// Complete mod declaration, i.e. `mod <|> ;` | 12 | /// Complete mod declaration, i.e. `mod <|> ;` |
16 | pub(super) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { | 13 | pub(crate) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { |
17 | let mod_under_caret = match &ctx.mod_declaration_under_caret { | 14 | let mod_under_caret = match &ctx.mod_declaration_under_caret { |
18 | Some(mod_under_caret) if mod_under_caret.item_list().is_some() => return None, | 15 | Some(mod_under_caret) if mod_under_caret.item_list().is_some() => return None, |
19 | Some(mod_under_caret) => mod_under_caret, | 16 | Some(mod_under_caret) => mod_under_caret, |
@@ -78,10 +75,9 @@ pub(super) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Op | |||
78 | if mod_under_caret.semicolon_token().is_none() { | 75 | if mod_under_caret.semicolon_token().is_none() { |
79 | label.push(';') | 76 | label.push(';') |
80 | } | 77 | } |
81 | acc.add( | 78 | CompletionItem::new(CompletionKind::Magic, ctx.source_range(), &label) |
82 | CompletionItem::new(CompletionKind::Magic, ctx.source_range(), &label) | 79 | .kind(CompletionItemKind::Module) |
83 | .kind(CompletionItemKind::Module), | 80 | .add_to(acc) |
84 | ) | ||
85 | }); | 81 | }); |
86 | 82 | ||
87 | Some(()) | 83 | Some(()) |
@@ -150,7 +146,7 @@ fn module_chain_to_containing_module_file( | |||
150 | 146 | ||
151 | #[cfg(test)] | 147 | #[cfg(test)] |
152 | mod tests { | 148 | mod tests { |
153 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 149 | use crate::{test_utils::completion_list, CompletionKind}; |
154 | use expect_test::{expect, Expect}; | 150 | use expect_test::{expect, Expect}; |
155 | 151 | ||
156 | fn check(ra_fixture: &str, expect: Expect) { | 152 | fn check(ra_fixture: &str, expect: Expect) { |
diff --git a/crates/ide/src/completion/complete_pattern.rs b/crates/completion/src/completions/pattern.rs index 5a13574d4..7ab7f09fe 100644 --- a/crates/ide/src/completion/complete_pattern.rs +++ b/crates/completion/src/completions/pattern.rs | |||
@@ -1,9 +1,9 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! Completes constats and paths in patterns. |
2 | 2 | ||
3 | use crate::completion::{CompletionContext, Completions}; | 3 | use crate::{CompletionContext, Completions}; |
4 | 4 | ||
5 | /// Completes constats and paths in patterns. | 5 | /// Completes constats and paths in patterns. |
6 | pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) { | 6 | pub(crate) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) { |
7 | if !ctx.is_pat_binding_or_const { | 7 | if !ctx.is_pat_binding_or_const { |
8 | return; | 8 | return; |
9 | } | 9 | } |
@@ -35,7 +35,7 @@ pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) { | |||
35 | mod tests { | 35 | mod tests { |
36 | use expect_test::{expect, Expect}; | 36 | use expect_test::{expect, Expect}; |
37 | 37 | ||
38 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 38 | use crate::{test_utils::completion_list, CompletionKind}; |
39 | 39 | ||
40 | fn check(ra_fixture: &str, expect: Expect) { | 40 | fn check(ra_fixture: &str, expect: Expect) { |
41 | let actual = completion_list(ra_fixture, CompletionKind::Reference); | 41 | let actual = completion_list(ra_fixture, CompletionKind::Reference); |
diff --git a/crates/ide/src/completion/complete_postfix.rs b/crates/completion/src/completions/postfix.rs index db5319618..348f017bd 100644 --- a/crates/ide/src/completion/complete_postfix.rs +++ b/crates/completion/src/completions/postfix.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! Postfix completions, like `Ok(10).ifl<|>` => `if let Ok() = Ok(10) { <|> }`. |
2 | 2 | ||
3 | mod format_like; | 3 | mod format_like; |
4 | 4 | ||
5 | use assists::utils::TryEnum; | 5 | use ide_db::ty_filter::TryEnum; |
6 | use syntax::{ | 6 | use syntax::{ |
7 | ast::{self, AstNode, AstToken}, | 7 | ast::{self, AstNode, AstToken}, |
8 | TextRange, TextSize, | 8 | TextRange, TextSize, |
@@ -11,15 +11,13 @@ use text_edit::TextEdit; | |||
11 | 11 | ||
12 | use self::format_like::add_format_like_completions; | 12 | use self::format_like::add_format_like_completions; |
13 | use crate::{ | 13 | use crate::{ |
14 | completion::{ | 14 | config::SnippetCap, |
15 | completion_config::SnippetCap, | 15 | context::CompletionContext, |
16 | completion_context::CompletionContext, | 16 | item::{Builder, CompletionKind}, |
17 | completion_item::{Builder, CompletionKind, Completions}, | 17 | CompletionItem, CompletionItemKind, Completions, |
18 | }, | ||
19 | CompletionItem, CompletionItemKind, | ||
20 | }; | 18 | }; |
21 | 19 | ||
22 | pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | 20 | pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { |
23 | if !ctx.config.enable_postfix_completions { | 21 | if !ctx.config.enable_postfix_completions { |
24 | return; | 22 | return; |
25 | } | 23 | } |
@@ -263,7 +261,7 @@ fn postfix_snippet( | |||
263 | mod tests { | 261 | mod tests { |
264 | use expect_test::{expect, Expect}; | 262 | use expect_test::{expect, Expect}; |
265 | 263 | ||
266 | use crate::completion::{ | 264 | use crate::{ |
267 | test_utils::{check_edit, completion_list}, | 265 | test_utils::{check_edit, completion_list}, |
268 | CompletionKind, | 266 | CompletionKind, |
269 | }; | 267 | }; |
diff --git a/crates/ide/src/completion/complete_postfix/format_like.rs b/crates/completion/src/completions/postfix/format_like.rs index 50d1e5c81..f35114ed1 100644 --- a/crates/ide/src/completion/complete_postfix/format_like.rs +++ b/crates/completion/src/completions/postfix/format_like.rs | |||
@@ -14,9 +14,9 @@ | |||
14 | // + `logw` -> `log::warn!(...)` | 14 | // + `logw` -> `log::warn!(...)` |
15 | // + `loge` -> `log::error!(...)` | 15 | // + `loge` -> `log::error!(...)` |
16 | 16 | ||
17 | use crate::completion::{ | 17 | use crate::{ |
18 | complete_postfix::postfix_snippet, completion_config::SnippetCap, | 18 | completions::postfix::postfix_snippet, config::SnippetCap, context::CompletionContext, |
19 | completion_context::CompletionContext, completion_item::Completions, | 19 | Completions, |
20 | }; | 20 | }; |
21 | use syntax::ast::{self, AstToken}; | 21 | use syntax::ast::{self, AstToken}; |
22 | 22 | ||
@@ -33,7 +33,7 @@ static KINDS: &[(&str, &str)] = &[ | |||
33 | ("loge", "log::error!"), | 33 | ("loge", "log::error!"), |
34 | ]; | 34 | ]; |
35 | 35 | ||
36 | pub(super) fn add_format_like_completions( | 36 | pub(crate) fn add_format_like_completions( |
37 | acc: &mut Completions, | 37 | acc: &mut Completions, |
38 | ctx: &CompletionContext, | 38 | ctx: &CompletionContext, |
39 | dot_receiver: &ast::Expr, | 39 | dot_receiver: &ast::Expr, |
@@ -70,7 +70,7 @@ fn string_literal_contents(item: &ast::String) -> Option<String> { | |||
70 | /// Parser for a format-like string. It is more allowing in terms of string contents, | 70 | /// Parser for a format-like string. It is more allowing in terms of string contents, |
71 | /// as we expect variable placeholders to be filled with expressions. | 71 | /// as we expect variable placeholders to be filled with expressions. |
72 | #[derive(Debug)] | 72 | #[derive(Debug)] |
73 | pub struct FormatStrParser { | 73 | pub(crate) struct FormatStrParser { |
74 | input: String, | 74 | input: String, |
75 | output: String, | 75 | output: String, |
76 | extracted_expressions: Vec<String>, | 76 | extracted_expressions: Vec<String>, |
diff --git a/crates/ide/src/completion/complete_qualified_path.rs b/crates/completion/src/completions/qualified_path.rs index 2fafedd47..d9387054d 100644 --- a/crates/ide/src/completion/complete_qualified_path.rs +++ b/crates/completion/src/completions/qualified_path.rs | |||
@@ -5,9 +5,9 @@ use rustc_hash::FxHashSet; | |||
5 | use syntax::AstNode; | 5 | use syntax::AstNode; |
6 | use test_utils::mark; | 6 | use test_utils::mark; |
7 | 7 | ||
8 | use crate::completion::{CompletionContext, Completions}; | 8 | use crate::{CompletionContext, Completions}; |
9 | 9 | ||
10 | pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) { | 10 | pub(crate) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) { |
11 | let path = match &ctx.path_qual { | 11 | let path = match &ctx.path_qual { |
12 | Some(path) => path.clone(), | 12 | Some(path) => path.clone(), |
13 | None => return, | 13 | None => return, |
@@ -149,7 +149,7 @@ mod tests { | |||
149 | use expect_test::{expect, Expect}; | 149 | use expect_test::{expect, Expect}; |
150 | use test_utils::mark; | 150 | use test_utils::mark; |
151 | 151 | ||
152 | use crate::completion::{ | 152 | use crate::{ |
153 | test_utils::{check_edit, completion_list}, | 153 | test_utils::{check_edit, completion_list}, |
154 | CompletionKind, | 154 | CompletionKind, |
155 | }; | 155 | }; |
@@ -369,11 +369,11 @@ struct S; | |||
369 | 369 | ||
370 | mod m { | 370 | mod m { |
371 | impl super::S { | 371 | impl super::S { |
372 | pub(super) fn public_method() { } | 372 | pub(crate) fn public_method() { } |
373 | fn private_method() { } | 373 | fn private_method() { } |
374 | pub(super) type PublicType = u32; | 374 | pub(crate) type PublicType = u32; |
375 | type PrivateType = u32; | 375 | type PrivateType = u32; |
376 | pub(super) const PUBLIC_CONST: u32 = 1; | 376 | pub(crate) const PUBLIC_CONST: u32 = 1; |
377 | const PRIVATE_CONST: u32 = 1; | 377 | const PRIVATE_CONST: u32 = 1; |
378 | } | 378 | } |
379 | } | 379 | } |
@@ -381,9 +381,9 @@ mod m { | |||
381 | fn foo() { let _ = S::<|> } | 381 | fn foo() { let _ = S::<|> } |
382 | "#, | 382 | "#, |
383 | expect![[r#" | 383 | expect![[r#" |
384 | ct PUBLIC_CONST pub(super) const PUBLIC_CONST: u32 = 1; | 384 | ct PUBLIC_CONST pub(crate) const PUBLIC_CONST: u32 = 1; |
385 | ta PublicType pub(super) type PublicType = u32; | 385 | ta PublicType pub(crate) type PublicType = u32; |
386 | fn public_method() pub(super) fn public_method() | 386 | fn public_method() pub(crate) fn public_method() |
387 | "#]], | 387 | "#]], |
388 | ); | 388 | ); |
389 | } | 389 | } |
diff --git a/crates/ide/src/completion/complete_record.rs b/crates/completion/src/completions/record.rs index ceb8d16c1..0f611084b 100644 --- a/crates/ide/src/completion/complete_record.rs +++ b/crates/completion/src/completions/record.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | //! Complete fields in record literals and patterns. | 1 | //! Complete fields in record literals and patterns. |
2 | use crate::completion::{CompletionContext, Completions}; | 2 | use crate::{CompletionContext, Completions}; |
3 | 3 | ||
4 | pub(super) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { | 4 | pub(crate) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { |
5 | let missing_fields = match (ctx.record_pat_syntax.as_ref(), ctx.record_lit_syntax.as_ref()) { | 5 | let missing_fields = match (ctx.record_pat_syntax.as_ref(), ctx.record_lit_syntax.as_ref()) { |
6 | (None, None) => return None, | 6 | (None, None) => return None, |
7 | (Some(_), Some(_)) => unreachable!("A record cannot be both a literal and a pattern"), | 7 | (Some(_), Some(_)) => unreachable!("A record cannot be both a literal and a pattern"), |
@@ -20,7 +20,7 @@ pub(super) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> | |||
20 | mod tests { | 20 | mod tests { |
21 | use expect_test::{expect, Expect}; | 21 | use expect_test::{expect, Expect}; |
22 | 22 | ||
23 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 23 | use crate::{test_utils::completion_list, CompletionKind}; |
24 | 24 | ||
25 | fn check(ra_fixture: &str, expect: Expect) { | 25 | fn check(ra_fixture: &str, expect: Expect) { |
26 | let actual = completion_list(ra_fixture, CompletionKind::Reference); | 26 | let actual = completion_list(ra_fixture, CompletionKind::Reference); |
diff --git a/crates/ide/src/completion/complete_snippet.rs b/crates/completion/src/completions/snippet.rs index 4837d2910..6f0c00078 100644 --- a/crates/ide/src/completion/complete_snippet.rs +++ b/crates/completion/src/completions/snippet.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! This file provides snippet completions, like `pd` => `eprintln!(...)`. |
2 | 2 | ||
3 | use crate::completion::{ | 3 | use crate::{ |
4 | completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem, | 4 | config::SnippetCap, item::Builder, CompletionContext, CompletionItem, CompletionItemKind, |
5 | CompletionItemKind, CompletionKind, Completions, | 5 | CompletionKind, Completions, |
6 | }; | 6 | }; |
7 | 7 | ||
8 | fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder { | 8 | fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder { |
@@ -11,7 +11,7 @@ fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) | |||
11 | .kind(CompletionItemKind::Snippet) | 11 | .kind(CompletionItemKind::Snippet) |
12 | } | 12 | } |
13 | 13 | ||
14 | pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) { | 14 | pub(crate) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) { |
15 | if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) { | 15 | if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) { |
16 | return; | 16 | return; |
17 | } | 17 | } |
@@ -24,7 +24,7 @@ pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionConte | |||
24 | snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc); | 24 | snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc); |
25 | } | 25 | } |
26 | 26 | ||
27 | pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) { | 27 | pub(crate) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) { |
28 | if !ctx.is_new_item { | 28 | if !ctx.is_new_item { |
29 | return; | 29 | return; |
30 | } | 30 | } |
@@ -71,7 +71,7 @@ fn ${1:feature}() { | |||
71 | mod tests { | 71 | mod tests { |
72 | use expect_test::{expect, Expect}; | 72 | use expect_test::{expect, Expect}; |
73 | 73 | ||
74 | use crate::completion::{test_utils::completion_list, CompletionKind}; | 74 | use crate::{test_utils::completion_list, CompletionKind}; |
75 | 75 | ||
76 | fn check(ra_fixture: &str, expect: Expect) { | 76 | fn check(ra_fixture: &str, expect: Expect) { |
77 | let actual = completion_list(ra_fixture, CompletionKind::Snippet); | 77 | let actual = completion_list(ra_fixture, CompletionKind::Snippet); |
diff --git a/crates/ide/src/completion/complete_trait_impl.rs b/crates/completion/src/completions/trait_impl.rs index ff115df92..a14be9c73 100644 --- a/crates/ide/src/completion/complete_trait_impl.rs +++ b/crates/completion/src/completions/trait_impl.rs | |||
@@ -31,19 +31,22 @@ | |||
31 | //! } | 31 | //! } |
32 | //! ``` | 32 | //! ``` |
33 | 33 | ||
34 | use assists::utils::get_missing_assoc_items; | ||
35 | use hir::{self, HasAttrs, HasSource}; | 34 | use hir::{self, HasAttrs, HasSource}; |
35 | use ide_db::traits::get_missing_assoc_items; | ||
36 | use syntax::{ | 36 | use syntax::{ |
37 | ast::{self, edit, Impl}, | 37 | ast::{self, edit, Impl}, |
38 | display::function_declaration, | ||
38 | AstNode, SyntaxKind, SyntaxNode, TextRange, T, | 39 | AstNode, SyntaxKind, SyntaxNode, TextRange, T, |
39 | }; | 40 | }; |
40 | use text_edit::TextEdit; | 41 | use text_edit::TextEdit; |
41 | 42 | ||
42 | use crate::{ | 43 | use crate::{ |
43 | completion::{ | 44 | CompletionContext, |
44 | CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions, | 45 | CompletionItem, |
45 | }, | 46 | CompletionItemKind, |
46 | display::function_declaration, | 47 | CompletionKind, |
48 | Completions, | ||
49 | // display::function_declaration, | ||
47 | }; | 50 | }; |
48 | 51 | ||
49 | #[derive(Debug, PartialEq, Eq)] | 52 | #[derive(Debug, PartialEq, Eq)] |
@@ -237,7 +240,7 @@ fn make_const_compl_syntax(const_: &ast::Const) -> String { | |||
237 | mod tests { | 240 | mod tests { |
238 | use expect_test::{expect, Expect}; | 241 | use expect_test::{expect, Expect}; |
239 | 242 | ||
240 | use crate::completion::{ | 243 | use crate::{ |
241 | test_utils::{check_edit, completion_list}, | 244 | test_utils::{check_edit, completion_list}, |
242 | CompletionKind, | 245 | CompletionKind, |
243 | }; | 246 | }; |
diff --git a/crates/ide/src/completion/complete_unqualified_path.rs b/crates/completion/src/completions/unqualified_path.rs index 8b6757195..7df58e1da 100644 --- a/crates/ide/src/completion/complete_unqualified_path.rs +++ b/crates/completion/src/completions/unqualified_path.rs | |||
@@ -4,9 +4,9 @@ use hir::{Adt, ModuleDef, ScopeDef, Type}; | |||
4 | use syntax::AstNode; | 4 | use syntax::AstNode; |
5 | use test_utils::mark; | 5 | use test_utils::mark; |
6 | 6 | ||
7 | use crate::completion::{CompletionContext, Completions}; | 7 | use crate::{CompletionContext, Completions}; |
8 | 8 | ||
9 | pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) { | 9 | pub(crate) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) { |
10 | if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) { | 10 | if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) { |
11 | return; | 11 | return; |
12 | } | 12 | } |
@@ -68,7 +68,7 @@ mod tests { | |||
68 | use expect_test::{expect, Expect}; | 68 | use expect_test::{expect, Expect}; |
69 | use test_utils::mark; | 69 | use test_utils::mark; |
70 | 70 | ||
71 | use crate::completion::{ | 71 | use crate::{ |
72 | test_utils::{check_edit, completion_list}, | 72 | test_utils::{check_edit, completion_list}, |
73 | CompletionKind, | 73 | CompletionKind, |
74 | }; | 74 | }; |
diff --git a/crates/ide/src/completion/completion_config.rs b/crates/completion/src/config.rs index 71b49ace8..71b49ace8 100644 --- a/crates/ide/src/completion/completion_config.rs +++ b/crates/completion/src/config.rs | |||
diff --git a/crates/ide/src/completion/completion_context.rs b/crates/completion/src/context.rs index 8dea8a4bf..dca304a8f 100644 --- a/crates/ide/src/completion/completion_context.rs +++ b/crates/completion/src/context.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! See `CompletionContext` structure. |
2 | 2 | ||
3 | use base_db::SourceDatabase; | ||
4 | use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type}; | 3 | use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type}; |
5 | use ide_db::RootDatabase; | 4 | use ide_db::base_db::{FilePosition, SourceDatabase}; |
5 | use ide_db::{call_info::ActiveParameter, RootDatabase}; | ||
6 | use syntax::{ | 6 | use syntax::{ |
7 | algo::{find_covering_element, find_node_at_offset}, | 7 | algo::{find_covering_element, find_node_at_offset}, |
8 | ast, match_ast, AstNode, NodeOrToken, | 8 | ast, match_ast, AstNode, NodeOrToken, |
@@ -13,17 +13,14 @@ use test_utils::mark; | |||
13 | use text_edit::Indel; | 13 | use text_edit::Indel; |
14 | 14 | ||
15 | use crate::{ | 15 | use crate::{ |
16 | call_info::ActiveParameter, | 16 | patterns::{ |
17 | completion::{ | 17 | fn_is_prev, for_is_prev2, has_bind_pat_parent, has_block_expr_parent, |
18 | patterns::{ | 18 | has_field_list_parent, has_impl_as_prev_sibling, has_impl_parent, |
19 | has_bind_pat_parent, has_block_expr_parent, has_field_list_parent, | 19 | has_item_list_or_source_file_parent, has_ref_parent, has_trait_as_prev_sibling, |
20 | has_impl_as_prev_sibling, has_impl_parent, has_item_list_or_source_file_parent, | 20 | has_trait_parent, if_is_prev, inside_impl_trait_block, is_in_loop_body, is_match_arm, |
21 | has_ref_parent, has_trait_as_prev_sibling, has_trait_parent, if_is_prev, | 21 | unsafe_is_prev, |
22 | is_in_loop_body, is_match_arm, unsafe_is_prev, | ||
23 | }, | ||
24 | CompletionConfig, | ||
25 | }, | 22 | }, |
26 | FilePosition, | 23 | CompletionConfig, |
27 | }; | 24 | }; |
28 | 25 | ||
29 | /// `CompletionContext` is created early during completion to figure out, where | 26 | /// `CompletionContext` is created early during completion to figure out, where |
@@ -86,11 +83,14 @@ pub(crate) struct CompletionContext<'a> { | |||
86 | pub(super) in_loop_body: bool, | 83 | pub(super) in_loop_body: bool, |
87 | pub(super) has_trait_parent: bool, | 84 | pub(super) has_trait_parent: bool, |
88 | pub(super) has_impl_parent: bool, | 85 | pub(super) has_impl_parent: bool, |
86 | pub(super) inside_impl_trait_block: bool, | ||
89 | pub(super) has_field_list_parent: bool, | 87 | pub(super) has_field_list_parent: bool, |
90 | pub(super) trait_as_prev_sibling: bool, | 88 | pub(super) trait_as_prev_sibling: bool, |
91 | pub(super) impl_as_prev_sibling: bool, | 89 | pub(super) impl_as_prev_sibling: bool, |
92 | pub(super) is_match_arm: bool, | 90 | pub(super) is_match_arm: bool, |
93 | pub(super) has_item_list_or_source_file_parent: bool, | 91 | pub(super) has_item_list_or_source_file_parent: bool, |
92 | pub(super) for_is_prev2: bool, | ||
93 | pub(super) fn_is_prev: bool, | ||
94 | pub(super) locals: Vec<(String, Local)>, | 94 | pub(super) locals: Vec<(String, Local)>, |
95 | } | 95 | } |
96 | 96 | ||
@@ -168,12 +168,15 @@ impl<'a> CompletionContext<'a> { | |||
168 | block_expr_parent: false, | 168 | block_expr_parent: false, |
169 | has_trait_parent: false, | 169 | has_trait_parent: false, |
170 | has_impl_parent: false, | 170 | has_impl_parent: false, |
171 | inside_impl_trait_block: false, | ||
171 | has_field_list_parent: false, | 172 | has_field_list_parent: false, |
172 | trait_as_prev_sibling: false, | 173 | trait_as_prev_sibling: false, |
173 | impl_as_prev_sibling: false, | 174 | impl_as_prev_sibling: false, |
174 | if_is_prev: false, | 175 | if_is_prev: false, |
175 | is_match_arm: false, | 176 | is_match_arm: false, |
176 | has_item_list_or_source_file_parent: false, | 177 | has_item_list_or_source_file_parent: false, |
178 | for_is_prev2: false, | ||
179 | fn_is_prev: false, | ||
177 | locals, | 180 | locals, |
178 | }; | 181 | }; |
179 | 182 | ||
@@ -221,6 +224,15 @@ impl<'a> CompletionContext<'a> { | |||
221 | Some(ctx) | 224 | Some(ctx) |
222 | } | 225 | } |
223 | 226 | ||
227 | /// Checks whether completions in that particular case don't make much sense. | ||
228 | /// Examples: | ||
229 | /// - `fn <|>` -- we expect function name, it's unlikely that "hint" will be helpful. | ||
230 | /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names. | ||
231 | /// - `for _ i<|>` -- obviously, it'll be "in" keyword. | ||
232 | pub(crate) fn no_completion_required(&self) -> bool { | ||
233 | (self.fn_is_prev && !self.inside_impl_trait_block) || self.for_is_prev2 | ||
234 | } | ||
235 | |||
224 | /// The range of the identifier that is being completed. | 236 | /// The range of the identifier that is being completed. |
225 | pub(crate) fn source_range(&self) -> TextRange { | 237 | pub(crate) fn source_range(&self) -> TextRange { |
226 | // check kind of macro-expanded token, but use range of original token | 238 | // check kind of macro-expanded token, but use range of original token |
@@ -233,6 +245,19 @@ impl<'a> CompletionContext<'a> { | |||
233 | } | 245 | } |
234 | } | 246 | } |
235 | 247 | ||
248 | pub(crate) fn active_name_and_type(&self) -> Option<(String, Type)> { | ||
249 | if let Some(record_field) = &self.record_field_syntax { | ||
250 | mark::hit!(record_field_type_match); | ||
251 | let (struct_field, _local) = self.sema.resolve_record_field(record_field)?; | ||
252 | Some((struct_field.name(self.db).to_string(), struct_field.signature_ty(self.db))) | ||
253 | } else if let Some(active_parameter) = &self.active_parameter { | ||
254 | mark::hit!(active_param_type_match); | ||
255 | Some((active_parameter.name.clone(), active_parameter.ty.clone())) | ||
256 | } else { | ||
257 | None | ||
258 | } | ||
259 | } | ||
260 | |||
236 | fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) { | 261 | fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) { |
237 | let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap(); | 262 | let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap(); |
238 | let syntax_element = NodeOrToken::Token(fake_ident_token); | 263 | let syntax_element = NodeOrToken::Token(fake_ident_token); |
@@ -244,6 +269,7 @@ impl<'a> CompletionContext<'a> { | |||
244 | self.in_loop_body = is_in_loop_body(syntax_element.clone()); | 269 | self.in_loop_body = is_in_loop_body(syntax_element.clone()); |
245 | self.has_trait_parent = has_trait_parent(syntax_element.clone()); | 270 | self.has_trait_parent = has_trait_parent(syntax_element.clone()); |
246 | self.has_impl_parent = has_impl_parent(syntax_element.clone()); | 271 | self.has_impl_parent = has_impl_parent(syntax_element.clone()); |
272 | self.inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone()); | ||
247 | self.has_field_list_parent = has_field_list_parent(syntax_element.clone()); | 273 | self.has_field_list_parent = has_field_list_parent(syntax_element.clone()); |
248 | self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone()); | 274 | self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone()); |
249 | self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone()); | 275 | self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone()); |
@@ -253,6 +279,8 @@ impl<'a> CompletionContext<'a> { | |||
253 | self.mod_declaration_under_caret = | 279 | self.mod_declaration_under_caret = |
254 | find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset) | 280 | find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset) |
255 | .filter(|module| module.item_list().is_none()); | 281 | .filter(|module| module.item_list().is_none()); |
282 | self.for_is_prev2 = for_is_prev2(syntax_element.clone()); | ||
283 | self.fn_is_prev = fn_is_prev(syntax_element.clone()); | ||
256 | } | 284 | } |
257 | 285 | ||
258 | fn fill( | 286 | fn fill( |
diff --git a/crates/completion/src/generated_lint_completions.rs b/crates/completion/src/generated_lint_completions.rs new file mode 100644 index 000000000..87df7f1c9 --- /dev/null +++ b/crates/completion/src/generated_lint_completions.rs | |||
@@ -0,0 +1,5 @@ | |||
1 | //! Generated file, do not edit by hand, see `xtask/src/codegen` | ||
2 | |||
3 | use crate::completions::attribute::LintCompletion; | ||
4 | pub (super) const FEATURES : & [LintCompletion] = & [LintCompletion { label : "non_ascii_idents" , description : "# `non_ascii_idents`\n\nThe tracking issue for this feature is: [#55467]\n\n[#55467]: https://github.com/rust-lang/rust/issues/55467\n\n------------------------\n\nThe `non_ascii_idents` feature adds support for non-ASCII identifiers.\n\n## Examples\n\n```rust\n#![feature(non_ascii_idents)]\n\nconst ε: f64 = 0.00001f64;\nconst Π: f64 = 3.14f64;\n```\n\n## Changes to the language reference\n\n> **<sup>Lexer:<sup>** \n> IDENTIFIER : \n> XID_start XID_continue<sup>\\*</sup> \n> | `_` XID_continue<sup>+</sup> \n\nAn identifier is any nonempty Unicode string of the following form:\n\nEither\n\n * The first character has property [`XID_start`]\n * The remaining characters have property [`XID_continue`]\n\nOr\n\n * The first character is `_`\n * The identifier is more than one character, `_` alone is not an identifier\n * The remaining characters have property [`XID_continue`]\n\nthat does _not_ occur in the set of [strict keywords].\n\n> **Note**: [`XID_start`] and [`XID_continue`] as character properties cover the\n> character ranges used to form the more familiar C and Java language-family\n> identifiers.\n\n[`XID_start`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=\n[`XID_continue`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=\n[strict keywords]: ../../reference/keywords.md#strict-keywords\n" } , LintCompletion { label : "custom_test_frameworks" , description : "# `custom_test_frameworks`\n\nThe tracking issue for this feature is: [#50297]\n\n[#50297]: https://github.com/rust-lang/rust/issues/50297\n\n------------------------\n\nThe `custom_test_frameworks` feature allows the use of `#[test_case]` and `#![test_runner]`.\nAny function, const, or static can be annotated with `#[test_case]` causing it to be aggregated (like `#[test]`)\nand be passed to the test runner determined by the `#![test_runner]` crate attribute.\n\n```rust\n#![feature(custom_test_frameworks)]\n#![test_runner(my_runner)]\n\nfn my_runner(tests: &[&i32]) {\n for t in tests {\n if **t == 0 {\n println!(\"PASSED\");\n } else {\n println!(\"FAILED\");\n }\n }\n}\n\n#[test_case]\nconst WILL_PASS: i32 = 0;\n\n#[test_case]\nconst WILL_FAIL: i32 = 4;\n```\n\n" } , LintCompletion { label : "abi_msp430_interrupt" , description : "# `abi_msp430_interrupt`\n\nThe tracking issue for this feature is: [#38487]\n\n[#38487]: https://github.com/rust-lang/rust/issues/38487\n\n------------------------\n\nIn the MSP430 architecture, interrupt handlers have a special calling\nconvention. You can use the `\"msp430-interrupt\"` ABI to make the compiler apply\nthe right calling convention to the interrupt handlers you define.\n\n<!-- NOTE(ignore) this example is specific to the msp430 target -->\n\n``` rust,ignore\n#![feature(abi_msp430_interrupt)]\n#![no_std]\n\n// Place the interrupt handler at the appropriate memory address\n// (Alternatively, you can use `#[used]` and remove `pub` and `#[no_mangle]`)\n#[link_section = \"__interrupt_vector_10\"]\n#[no_mangle]\npub static TIM0_VECTOR: extern \"msp430-interrupt\" fn() = tim0;\n\n// The interrupt handler\nextern \"msp430-interrupt\" fn tim0() {\n // ..\n}\n```\n\n``` text\n$ msp430-elf-objdump -CD ./target/msp430/release/app\nDisassembly of section __interrupt_vector_10:\n\n0000fff2 <TIM0_VECTOR>:\n fff2: 00 c0 interrupt service routine at 0xc000\n\nDisassembly of section .text:\n\n0000c000 <int::tim0>:\n c000: 00 13 reti\n```\n" } , LintCompletion { label : "link_args" , description : "# `link_args`\n\nThe tracking issue for this feature is: [#29596]\n\n[#29596]: https://github.com/rust-lang/rust/issues/29596\n\n------------------------\n\nYou can tell `rustc` how to customize linking, and that is via the `link_args`\nattribute. This attribute is applied to `extern` blocks and specifies raw flags\nwhich need to get passed to the linker when producing an artifact. An example\nusage would be:\n\n```rust,no_run\n#![feature(link_args)]\n\n#[link_args = \"-foo -bar -baz\"]\nextern {}\n# fn main() {}\n```\n\nNote that this feature is currently hidden behind the `feature(link_args)` gate\nbecause this is not a sanctioned way of performing linking. Right now `rustc`\nshells out to the system linker (`gcc` on most systems, `link.exe` on MSVC), so\nit makes sense to provide extra command line arguments, but this will not\nalways be the case. In the future `rustc` may use LLVM directly to link native\nlibraries, in which case `link_args` will have no meaning. You can achieve the\nsame effect as the `link_args` attribute with the `-C link-args` argument to\n`rustc`.\n\nIt is highly recommended to *not* use this attribute, and rather use the more\nformal `#[link(...)]` attribute on `extern` blocks instead.\n" } , LintCompletion { label : "const_eval_limit" , description : "# `const_eval_limit`\n\nThe tracking issue for this feature is: [#67217]\n\n[#67217]: https://github.com/rust-lang/rust/issues/67217\n\nThe `const_eval_limit` allows someone to limit the evaluation steps the CTFE undertakes to evaluate a `const fn`.\n" } , LintCompletion { label : "marker_trait_attr" , description : "# `marker_trait_attr`\n\nThe tracking issue for this feature is: [#29864]\n\n[#29864]: https://github.com/rust-lang/rust/issues/29864\n\n------------------------\n\nNormally, Rust keeps you from adding trait implementations that could\noverlap with each other, as it would be ambiguous which to use. This\nfeature, however, carves out an exception to that rule: a trait can\nopt-in to having overlapping implementations, at the cost that those\nimplementations are not allowed to override anything (and thus the\ntrait itself cannot have any associated items, as they're pointless\nwhen they'd need to do the same thing for every type anyway).\n\n```rust\n#![feature(marker_trait_attr)]\n\n#[marker] trait CheapToClone: Clone {}\n\nimpl<T: Copy> CheapToClone for T {}\n\n// These could potentially overlap with the blanket implementation above,\n// so are only allowed because CheapToClone is a marker trait.\nimpl<T: CheapToClone, U: CheapToClone> CheapToClone for (T, U) {}\nimpl<T: CheapToClone> CheapToClone for std::ops::Range<T> {}\n\nfn cheap_clone<T: CheapToClone>(t: T) -> T {\n t.clone()\n}\n```\n\nThis is expected to replace the unstable `overlapping_marker_traits`\nfeature, which applied to all empty traits (without needing an opt-in).\n" } , LintCompletion { label : "ffi_const" , description : "# `ffi_const`\n\nThe tracking issue for this feature is: [#58328]\n\n------\n\nThe `#[ffi_const]` attribute applies clang's `const` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_const]` functions shall have no effects except for its return\nvalue, which can only depend on the values of the function parameters, and is\nnot affected by changes to the observable state of the program.\n\nApplying the `#[ffi_const]` attribute to a function that violates these\nrequirements is undefined behaviour.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination, and it can avoid emitting some calls in repeated invocations of the\nfunction with the same argument values regardless of other operations being\nperformed in between these functions calls (as opposed to `#[ffi_pure]`\nfunctions).\n\n## Pitfalls\n\nA `#[ffi_const]` function can only read global memory that would not affect\nits return value for the whole execution of the program (e.g. immutable global\nmemory). `#[ffi_const]` functions are referentially-transparent and therefore\nmore strict than `#[ffi_pure]` functions.\n\nA common pitfall involves applying the `#[ffi_const]` attribute to a\nfunction that reads memory through pointer arguments which do not necessarily\npoint to immutable global memory.\n\nA `#[ffi_const]` function that returns unit has no effect on the abstract\nmachine's state, and a `#[ffi_const]` function cannot be `#[ffi_pure]`.\n\nA `#[ffi_const]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `const` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`const` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_const]`.\n\n[#58328]: https://github.com/rust-lang/rust/issues/58328\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacgigch.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_const.htm\n" } , LintCompletion { label : "doc_spotlight" , description : "# `doc_spotlight`\n\nThe tracking issue for this feature is: [#45040]\n\nThe `doc_spotlight` feature allows the use of the `spotlight` parameter to the `#[doc]` attribute,\nto \"spotlight\" a specific trait on the return values of functions. Adding a `#[doc(spotlight)]`\nattribute to a trait definition will make rustdoc print extra information for functions which return\na type that implements that trait. This attribute is applied to the `Iterator`, `io::Read`, and\n`io::Write` traits in the standard library.\n\nYou can do this on your own traits, like this:\n\n```\n#![feature(doc_spotlight)]\n\n#[doc(spotlight)]\npub trait MyTrait {}\n\npub struct MyStruct;\nimpl MyTrait for MyStruct {}\n\n/// The docs for this function will have an extra line about `MyStruct` implementing `MyTrait`,\n/// without having to write that yourself!\npub fn my_fn() -> MyStruct { MyStruct }\n```\n\nThis feature was originally implemented in PR [#45039].\n\n[#45040]: https://github.com/rust-lang/rust/issues/45040\n[#45039]: https://github.com/rust-lang/rust/pull/45039\n" } , LintCompletion { label : "compiler_builtins" , description : "# `compiler_builtins`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "lang_items" , description : "# `lang_items`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe `rustc` compiler has certain pluggable operations, that is,\nfunctionality that isn't hard-coded into the language, but is\nimplemented in libraries, with a special marker to tell the compiler\nit exists. The marker is the attribute `#[lang = \"...\"]` and there are\nvarious different values of `...`, i.e. various different 'lang\nitems'.\n\nFor example, `Box` pointers require two lang items, one for allocation\nand one for deallocation. A freestanding program that uses the `Box`\nsugar for dynamic allocations via `malloc` and `free`:\n\n```rust,ignore\n#![feature(lang_items, box_syntax, start, libc, core_intrinsics)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\nextern crate libc;\n\n#[lang = \"owned_box\"]\npub struct Box<T>(*mut T);\n\n#[lang = \"exchange_malloc\"]\nunsafe fn allocate(size: usize, _align: usize) -> *mut u8 {\n let p = libc::malloc(size as libc::size_t) as *mut u8;\n\n // Check if `malloc` failed:\n if p as usize == 0 {\n intrinsics::abort();\n }\n\n p\n}\n\n#[lang = \"box_free\"]\nunsafe fn box_free<T: ?Sized>(ptr: *mut T) {\n libc::free(ptr as *mut libc::c_void)\n}\n\n#[start]\nfn main(_argc: isize, _argv: *const *const u8) -> isize {\n let _x = box 1;\n\n 0\n}\n\n#[lang = \"eh_personality\"] extern fn rust_eh_personality() {}\n#[lang = \"panic_impl\"] extern fn rust_begin_panic(info: &PanicInfo) -> ! { unsafe { intrinsics::abort() } }\n#[no_mangle] pub extern fn rust_eh_register_frames () {}\n#[no_mangle] pub extern fn rust_eh_unregister_frames () {}\n```\n\nNote the use of `abort`: the `exchange_malloc` lang item is assumed to\nreturn a valid pointer, and so needs to do the check internally.\n\nOther features provided by lang items include:\n\n- overloadable operators via traits: the traits corresponding to the\n `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all\n marked with lang items; those specific four are `eq`, `ord`,\n `deref`, and `add` respectively.\n- stack unwinding and general failure; the `eh_personality`,\n `panic` and `panic_bounds_checks` lang items.\n- the traits in `std::marker` used to indicate types of\n various kinds; lang items `send`, `sync` and `copy`.\n- the marker types and variance indicators found in\n `std::marker`; lang items `covariant_type`,\n `contravariant_lifetime`, etc.\n\nLang items are loaded lazily by the compiler; e.g. if one never uses\n`Box` then there is no need to define functions for `exchange_malloc`\nand `box_free`. `rustc` will emit an error when an item is needed\nbut not found in the current crate or any that it depends on.\n\nMost lang items are defined by `libcore`, but if you're trying to build\nan executable without the standard library, you'll run into the need\nfor lang items. The rest of this page focuses on this use-case, even though\nlang items are a bit broader than that.\n\n### Using libc\n\nIn order to build a `#[no_std]` executable we will need libc as a dependency.\nWe can specify this using our `Cargo.toml` file:\n\n```toml\n[dependencies]\nlibc = { version = \"0.2.14\", default-features = false }\n```\n\nNote that the default features have been disabled. This is a critical step -\n**the default features of libc include the standard library and so must be\ndisabled.**\n\n### Writing an executable without stdlib\n\nControlling the entry point is possible in two ways: the `#[start]` attribute,\nor overriding the default shim for the C `main` function with your own.\n\nThe function marked `#[start]` is passed the command line parameters\nin the same format as C:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[start]\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nTo override the compiler-inserted `main` shim, one has to disable it\nwith `#![no_main]` and then create the appropriate symbol with the\ncorrect ABI and the correct name, which requires overriding the\ncompiler's name mangling too:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\n#![no_main]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[no_mangle] // ensure that this symbol is called `main` in the output\npub extern fn main(_argc: i32, _argv: *const *const u8) -> i32 {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nIn many cases, you may need to manually link to the `compiler_builtins` crate\nwhen building a `no_std` binary. You may observe this via linker error messages\nsuch as \"```undefined reference to `__rust_probestack'```\".\n\n## More about the language items\n\nThe compiler currently makes a few assumptions about symbols which are\navailable in the executable to call. Normally these functions are provided by\nthe standard library, but without it you must define your own. These symbols\nare called \"language items\", and they each have an internal name, and then a\nsignature that an implementation must conform to.\n\nThe first of these functions, `rust_eh_personality`, is used by the failure\nmechanisms of the compiler. This is often mapped to GCC's personality function\n(see the [libstd implementation][unwind] for more information), but crates\nwhich do not trigger a panic can be assured that this function is never\ncalled. The language item's name is `eh_personality`.\n\n[unwind]: https://github.com/rust-lang/rust/blob/master/src/libpanic_unwind/gcc.rs\n\nThe second function, `rust_begin_panic`, is also used by the failure mechanisms of the\ncompiler. When a panic happens, this controls the message that's displayed on\nthe screen. While the language item's name is `panic_impl`, the symbol name is\n`rust_begin_panic`.\n\nFinally, a `eh_catch_typeinfo` static is needed for certain targets which\nimplement Rust panics on top of C++ exceptions.\n\n## List of all language items\n\nThis is a list of all language items in Rust along with where they are located in\nthe source code.\n\n- Primitives\n - `i8`: `libcore/num/mod.rs`\n - `i16`: `libcore/num/mod.rs`\n - `i32`: `libcore/num/mod.rs`\n - `i64`: `libcore/num/mod.rs`\n - `i128`: `libcore/num/mod.rs`\n - `isize`: `libcore/num/mod.rs`\n - `u8`: `libcore/num/mod.rs`\n - `u16`: `libcore/num/mod.rs`\n - `u32`: `libcore/num/mod.rs`\n - `u64`: `libcore/num/mod.rs`\n - `u128`: `libcore/num/mod.rs`\n - `usize`: `libcore/num/mod.rs`\n - `f32`: `libstd/f32.rs`\n - `f64`: `libstd/f64.rs`\n - `char`: `libcore/char.rs`\n - `slice`: `liballoc/slice.rs`\n - `str`: `liballoc/str.rs`\n - `const_ptr`: `libcore/ptr.rs`\n - `mut_ptr`: `libcore/ptr.rs`\n - `unsafe_cell`: `libcore/cell.rs`\n- Runtime\n - `start`: `libstd/rt.rs`\n - `eh_personality`: `libpanic_unwind/emcc.rs` (EMCC)\n - `eh_personality`: `libpanic_unwind/gcc.rs` (GNU)\n - `eh_personality`: `libpanic_unwind/seh.rs` (SEH)\n - `eh_catch_typeinfo`: `libpanic_unwind/emcc.rs` (EMCC)\n - `panic`: `libcore/panicking.rs`\n - `panic_bounds_check`: `libcore/panicking.rs`\n - `panic_impl`: `libcore/panicking.rs`\n - `panic_impl`: `libstd/panicking.rs`\n- Allocations\n - `owned_box`: `liballoc/boxed.rs`\n - `exchange_malloc`: `liballoc/heap.rs`\n - `box_free`: `liballoc/heap.rs`\n- Operands\n - `not`: `libcore/ops/bit.rs`\n - `bitand`: `libcore/ops/bit.rs`\n - `bitor`: `libcore/ops/bit.rs`\n - `bitxor`: `libcore/ops/bit.rs`\n - `shl`: `libcore/ops/bit.rs`\n - `shr`: `libcore/ops/bit.rs`\n - `bitand_assign`: `libcore/ops/bit.rs`\n - `bitor_assign`: `libcore/ops/bit.rs`\n - `bitxor_assign`: `libcore/ops/bit.rs`\n - `shl_assign`: `libcore/ops/bit.rs`\n - `shr_assign`: `libcore/ops/bit.rs`\n - `deref`: `libcore/ops/deref.rs`\n - `deref_mut`: `libcore/ops/deref.rs`\n - `index`: `libcore/ops/index.rs`\n - `index_mut`: `libcore/ops/index.rs`\n - `add`: `libcore/ops/arith.rs`\n - `sub`: `libcore/ops/arith.rs`\n - `mul`: `libcore/ops/arith.rs`\n - `div`: `libcore/ops/arith.rs`\n - `rem`: `libcore/ops/arith.rs`\n - `neg`: `libcore/ops/arith.rs`\n - `add_assign`: `libcore/ops/arith.rs`\n - `sub_assign`: `libcore/ops/arith.rs`\n - `mul_assign`: `libcore/ops/arith.rs`\n - `div_assign`: `libcore/ops/arith.rs`\n - `rem_assign`: `libcore/ops/arith.rs`\n - `eq`: `libcore/cmp.rs`\n - `ord`: `libcore/cmp.rs`\n- Functions\n - `fn`: `libcore/ops/function.rs`\n - `fn_mut`: `libcore/ops/function.rs`\n - `fn_once`: `libcore/ops/function.rs`\n - `generator_state`: `libcore/ops/generator.rs`\n - `generator`: `libcore/ops/generator.rs`\n- Other\n - `coerce_unsized`: `libcore/ops/unsize.rs`\n - `drop`: `libcore/ops/drop.rs`\n - `drop_in_place`: `libcore/ptr.rs`\n - `clone`: `libcore/clone.rs`\n - `copy`: `libcore/marker.rs`\n - `send`: `libcore/marker.rs`\n - `sized`: `libcore/marker.rs`\n - `unsize`: `libcore/marker.rs`\n - `sync`: `libcore/marker.rs`\n - `phantom_data`: `libcore/marker.rs`\n - `discriminant_kind`: `libcore/marker.rs`\n - `freeze`: `libcore/marker.rs`\n - `debug_trait`: `libcore/fmt/mod.rs`\n - `non_zero`: `libcore/nonzero.rs`\n - `arc`: `liballoc/sync.rs`\n - `rc`: `liballoc/rc.rs`\n" } , LintCompletion { label : "member_constraints" , description : "# `member_constraints`\n\nThe tracking issue for this feature is: [#61997]\n\n[#61997]: https://github.com/rust-lang/rust/issues/61997\n\n------------------------\n\nThe `member_constraints` feature gate lets you use `impl Trait` syntax with\nmultiple unrelated lifetime parameters.\n\nA simple example is:\n\n```rust\n#![feature(member_constraints)]\n\ntrait Trait<'a, 'b> { }\nimpl<T> Trait<'_, '_> for T {}\n\nfn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> impl Trait<'a, 'b> {\n (x, y)\n}\n\nfn main() { }\n```\n\nWithout the `member_constraints` feature gate, the above example is an\nerror because both `'a` and `'b` appear in the impl Trait bounds, but\nneither outlives the other.\n" } , LintCompletion { label : "crate_visibility_modifier" , description : "# `crate_visibility_modifier`\n\nThe tracking issue for this feature is: [#53120]\n\n[#53120]: https://github.com/rust-lang/rust/issues/53120\n\n-----\n\nThe `crate_visibility_modifier` feature allows the `crate` keyword to be used\nas a visibility modifier synonymous to `pub(crate)`, indicating that a type\n(function, _&c._) is to be visible to the entire enclosing crate, but not to\nother crates.\n\n```rust\n#![feature(crate_visibility_modifier)]\n\ncrate struct Foo {\n bar: usize,\n}\n```\n" } , LintCompletion { label : "try_blocks" , description : "# `try_blocks`\n\nThe tracking issue for this feature is: [#31436]\n\n[#31436]: https://github.com/rust-lang/rust/issues/31436\n\n------------------------\n\nThe `try_blocks` feature adds support for `try` blocks. A `try`\nblock creates a new scope one can use the `?` operator in.\n\n```rust,edition2018\n#![feature(try_blocks)]\n\nuse std::num::ParseIntError;\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"2\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert_eq!(result, Ok(6));\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"foo\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert!(result.is_err());\n```\n" } , LintCompletion { label : "const_in_array_repeat_expressions" , description : "# `const_in_array_repeat_expressions`\n\nThe tracking issue for this feature is: [#49147]\n\n[#49147]: https://github.com/rust-lang/rust/issues/49147\n\n------------------------\n\nRelaxes the rules for repeat expressions, `[x; N]` such that `x` may also be `const` (strictly\nspeaking rvalue promotable), in addition to `typeof(x): Copy`. The result of `[x; N]` where `x` is\n`const` is itself also `const`.\n" } , LintCompletion { label : "negative_impls" , description : "# `negative_impls`\n\nThe tracking issue for this feature is [#68318].\n\n[#68318]: https://github.com/rust-lang/rust/issues/68318\n\n----\n\nWith the feature gate `negative_impls`, you can write negative impls as well as positive ones:\n\n```rust\n#![feature(negative_impls)]\ntrait DerefMut { }\nimpl<T: ?Sized> !DerefMut for &T { }\n```\n\nNegative impls indicate a semver guarantee that the given trait will not be implemented for the given types. Negative impls play an additional purpose for auto traits, described below.\n\nNegative impls have the following characteristics:\n\n* They do not have any items.\n* They must obey the orphan rules as if they were a positive impl.\n* They cannot \"overlap\" with any positive impls.\n\n## Semver interaction\n\nIt is a breaking change to remove a negative impl. Negative impls are a commitment not to implement the given trait for the named types.\n\n## Orphan and overlap rules\n\nNegative impls must obey the same orphan rules as a positive impl. This implies you cannot add a negative impl for types defined in upstream crates and so forth.\n\nSimilarly, negative impls cannot overlap with positive impls, again using the same \"overlap\" check that we ordinarily use to determine if two impls overlap. (Note that positive impls typically cannot overlap with one another either, except as permitted by specialization.)\n\n## Interaction with auto traits\n\nDeclaring a negative impl `impl !SomeAutoTrait for SomeType` for an\nauto-trait serves two purposes:\n\n* as with any trait, it declares that `SomeType` will never implement `SomeAutoTrait`;\n* it disables the automatic `SomeType: SomeAutoTrait` impl that would otherwise have been generated.\n\nNote that, at present, there is no way to indicate that a given type\ndoes not implement an auto trait *but that it may do so in the\nfuture*. For ordinary types, this is done by simply not declaring any\nimpl at all, but that is not an option for auto traits. A workaround\nis that one could embed a marker type as one of the fields, where the\nmarker type is `!AutoTrait`.\n\n## Immediate uses\n\nNegative impls are used to declare that `&T: !DerefMut` and `&mut T: !Clone`, as required to fix the soundness of `Pin` described in [#66544](https://github.com/rust-lang/rust/issues/66544).\n\nThis serves two purposes:\n\n* For proving the correctness of unsafe code, we can use that impl as evidence that no `DerefMut` or `Clone` impl exists.\n* It prevents downstream crates from creating such impls.\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` language feature enables C-variadic functions to be\ndefined in Rust. The may be called both from within Rust and via FFI.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\npub unsafe extern \"C\" fn add(n: usize, mut args: ...) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "profiler_runtime" , description : "# `profiler_runtime`\n\nThe tracking issue for this feature is: [#42524](https://github.com/rust-lang/rust/issues/42524).\n\n------------------------\n" } , LintCompletion { label : "box_syntax" , description : "# `box_syntax`\n\nThe tracking issue for this feature is: [#49733]\n\n[#49733]: https://github.com/rust-lang/rust/issues/49733\n\nSee also [`box_patterns`](box-patterns.md)\n\n------------------------\n\nCurrently the only stable way to create a `Box` is via the `Box::new` method.\nAlso it is not possible in stable Rust to destructure a `Box` in a match\npattern. The unstable `box` keyword can be used to create a `Box`. An example\nusage would be:\n\n```rust\n#![feature(box_syntax)]\n\nfn main() {\n let b = box 5;\n}\n```\n" } , LintCompletion { label : "ffi_pure" , description : "# `ffi_pure`\n\nThe tracking issue for this feature is: [#58329]\n\n------\n\nThe `#[ffi_pure]` attribute applies clang's `pure` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_pure]` functions shall have no effects except for its return\nvalue, which shall not change across two consecutive function calls with\nthe same parameters.\n\nApplying the `#[ffi_pure]` attribute to a function that violates these\nrequirements is undefined behavior.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination and loop optimizations. Some common examples of pure functions are\n`strlen` or `memcmp`.\n\nThese optimizations are only applicable when the compiler can prove that no\nprogram state observable by the `#[ffi_pure]` function has changed between calls\nof the function, which could alter the result. See also the `#[ffi_const]`\nattribute, which provides stronger guarantees regarding the allowable behavior\nof a function, enabling further optimization.\n\n## Pitfalls\n\nA `#[ffi_pure]` function can read global memory through the function\nparameters (e.g. pointers), globals, etc. `#[ffi_pure]` functions are not\nreferentially-transparent, and are therefore more relaxed than `#[ffi_const]`\nfunctions.\n\nHowever, accesing global memory through volatile or atomic reads can violate the\nrequirement that two consecutive function calls shall return the same value.\n\nA `pure` function that returns unit has no effect on the abstract machine's\nstate.\n\nA `#[ffi_pure]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `pure` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`pure` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_pure]`.\n\n\n[#58329]: https://github.com/rust-lang/rust/issues/58329\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacigdac.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_pure.htm\n" } , LintCompletion { label : "arbitrary_enum_discriminant" , description : "# `arbitrary_enum_discriminant`\n\nThe tracking issue for this feature is: [#60553]\n\n[#60553]: https://github.com/rust-lang/rust/issues/60553\n\n------------------------\n\nThe `arbitrary_enum_discriminant` feature permits tuple-like and\nstruct-like enum variants with `#[repr(<int-type>)]` to have explicit discriminants.\n\n## Examples\n\n```rust\n#![feature(arbitrary_enum_discriminant)]\n\n#[allow(dead_code)]\n#[repr(u8)]\nenum Enum {\n Unit = 3,\n Tuple(u16) = 2,\n Struct {\n a: u8,\n b: u16,\n } = 1,\n}\n\nimpl Enum {\n fn tag(&self) -> u8 {\n unsafe { *(self as *const Self as *const u8) }\n }\n}\n\nassert_eq!(3, Enum::Unit.tag());\nassert_eq!(2, Enum::Tuple(5).tag());\nassert_eq!(1, Enum::Struct{a: 7, b: 11}.tag());\n```\n" } , LintCompletion { label : "unsized_locals" , description : "# `unsized_locals`\n\nThe tracking issue for this feature is: [#48055]\n\n[#48055]: https://github.com/rust-lang/rust/issues/48055\n\n------------------------\n\nThis implements [RFC1909]. When turned on, you can have unsized arguments and locals:\n\n[RFC1909]: https://github.com/rust-lang/rfcs/blob/master/text/1909-unsized-rvalues.md\n\n```rust\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nfn main() {\n let x: Box<dyn Any> = Box::new(42);\n let x: dyn Any = *x;\n // ^ unsized local variable\n // ^^ unsized temporary\n foo(x);\n}\n\nfn foo(_: dyn Any) {}\n// ^^^^^^ unsized argument\n```\n\nThe RFC still forbids the following unsized expressions:\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nstruct MyStruct<T: ?Sized> {\n content: T,\n}\n\nstruct MyTupleStruct<T: ?Sized>(T);\n\nfn answer() -> Box<dyn Any> {\n Box::new(42)\n}\n\nfn main() {\n // You CANNOT have unsized statics.\n static X: dyn Any = *answer(); // ERROR\n const Y: dyn Any = *answer(); // ERROR\n\n // You CANNOT have struct initialized unsized.\n MyStruct { content: *answer() }; // ERROR\n MyTupleStruct(*answer()); // ERROR\n (42, *answer()); // ERROR\n\n // You CANNOT have unsized return types.\n fn my_function() -> dyn Any { *answer() } // ERROR\n\n // You CAN have unsized local variables...\n let mut x: dyn Any = *answer(); // OK\n // ...but you CANNOT reassign to them.\n x = *answer(); // ERROR\n\n // You CANNOT even initialize them separately.\n let y: dyn Any; // OK\n y = *answer(); // ERROR\n\n // Not mentioned in the RFC, but by-move captured variables are also Sized.\n let x: dyn Any = *answer();\n (move || { // ERROR\n let y = x;\n })();\n\n // You CAN create a closure with unsized arguments,\n // but you CANNOT call it.\n // This is an implementation detail and may be changed in the future.\n let f = |x: dyn Any| {};\n f(*answer()); // ERROR\n}\n```\n\n## By-value trait objects\n\nWith this feature, you can have by-value `self` arguments without `Self: Sized` bounds.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main() {\n let slice: Box<[i32]> = Box::new([1, 2, 3]);\n <[i32] as Foo>::foo(*slice);\n}\n```\n\nAnd `Foo` will also be object-safe.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main () {\n let slice: Box<dyn Foo> = Box::new([1, 2, 3]);\n // doesn't compile yet\n <dyn Foo as Foo>::foo(*slice);\n}\n```\n\nOne of the objectives of this feature is to allow `Box<dyn FnOnce>`.\n\n## Variable length arrays\n\nThe RFC also describes an extension to the array literal syntax: `[e; dyn n]`. In the syntax, `n` isn't necessarily a constant expression. The array is dynamically allocated on the stack and has the type of `[T]`, instead of `[T; n]`.\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nfn mergesort<T: Ord>(a: &mut [T]) {\n let mut tmp = [T; dyn a.len()];\n // ...\n}\n\nfn main() {\n let mut a = [3, 1, 5, 6];\n mergesort(&mut a);\n assert_eq!(a, [1, 3, 5, 6]);\n}\n```\n\nVLAs are not implemented yet. The syntax isn't final, either. We may need an alternative syntax for Rust 2015 because, in Rust 2015, expressions like `[e; dyn(1)]` would be ambiguous. One possible alternative proposed in the RFC is `[e; n]`: if `n` captures one or more local variables, then it is considered as `[e; dyn n]`.\n\n## Advisory on stack usage\n\nIt's advised not to casually use the `#![feature(unsized_locals)]` feature. Typical use-cases are:\n\n- When you need a by-value trait objects.\n- When you really need a fast allocation of small temporary arrays.\n\nAnother pitfall is repetitive allocation and temporaries. Currently the compiler simply extends the stack frame every time it encounters an unsized assignment. So for example, the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = {{{{{{{{{{*x}}}}}}}}}};\n}\n```\n\nand the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n for _ in 0..10 {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = *x;\n }\n}\n```\n\nwill unnecessarily extend the stack frame.\n" } , LintCompletion { label : "cfg_sanitize" , description : "# `cfg_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `cfg_sanitize` feature makes it possible to execute different code\ndepending on whether a particular sanitizer is enabled or not.\n\n## Examples\n\n```rust\n#![feature(cfg_sanitize)]\n\n#[cfg(sanitize = \"thread\")]\nfn a() {\n // ...\n}\n\n#[cfg(not(sanitize = \"thread\"))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(sanitize = \"leak\") {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "cmse_nonsecure_entry" , description : "# `cmse_nonsecure_entry`\n\nThe tracking issue for this feature is: [#75835]\n\n[#75835]: https://github.com/rust-lang/rust/issues/75835\n\n------------------------\n\nThe [TrustZone-M\nfeature](https://developer.arm.com/documentation/100690/latest/) is available\nfor targets with the Armv8-M architecture profile (`thumbv8m` in their target\nname).\nLLVM, the Rust compiler and the linker are providing\n[support](https://developer.arm.com/documentation/ecm0359818/latest/) for the\nTrustZone-M feature.\n\nOne of the things provided, with this unstable feature, is the\n`cmse_nonsecure_entry` attribute. This attribute marks a Secure function as an\nentry function (see [section\n5.4](https://developer.arm.com/documentation/ecm0359818/latest/) for details).\nWith this attribute, the compiler will do the following:\n* add a special symbol on the function which is the `__acle_se_` prefix and the\n standard function name\n* constrain the number of parameters to avoid using the Non-Secure stack\n* before returning from the function, clear registers that might contain Secure\n information\n* use the `BXNS` instruction to return\n\nBecause the stack can not be used to pass parameters, there will be compilation\nerrors if:\n* the total size of all parameters is too big (for example more than four 32\n bits integers)\n* the entry function is not using a C ABI\n\nThe special symbol `__acle_se_` will be used by the linker to generate a secure\ngateway veneer.\n\n<!-- NOTE(ignore) this example is specific to thumbv8m targets -->\n\n``` rust,ignore\n#![feature(cmse_nonsecure_entry)]\n\n#[no_mangle]\n#[cmse_nonsecure_entry]\npub extern \"C\" fn entry_function(input: u32) -> u32 {\n input + 6\n}\n```\n\n``` text\n$ rustc --emit obj --crate-type lib --target thumbv8m.main-none-eabi function.rs\n$ arm-none-eabi-objdump -D function.o\n\n00000000 <entry_function>:\n 0: b580 push {r7, lr}\n 2: 466f mov r7, sp\n 4: b082 sub sp, #8\n 6: 9001 str r0, [sp, #4]\n 8: 1d81 adds r1, r0, #6\n a: 460a mov r2, r1\n c: 4281 cmp r1, r0\n e: 9200 str r2, [sp, #0]\n 10: d30b bcc.n 2a <entry_function+0x2a>\n 12: e7ff b.n 14 <entry_function+0x14>\n 14: 9800 ldr r0, [sp, #0]\n 16: b002 add sp, #8\n 18: e8bd 4080 ldmia.w sp!, {r7, lr}\n 1c: 4671 mov r1, lr\n 1e: 4672 mov r2, lr\n 20: 4673 mov r3, lr\n 22: 46f4 mov ip, lr\n 24: f38e 8800 msr CPSR_f, lr\n 28: 4774 bxns lr\n 2a: f240 0000 movw r0, #0\n 2e: f2c0 0000 movt r0, #0\n 32: f240 0200 movw r2, #0\n 36: f2c0 0200 movt r2, #0\n 3a: 211c movs r1, #28\n 3c: f7ff fffe bl 0 <_ZN4core9panicking5panic17h5c028258ca2fb3f5E>\n 40: defe udf #254 ; 0xfe\n```\n" } , LintCompletion { label : "cfg_version" , description : "# `cfg_version`\n\nThe tracking issue for this feature is: [#64796]\n\n[#64796]: https://github.com/rust-lang/rust/issues/64796\n\n------------------------\n\nThe `cfg_version` feature makes it possible to execute different code\ndepending on the compiler version.\n\n## Examples\n\n```rust\n#![feature(cfg_version)]\n\n#[cfg(version(\"1.42\"))]\nfn a() {\n // ...\n}\n\n#[cfg(not(version(\"1.42\")))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(version(\"1.42\")) {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "unsized_tuple_coercion" , description : "# `unsized_tuple_coercion`\n\nThe tracking issue for this feature is: [#42877]\n\n[#42877]: https://github.com/rust-lang/rust/issues/42877\n\n------------------------\n\nThis is a part of [RFC0401]. According to the RFC, there should be an implementation like this:\n\n```rust,ignore\nimpl<..., T, U: ?Sized> Unsized<(..., U)> for (..., T) where T: Unsized<U> {}\n```\n\nThis implementation is currently gated behind `#[feature(unsized_tuple_coercion)]` to avoid insta-stability. Therefore you can use it like this:\n\n```rust\n#![feature(unsized_tuple_coercion)]\n\nfn main() {\n let x : ([i32; 3], [i32; 3]) = ([1, 2, 3], [4, 5, 6]);\n let y : &([i32; 3], [i32]) = &x;\n assert_eq!(y.1[0], 4);\n}\n```\n\n[RFC0401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md\n" } , LintCompletion { label : "generators" , description : "# `generators`\n\nThe tracking issue for this feature is: [#43122]\n\n[#43122]: https://github.com/rust-lang/rust/issues/43122\n\n------------------------\n\nThe `generators` feature gate in Rust allows you to define generator or\ncoroutine literals. A generator is a \"resumable function\" that syntactically\nresembles a closure but compiles to much different semantics in the compiler\nitself. The primary feature of a generator is that it can be suspended during\nexecution to be resumed at a later date. Generators use the `yield` keyword to\n\"return\", and then the caller can `resume` a generator to resume execution just\nafter the `yield` keyword.\n\nGenerators are an extra-unstable feature in the compiler right now. Added in\n[RFC 2033] they're mostly intended right now as a information/constraint\ngathering phase. The intent is that experimentation can happen on the nightly\ncompiler before actual stabilization. A further RFC will be required to\nstabilize generators/coroutines and will likely contain at least a few small\ntweaks to the overall design.\n\n[RFC 2033]: https://github.com/rust-lang/rfcs/pull/2033\n\nA syntactical example of a generator is:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n yield 1;\n return \"foo\"\n };\n\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Yielded(1) => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Complete(\"foo\") => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n}\n```\n\nGenerators are closure-like literals which can contain a `yield` statement. The\n`yield` statement takes an optional expression of a value to yield out of the\ngenerator. All generator literals implement the `Generator` trait in the\n`std::ops` module. The `Generator` trait has one main method, `resume`, which\nresumes execution of the generator at the previous suspension point.\n\nAn example of the control flow of generators is that the following example\nprints all numbers in order:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n println!(\"2\");\n yield;\n println!(\"4\");\n };\n\n println!(\"1\");\n Pin::new(&mut generator).resume(());\n println!(\"3\");\n Pin::new(&mut generator).resume(());\n println!(\"5\");\n}\n```\n\nAt this time the main intended use case of generators is an implementation\nprimitive for async/await syntax, but generators will likely be extended to\nergonomic implementations of iterators and other primitives in the future.\nFeedback on the design and usage is always appreciated!\n\n### The `Generator` trait\n\nThe `Generator` trait in `std::ops` currently looks like:\n\n```rust\n# #![feature(arbitrary_self_types, generator_trait)]\n# use std::ops::GeneratorState;\n# use std::pin::Pin;\n\npub trait Generator<R = ()> {\n type Yield;\n type Return;\n fn resume(self: Pin<&mut Self>, resume: R) -> GeneratorState<Self::Yield, Self::Return>;\n}\n```\n\nThe `Generator::Yield` type is the type of values that can be yielded with the\n`yield` statement. The `Generator::Return` type is the returned type of the\ngenerator. This is typically the last expression in a generator's definition or\nany value passed to `return` in a generator. The `resume` function is the entry\npoint for executing the `Generator` itself.\n\nThe return value of `resume`, `GeneratorState`, looks like:\n\n```rust\npub enum GeneratorState<Y, R> {\n Yielded(Y),\n Complete(R),\n}\n```\n\nThe `Yielded` variant indicates that the generator can later be resumed. This\ncorresponds to a `yield` point in a generator. The `Complete` variant indicates\nthat the generator is complete and cannot be resumed again. Calling `resume`\nafter a generator has returned `Complete` will likely result in a panic of the\nprogram.\n\n### Closure-like semantics\n\nThe closure-like syntax for generators alludes to the fact that they also have\nclosure-like semantics. Namely:\n\n* When created, a generator executes no code. A closure literal does not\n actually execute any of the closure's code on construction, and similarly a\n generator literal does not execute any code inside the generator when\n constructed.\n\n* Generators can capture outer variables by reference or by move, and this can\n be tweaked with the `move` keyword at the beginning of the closure. Like\n closures all generators will have an implicit environment which is inferred by\n the compiler. Outer variables can be moved into a generator for use as the\n generator progresses.\n\n* Generator literals produce a value with a unique type which implements the\n `std::ops::Generator` trait. This allows actual execution of the generator\n through the `Generator::resume` method as well as also naming it in return\n types and such.\n\n* Traits like `Send` and `Sync` are automatically implemented for a `Generator`\n depending on the captured variables of the environment. Unlike closures,\n generators also depend on variables live across suspension points. This means\n that although the ambient environment may be `Send` or `Sync`, the generator\n itself may not be due to internal variables live across `yield` points being\n not-`Send` or not-`Sync`. Note that generators do\n not implement traits like `Copy` or `Clone` automatically.\n\n* Whenever a generator is dropped it will drop all captured environment\n variables.\n\n### Generators as state machines\n\nIn the compiler, generators are currently compiled as state machines. Each\n`yield` expression will correspond to a different state that stores all live\nvariables over that suspension point. Resumption of a generator will dispatch on\nthe current state and then execute internally until a `yield` is reached, at\nwhich point all state is saved off in the generator and a value is returned.\n\nLet's take a look at an example to see what's going on here:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = move || {\n yield 1;\n return ret\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nThis generator literal will compile down to something similar to:\n\n```rust\n#![feature(arbitrary_self_types, generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = {\n enum __Generator {\n Start(&'static str),\n Yield1(&'static str),\n Done,\n }\n\n impl Generator for __Generator {\n type Yield = i32;\n type Return = &'static str;\n\n fn resume(mut self: Pin<&mut Self>, resume: ()) -> GeneratorState<i32, &'static str> {\n use std::mem;\n match mem::replace(&mut *self, __Generator::Done) {\n __Generator::Start(s) => {\n *self = __Generator::Yield1(s);\n GeneratorState::Yielded(1)\n }\n\n __Generator::Yield1(s) => {\n *self = __Generator::Done;\n GeneratorState::Complete(s)\n }\n\n __Generator::Done => {\n panic!(\"generator resumed after completion\")\n }\n }\n }\n }\n\n __Generator::Start(ret)\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nNotably here we can see that the compiler is generating a fresh type,\n`__Generator` in this case. This type has a number of states (represented here\nas an `enum`) corresponding to each of the conceptual states of the generator.\nAt the beginning we're closing over our outer variable `foo` and then that\nvariable is also live over the `yield` point, so it's stored in both states.\n\nWhen the generator starts it'll immediately yield 1, but it saves off its state\njust before it does so indicating that it has reached the yield point. Upon\nresuming again we'll execute the `return ret` which returns the `Complete`\nstate.\n\nHere we can also note that the `Done` state, if resumed, panics immediately as\nit's invalid to resume a completed generator. It's also worth noting that this\nis just a rough desugaring, not a normative specification for what the compiler\ndoes.\n" } , LintCompletion { label : "transparent_unions" , description : "# `transparent_unions`\n\nThe tracking issue for this feature is [#60405]\n\n[#60405]: https://github.com/rust-lang/rust/issues/60405\n\n----\n\nThe `transparent_unions` feature allows you mark `union`s as\n`#[repr(transparent)]`. A `union` may be `#[repr(transparent)]` in exactly the\nsame conditions in which a `struct` may be `#[repr(transparent)]` (generally,\nthis means the `union` must have exactly one non-zero-sized field). Some\nconcrete illustrations follow.\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `f32`.\n#[repr(transparent)]\nunion SingleFieldUnion {\n field: f32,\n}\n\n// This union has the same representation as `usize`.\n#[repr(transparent)]\nunion MultiFieldUnion {\n field: usize,\n nothing: (),\n}\n```\n\nFor consistency with transparent `struct`s, `union`s must have exactly one\nnon-zero-sized field. If all fields are zero-sized, the `union` must not be\n`#[repr(transparent)]`:\n\n```rust\n#![feature(transparent_unions)]\n\n// This (non-transparent) union is already valid in stable Rust:\npub union GoodUnion {\n pub nothing: (),\n}\n\n// Error: transparent union needs exactly one non-zero-sized field, but has 0\n// #[repr(transparent)]\n// pub union BadUnion {\n// pub nothing: (),\n// }\n```\n\nThe one exception is if the `union` is generic over `T` and has a field of type\n`T`, it may be `#[repr(transparent)]` even if `T` is a zero-sized type:\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `T`.\n#[repr(transparent)]\npub union GenericUnion<T: Copy> { // Unions with non-`Copy` fields are unstable.\n pub field: T,\n pub nothing: (),\n}\n\n// This is okay even though `()` is a zero-sized type.\npub const THIS_IS_OKAY: GenericUnion<()> = GenericUnion { field: () };\n```\n\nLike transarent `struct`s, a transparent `union` of type `U` has the same\nlayout, size, and ABI as its single non-ZST field. If it is generic over a type\n`T`, and all its fields are ZSTs except for exactly one field of type `T`, then\nit has the same layout and ABI as `T` (even if `T` is a ZST when monomorphized).\n\nLike transparent `struct`s, transparent `union`s are FFI-safe if and only if\ntheir underlying representation type is also FFI-safe.\n\nA `union` may not be eligible for the same nonnull-style optimizations that a\n`struct` or `enum` (with the same fields) are eligible for. Adding\n`#[repr(transparent)]` to `union` does not change this. To give a more concrete\nexample, it is unspecified whether `size_of::<T>()` is equal to\n`size_of::<Option<T>>()`, where `T` is a `union` (regardless of whether or not\nit is transparent). The Rust compiler is free to perform this optimization if\npossible, but is not required to, and different compiler versions may differ in\ntheir application of these optimizations.\n" } , LintCompletion { label : "plugin_registrar" , description : "# `plugin_registrar`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin`] and `rustc_private` features as well. For more details, see\ntheir docs.\n\n[`plugin`]: plugin.md\n\n------------------------\n" } , LintCompletion { label : "or_patterns" , description : "# `or_patterns`\n\nThe tracking issue for this feature is: [#54883]\n\n[#54883]: https://github.com/rust-lang/rust/issues/54883\n\n------------------------\n\nThe `or_pattern` language feature allows `|` to be arbitrarily nested within\na pattern, for example, `Some(A(0) | B(1 | 2))` becomes a valid pattern.\n\n## Examples\n\n```rust,ignore\n#![feature(or_patterns)]\n\npub enum Foo {\n Bar,\n Baz,\n Quux,\n}\n\npub fn example(maybe_foo: Option<Foo>) {\n match maybe_foo {\n Some(Foo::Bar | Foo::Baz) => {\n println!(\"The value contained `Bar` or `Baz`\");\n }\n Some(_) => {\n println!(\"The value did not contain `Bar` or `Baz`\");\n }\n None => {\n println!(\"The value was `None`\");\n }\n }\n}\n```\n" } , LintCompletion { label : "repr128" , description : "# `repr128`\n\nThe tracking issue for this feature is: [#56071]\n\n[#56071]: https://github.com/rust-lang/rust/issues/56071\n\n------------------------\n\nThe `repr128` feature adds support for `#[repr(u128)]` on `enum`s.\n\n```rust\n#![feature(repr128)]\n\n#[repr(u128)]\nenum Foo {\n Bar(u64),\n}\n```\n" } , LintCompletion { label : "unboxed_closures" , description : "# `unboxed_closures`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`fn_traits`](../library-features/fn-traits.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `unboxed_closures` feature allows you to write functions using the `\"rust-call\"` ABI,\nrequired for implementing the [`Fn*`] family of traits. `\"rust-call\"` functions must have \nexactly one (non self) argument, a tuple representing the argument list.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n\nextern \"rust-call\" fn add_args(args: (u32, u32)) -> u32 {\n args.0 + args.1\n}\n\nfn main() {}\n```\n" } , LintCompletion { label : "link_cfg" , description : "# `link_cfg`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "rustc_attrs" , description : "# `rustc_attrs`\n\nThis feature has no tracking issue, and is therefore internal to\nthe compiler, not being intended for general use.\n\nNote: `rustc_attrs` enables many rustc-internal attributes and this page\nonly discuss a few of them.\n\n------------------------\n\nThe `rustc_attrs` feature allows debugging rustc type layouts by using\n`#[rustc_layout(...)]` to debug layout at compile time (it even works\nwith `cargo check`) as an alternative to `rustc -Z print-type-sizes`\nthat is way more verbose.\n\nOptions provided by `#[rustc_layout(...)]` are `debug`, `size`, `align`,\n`abi`. Note that it only works on sized types without generics.\n\n## Examples\n\n```rust,ignore\n#![feature(rustc_attrs)]\n\n#[rustc_layout(abi, size)]\npub enum X {\n Y(u8, u8, u8),\n Z(isize),\n}\n```\n\nWhen that is compiled, the compiler will error with something like\n\n```text\nerror: abi: Aggregate { sized: true }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: size: Size { raw: 16 }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: aborting due to 2 previous errors\n```\n" } , LintCompletion { label : "box_patterns" , description : "# `box_patterns`\n\nThe tracking issue for this feature is: [#29641]\n\n[#29641]: https://github.com/rust-lang/rust/issues/29641\n\nSee also [`box_syntax`](box-syntax.md)\n\n------------------------\n\nBox patterns let you match on `Box<T>`s:\n\n\n```rust\n#![feature(box_patterns)]\n\nfn main() {\n let b = Some(Box::new(5));\n match b {\n Some(box n) if n < 0 => {\n println!(\"Box contains negative number {}\", n);\n },\n Some(box n) if n >= 0 => {\n println!(\"Box contains non-negative number {}\", n);\n },\n None => {\n println!(\"No box\");\n },\n _ => unreachable!()\n }\n}\n```\n" } , LintCompletion { label : "infer_static_outlives_requirements" , description : "# `infer_static_outlives_requirements`\n\nThe tracking issue for this feature is: [#54185]\n\n[#54185]: https://github.com/rust-lang/rust/issues/54185\n\n------------------------\nThe `infer_static_outlives_requirements` feature indicates that certain\n`'static` outlives requirements can be inferred by the compiler rather than\nstating them explicitly.\n\nNote: It is an accompanying feature to `infer_outlives_requirements`,\nwhich must be enabled to infer outlives requirements.\n\nFor example, currently generic struct definitions that contain\nreferences, require where-clauses of the form T: 'static. By using\nthis feature the outlives predicates will be inferred, although\nthey may still be written explicitly.\n\n```rust,ignore (pseudo-Rust)\nstruct Foo<U> where U: 'static { // <-- currently required\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n\n## Examples:\n\n```rust,ignore (pseudo-Rust)\n#![feature(infer_outlives_requirements)]\n#![feature(infer_static_outlives_requirements)]\n\n#[rustc_outlives]\n// Implicitly infer U: 'static\nstruct Foo<U> {\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n" } , LintCompletion { label : "trait_alias" , description : "# `trait_alias`\n\nThe tracking issue for this feature is: [#41517]\n\n[#41517]: https://github.com/rust-lang/rust/issues/41517\n\n------------------------\n\nThe `trait_alias` feature adds support for trait aliases. These allow aliases\nto be created for one or more traits (currently just a single regular trait plus\nany number of auto-traits), and used wherever traits would normally be used as\neither bounds or trait objects.\n\n```rust\n#![feature(trait_alias)]\n\ntrait Foo = std::fmt::Debug + Send;\ntrait Bar = Foo + Sync;\n\n// Use trait alias as bound on type parameter.\nfn foo<T: Foo>(v: &T) {\n println!(\"{:?}\", v);\n}\n\npub fn main() {\n foo(&1);\n\n // Use trait alias for trait objects.\n let a: &Bar = &123;\n println!(\"{:?}\", a);\n let b = Box::new(456) as Box<dyn Foo>;\n println!(\"{:?}\", b);\n}\n```\n" } , LintCompletion { label : "const_fn" , description : "# `const_fn`\n\nThe tracking issue for this feature is: [#57563]\n\n[#57563]: https://github.com/rust-lang/rust/issues/57563\n\n------------------------\n\nThe `const_fn` feature allows marking free functions and inherent methods as\n`const`, enabling them to be called in constants contexts, with constant\narguments.\n\n## Examples\n\n```rust\n#![feature(const_fn)]\n\nconst fn double(x: i32) -> i32 {\n x * 2\n}\n\nconst FIVE: i32 = 5;\nconst TEN: i32 = double(FIVE);\n\nfn main() {\n assert_eq!(5, FIVE);\n assert_eq!(10, TEN);\n}\n```\n" } , LintCompletion { label : "doc_cfg" , description : "# `doc_cfg`\n\nThe tracking issue for this feature is: [#43781]\n\n------\n\nThe `doc_cfg` feature allows an API be documented as only available in some specific platforms.\nThis attribute has two effects:\n\n1. In the annotated item's documentation, there will be a message saying \"This is supported on\n (platform) only\".\n\n2. The item's doc-tests will only run on the specific platform.\n\nIn addition to allowing the use of the `#[doc(cfg)]` attribute, this feature enables the use of a\nspecial conditional compilation flag, `#[cfg(doc)]`, set whenever building documentation on your\ncrate.\n\nThis feature was introduced as part of PR [#43348] to allow the platform-specific parts of the\nstandard library be documented.\n\n```rust\n#![feature(doc_cfg)]\n\n#[cfg(any(windows, doc))]\n#[doc(cfg(windows))]\n/// The application's icon in the notification area (a.k.a. system tray).\n///\n/// # Examples\n///\n/// ```no_run\n/// extern crate my_awesome_ui_library;\n/// use my_awesome_ui_library::current_app;\n/// use my_awesome_ui_library::windows::notification;\n///\n/// let icon = current_app().get::<notification::Icon>();\n/// icon.show();\n/// icon.show_message(\"Hello\");\n/// ```\npub struct Icon {\n // ...\n}\n```\n\n[#43781]: https://github.com/rust-lang/rust/issues/43781\n[#43348]: https://github.com/rust-lang/rust/issues/43348\n" } , LintCompletion { label : "allocator_internals" , description : "# `allocator_internals`\n\nThis feature does not have a tracking issue, it is an unstable implementation\ndetail of the `global_allocator` feature not intended for use outside the\ncompiler.\n\n------------------------\n" } , LintCompletion { label : "doc_masked" , description : "# `doc_masked`\n\nThe tracking issue for this feature is: [#44027]\n\n-----\n\nThe `doc_masked` feature allows a crate to exclude types from a given crate from appearing in lists\nof trait implementations. The specifics of the feature are as follows:\n\n1. When rustdoc encounters an `extern crate` statement annotated with a `#[doc(masked)]` attribute,\n it marks the crate as being masked.\n\n2. When listing traits a given type implements, rustdoc ensures that traits from masked crates are\n not emitted into the documentation.\n\n3. When listing types that implement a given trait, rustdoc ensures that types from masked crates\n are not emitted into the documentation.\n\nThis feature was introduced in PR [#44026] to ensure that compiler-internal and\nimplementation-specific types and traits were not included in the standard library's documentation.\nSuch types would introduce broken links into the documentation.\n\n[#44026]: https://github.com/rust-lang/rust/pull/44026\n[#44027]: https://github.com/rust-lang/rust/pull/44027\n" } , LintCompletion { label : "no_sanitize" , description : "# `no_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `no_sanitize` attribute can be used to selectively disable sanitizer\ninstrumentation in an annotated function. This might be useful to: avoid\ninstrumentation overhead in a performance critical function, or avoid\ninstrumenting code that contains constructs unsupported by given sanitizer.\n\nThe precise effect of this annotation depends on particular sanitizer in use.\nFor example, with `no_sanitize(thread)`, the thread sanitizer will no longer\ninstrument non-atomic store / load operations, but it will instrument atomic\noperations to avoid reporting false positives and provide meaning full stack\ntraces.\n\n## Examples\n\n``` rust\n#![feature(no_sanitize)]\n\n#[no_sanitize(address)]\nfn foo() {\n // ...\n}\n```\n" } , LintCompletion { label : "intrinsics" , description : "# `intrinsics`\n\nThe tracking issue for this feature is: None.\n\nIntrinsics are never intended to be stable directly, but intrinsics are often\nexported in some sort of stable manner. Prefer using the stable interfaces to\nthe intrinsic directly when you can.\n\n------------------------\n\n\nThese are imported as if they were FFI functions, with the special\n`rust-intrinsic` ABI. For example, if one was in a freestanding\ncontext, but wished to be able to `transmute` between types, and\nperform efficient pointer arithmetic, one would import those functions\nvia a declaration like\n\n```rust\n#![feature(intrinsics)]\n# fn main() {}\n\nextern \"rust-intrinsic\" {\n fn transmute<T, U>(x: T) -> U;\n\n fn offset<T>(dst: *const T, offset: isize) -> *const T;\n}\n```\n\nAs with any other FFI functions, these are always `unsafe` to call.\n\n" } , LintCompletion { label : "external_doc" , description : "# `external_doc`\n\nThe tracking issue for this feature is: [#44732]\n\nThe `external_doc` feature allows the use of the `include` parameter to the `#[doc]` attribute, to\ninclude external files in documentation. Use the attribute in place of, or in addition to, regular\ndoc comments and `#[doc]` attributes, and `rustdoc` will load the given file when it renders\ndocumentation for your crate.\n\nWith the following files in the same directory:\n\n`external-doc.md`:\n\n```markdown\n# My Awesome Type\n\nThis is the documentation for this spectacular type.\n```\n\n`lib.rs`:\n\n```no_run (needs-external-files)\n#![feature(external_doc)]\n\n#[doc(include = \"external-doc.md\")]\npub struct MyAwesomeType;\n```\n\n`rustdoc` will load the file `external-doc.md` and use it as the documentation for the `MyAwesomeType`\nstruct.\n\nWhen locating files, `rustdoc` will base paths in the `src/` directory, as if they were alongside the\n`lib.rs` for your crate. So if you want a `docs/` folder to live alongside the `src/` directory,\nstart your paths with `../docs/` for `rustdoc` to properly find the file.\n\nThis feature was proposed in [RFC #1990] and initially implemented in PR [#44781].\n\n[#44732]: https://github.com/rust-lang/rust/issues/44732\n[RFC #1990]: https://github.com/rust-lang/rfcs/pull/1990\n[#44781]: https://github.com/rust-lang/rust/pull/44781\n" } , LintCompletion { label : "inline_const" , description : "# `inline_const`\n\nThe tracking issue for this feature is: [#76001]\n\n------\n\nThis feature allows you to use inline constant expressions. For example, you can\nturn this code:\n\n```rust\n# fn add_one(x: i32) -> i32 { x + 1 }\nconst MY_COMPUTATION: i32 = 1 + 2 * 3 / 4;\n\nfn main() {\n let x = add_one(MY_COMPUTATION);\n}\n```\n\ninto this code:\n\n```rust\n#![feature(inline_const)]\n\n# fn add_one(x: i32) -> i32 { x + 1 }\nfn main() {\n let x = add_one(const { 1 + 2 * 3 / 4 });\n}\n```\n\nYou can also use inline constant expressions in patterns:\n\n```rust\n#![feature(inline_const)]\n\nconst fn one() -> i32 { 1 }\n\nlet some_int = 3;\nmatch some_int {\n const { 1 + 2 } => println!(\"Matched 1 + 2\"),\n const { one() } => println!(\"Matched const fn returning 1\"),\n _ => println!(\"Didn't match anything :(\"),\n}\n```\n\n[#76001]: https://github.com/rust-lang/rust/issues/76001\n" } , LintCompletion { label : "abi_thiscall" , description : "# `abi_thiscall`\n\nThe tracking issue for this feature is: [#42202]\n\n[#42202]: https://github.com/rust-lang/rust/issues/42202\n\n------------------------\n\nThe MSVC ABI on x86 Windows uses the `thiscall` calling convention for C++\ninstance methods by default; it is identical to the usual (C) calling\nconvention on x86 Windows except that the first parameter of the method,\nthe `this` pointer, is passed in the ECX register.\n" } , LintCompletion { label : "plugin" , description : "# `plugin`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin_registrar`] and `rustc_private` features.\n\n[`plugin_registrar`]: plugin-registrar.md\n\n------------------------\n\n`rustc` can load compiler plugins, which are user-provided libraries that\nextend the compiler's behavior with new lint checks, etc.\n\nA plugin is a dynamic library crate with a designated *registrar* function that\nregisters extensions with `rustc`. Other crates can load these extensions using\nthe crate attribute `#![plugin(...)]`. See the\n`rustc_driver::plugin` documentation for more about the\nmechanics of defining and loading a plugin.\n\nIn the vast majority of cases, a plugin should *only* be used through\n`#![plugin]` and not through an `extern crate` item. Linking a plugin would\npull in all of librustc_ast and librustc as dependencies of your crate. This is\ngenerally unwanted unless you are building another plugin.\n\nThe usual practice is to put compiler plugins in their own crate, separate from\nany `macro_rules!` macros or ordinary Rust code meant to be used by consumers\nof a library.\n\n# Lint plugins\n\nPlugins can extend [Rust's lint\ninfrastructure](../../reference/attributes/diagnostics.md#lint-check-attributes) with\nadditional checks for code style, safety, etc. Now let's write a plugin\n[`lint-plugin-test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs)\nthat warns about any item named `lintme`.\n\n```rust,ignore\n#![feature(plugin_registrar)]\n#![feature(box_syntax, rustc_private)]\n\nextern crate rustc_ast;\n\n// Load rustc as a plugin to get macros\nextern crate rustc_driver;\n#[macro_use]\nextern crate rustc_lint;\n#[macro_use]\nextern crate rustc_session;\n\nuse rustc_driver::plugin::Registry;\nuse rustc_lint::{EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};\nuse rustc_ast::ast;\ndeclare_lint!(TEST_LINT, Warn, \"Warn about items named 'lintme'\");\n\ndeclare_lint_pass!(Pass => [TEST_LINT]);\n\nimpl EarlyLintPass for Pass {\n fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {\n if it.ident.name.as_str() == \"lintme\" {\n cx.lint(TEST_LINT, |lint| {\n lint.build(\"item is named 'lintme'\").set_span(it.span).emit()\n });\n }\n }\n}\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n reg.lint_store.register_lints(&[&TEST_LINT]);\n reg.lint_store.register_early_pass(|| box Pass);\n}\n```\n\nThen code like\n\n```rust,ignore\n#![feature(plugin)]\n#![plugin(lint_plugin_test)]\n\nfn lintme() { }\n```\n\nwill produce a compiler warning:\n\n```txt\nfoo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default\nfoo.rs:4 fn lintme() { }\n ^~~~~~~~~~~~~~~\n```\n\nThe components of a lint plugin are:\n\n* one or more `declare_lint!` invocations, which define static `Lint` structs;\n\n* a struct holding any state needed by the lint pass (here, none);\n\n* a `LintPass`\n implementation defining how to check each syntax element. A single\n `LintPass` may call `span_lint` for several different `Lint`s, but should\n register them all through the `get_lints` method.\n\nLint passes are syntax traversals, but they run at a late stage of compilation\nwhere type information is available. `rustc`'s [built-in\nlints](https://github.com/rust-lang/rust/blob/master/src/librustc_session/lint/builtin.rs)\nmostly use the same infrastructure as lint plugins, and provide examples of how\nto access type information.\n\nLints defined by plugins are controlled by the usual [attributes and compiler\nflags](../../reference/attributes/diagnostics.md#lint-check-attributes), e.g.\n`#[allow(test_lint)]` or `-A test-lint`. These identifiers are derived from the\nfirst argument to `declare_lint!`, with appropriate case and punctuation\nconversion.\n\nYou can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,\nincluding those provided by plugins loaded by `foo.rs`.\n" } , LintCompletion { label : "optin_builtin_traits" , description : "# `optin_builtin_traits`\n\nThe tracking issue for this feature is [#13231] \n\n[#13231]: https://github.com/rust-lang/rust/issues/13231\n\n----\n\nThe `optin_builtin_traits` feature gate allows you to define auto traits.\n\nAuto traits, like [`Send`] or [`Sync`] in the standard library, are marker traits\nthat are automatically implemented for every type, unless the type, or a type it contains, \nhas explicitly opted out via a negative impl. (Negative impls are separately controlled\nby the `negative_impls` feature.)\n\n[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html\n[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html\n\n```rust,ignore\nimpl !Trait for Type\n```\n\nExample:\n\n```rust\n#![feature(negative_impls)]\n#![feature(optin_builtin_traits)]\n\nauto trait Valid {}\n\nstruct True;\nstruct False;\n\nimpl !Valid for False {}\n\nstruct MaybeValid<T>(T);\n\nfn must_be_valid<T: Valid>(_t: T) { }\n\nfn main() {\n // works\n must_be_valid( MaybeValid(True) );\n \n // compiler error - trait bound not satisfied\n // must_be_valid( MaybeValid(False) );\n}\n```\n\n## Automatic trait implementations\n\nWhen a type is declared as an `auto trait`, we will automatically\ncreate impls for every struct/enum/union, unless an explicit impl is\nprovided. These automatic impls contain a where clause for each field\nof the form `T: AutoTrait`, where `T` is the type of the field and\n`AutoTrait` is the auto trait in question. As an example, consider the\nstruct `List` and the auto trait `Send`:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n```\n\nPresuming that there is no explicit impl of `Send` for `List`, the\ncompiler will supply an automatic impl of the form:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n\nunsafe impl<T> Send for List<T>\nwhere\n T: Send, // from the field `data`\n Option<Box<List<T>>>: Send, // from the field `next`\n{ }\n```\n\nExplicit impls may be either positive or negative. They take the form:\n\n```rust,ignore\nimpl<...> AutoTrait for StructName<..> { }\nimpl<...> !AutoTrait for StructName<..> { }\n```\n\n## Coinduction: Auto traits permit cyclic matching\n\nUnlike ordinary trait matching, auto traits are **coinductive**. This\nmeans, in short, that cycles which occur in trait matching are\nconsidered ok. As an example, consider the recursive struct `List`\nintroduced in the previous section. In attempting to determine whether\n`List: Send`, we would wind up in a cycle: to apply the impl, we must\nshow that `Option<Box<List>>: Send`, which will in turn require\n`Box<List>: Send` and then finally `List: Send` again. Under ordinary\ntrait matching, this cycle would be an error, but for an auto trait it\nis considered a successful match.\n\n## Items\n\nAuto traits cannot have any trait items, such as methods or associated types. This ensures that we can generate default implementations.\n\n## Supertraits\n\nAuto traits cannot have supertraits. This is for soundness reasons, as the interaction of coinduction with implied bounds is difficult to reconcile.\n\n" } , LintCompletion { label : "impl_trait_in_bindings" , description : "# `impl_trait_in_bindings`\n\nThe tracking issue for this feature is: [#63065]\n\n[#63065]: https://github.com/rust-lang/rust/issues/63065\n\n------------------------\n\nThe `impl_trait_in_bindings` feature gate lets you use `impl Trait` syntax in\n`let`, `static`, and `const` bindings.\n\nA simple example is:\n\n```rust\n#![feature(impl_trait_in_bindings)]\n\nuse std::fmt::Debug;\n\nfn main() {\n let a: impl Debug + Clone = 42;\n let b = a.clone();\n println!(\"{:?}\", b); // prints `42`\n}\n```\n\nNote however that because the types of `a` and `b` are opaque in the above\nexample, calling inherent methods or methods outside of the specified traits\n(e.g., `a.abs()` or `b.abs()`) is not allowed, and yields an error.\n" } , LintCompletion { label : "abi_ptx" , description : "# `abi_ptx`\n\nThe tracking issue for this feature is: [#38788]\n\n[#38788]: https://github.com/rust-lang/rust/issues/38788\n\n------------------------\n\nWhen emitting PTX code, all vanilla Rust functions (`fn`) get translated to\n\"device\" functions. These functions are *not* callable from the host via the\nCUDA API so a crate with only device functions is not too useful!\n\nOTOH, \"global\" functions *can* be called by the host; you can think of them\nas the real public API of your crate. To produce a global function use the\n`\"ptx-kernel\"` ABI.\n\n<!-- NOTE(ignore) this example is specific to the nvptx targets -->\n\n``` rust,ignore\n#![feature(abi_ptx)]\n#![no_std]\n\npub unsafe extern \"ptx-kernel\" fn global_function() {\n device_function();\n}\n\npub fn device_function() {\n // ..\n}\n```\n\n``` text\n$ xargo rustc --target nvptx64-nvidia-cuda --release -- --emit=asm\n\n$ cat $(find -name '*.s')\n//\n// Generated by LLVM NVPTX Back-End\n//\n\n.version 3.2\n.target sm_20\n.address_size 64\n\n // .globl _ZN6kernel15global_function17h46111ebe6516b382E\n\n.visible .entry _ZN6kernel15global_function17h46111ebe6516b382E()\n{\n\n\n ret;\n}\n\n // .globl _ZN6kernel15device_function17hd6a0e4993bbf3f78E\n.visible .func _ZN6kernel15device_function17hd6a0e4993bbf3f78E()\n{\n\n\n ret;\n}\n```\n" } , LintCompletion { label : "dec2flt" , description : "# `dec2flt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "int_error_internals" , description : "# `int_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "llvm_asm" , description : "# `llvm_asm`\n\nThe tracking issue for this feature is: [#70173]\n\n[#70173]: https://github.com/rust-lang/rust/issues/70173\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `llvm_asm!` macro.\n\n```rust,ignore\nllvm_asm!(assembly template\n : output operands\n : input operands\n : clobbers\n : options\n );\n```\n\nAny use of `llvm_asm` is feature gated (requires `#![feature(llvm_asm)]` on the\ncrate to allow) and of course requires an `unsafe` block.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but\n> all platforms are supported.\n\n## Assembly template\n\nThe `assembly template` is the only required parameter and must be a\nliteral string (i.e. `\"\"`)\n\n```rust\n#![feature(llvm_asm)]\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn foo() {\n unsafe {\n llvm_asm!(\"NOP\");\n }\n}\n\n// Other platforms:\n#[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\nfn foo() { /* ... */ }\n\nfn main() {\n // ...\n foo();\n // ...\n}\n```\n\n(The `feature(llvm_asm)` and `#[cfg]`s are omitted from now on.)\n\nOutput operands, input operands, clobbers and options are all optional\nbut you must add the right number of `:` if you skip them:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\"\n :\n :\n : \"eax\"\n );\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nWhitespace also doesn't matter:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\" ::: \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## Operands\n\nInput and output operands follow the same format: `:\n\"constraints1\"(expr1), \"constraints2\"(expr2), ...\"`. Output operand\nexpressions must be mutable place, or not yet assigned:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn add(a: i32, b: i32) -> i32 {\n let c: i32;\n unsafe {\n llvm_asm!(\"add $2, $0\"\n : \"=r\"(c)\n : \"0\"(a), \"r\"(b)\n );\n }\n c\n}\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn add(a: i32, b: i32) -> i32 { a + b }\n\nfn main() {\n assert_eq!(add(3, 14159), 14162)\n}\n```\n\nIf you would like to use real operands in this position, however,\nyou are required to put curly braces `{}` around the register that\nyou want, and you are required to put the specific size of the\noperand. This is useful for very low level programming, where\nwhich register you use is important:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# unsafe fn read_byte_in(port: u16) -> u8 {\nlet result: u8;\nllvm_asm!(\"in %dx, %al\" : \"={al}\"(result) : \"{dx}\"(port));\nresult\n# }\n```\n\n## Clobbers\n\nSome instructions modify registers which might otherwise have held\ndifferent values so we use the clobbers list to indicate to the\ncompiler not to assume any values loaded into those registers will\nstay valid.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\n// Put the value 0x200 in eax:\nllvm_asm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nInput and output registers need not be listed since that information\nis already communicated by the given constraints. Otherwise, any other\nregisters used either implicitly or explicitly should be listed.\n\nIf the assembly changes the condition code register `cc` should be\nspecified as one of the clobbers. Similarly, if the assembly modifies\nmemory, `memory` should also be specified.\n\n## Options\n\nThe last section, `options` is specific to Rust. The format is comma\nseparated literal strings (i.e. `:\"foo\", \"bar\", \"baz\"`). It's used to\nspecify some extra info about the inline assembly:\n\nCurrent valid options are:\n\n1. `volatile` - specifying this is analogous to\n `__asm__ __volatile__ (...)` in gcc/clang.\n2. `alignstack` - certain instructions expect the stack to be\n aligned a certain way (i.e. SSE) and specifying this indicates to\n the compiler to insert its usual stack alignment code\n3. `intel` - use intel syntax instead of the default AT&T.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() {\nlet result: i32;\nunsafe {\n llvm_asm!(\"mov eax, 2\" : \"={eax}\"(result) : : : \"intel\")\n}\nprintln!(\"eax is currently {}\", result);\n# }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## More Information\n\nThe current implementation of the `llvm_asm!` macro is a direct binding to [LLVM's\ninline assembler expressions][llvm-docs], so be sure to check out [their\ndocumentation as well][llvm-docs] for more information about clobbers,\nconstraints, etc.\n\n[llvm-docs]: http://llvm.org/docs/LangRef.html#inline-assembler-expressions\n\nIf you need more power and don't mind losing some of the niceties of\n`llvm_asm!`, check out [global_asm](global-asm.md).\n" } , LintCompletion { label : "default_free_fn" , description : "# `default_free_fn`\n\nThe tracking issue for this feature is: [#73014]\n\n[#73014]: https://github.com/rust-lang/rust/issues/73014\n\n------------------------\n\nAdds a free `default()` function to the `std::default` module. This function\njust forwards to [`Default::default()`], but may remove repetition of the word\n\"default\" from the call site.\n\n[`Default::default()`]: https://doc.rust-lang.org/nightly/std/default/trait.Default.html#tymethod.default\n\nHere is an example:\n\n```rust\n#![feature(default_free_fn)]\nuse std::default::default;\n\n#[derive(Default)]\nstruct AppConfig {\n foo: FooConfig,\n bar: BarConfig,\n}\n\n#[derive(Default)]\nstruct FooConfig {\n foo: i32,\n}\n\n#[derive(Default)]\nstruct BarConfig {\n bar: f32,\n baz: u8,\n}\n\nfn main() {\n let options = AppConfig {\n foo: default(),\n bar: BarConfig {\n bar: 10.1,\n ..default()\n },\n };\n}\n```\n" } , LintCompletion { label : "libstd_thread_internals" , description : "# `libstd_thread_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "char_error_internals" , description : "# `char_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_handle" , description : "# `windows_handle`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "global_asm" , description : "# `global_asm`\n\nThe tracking issue for this feature is: [#35119]\n\n[#35119]: https://github.com/rust-lang/rust/issues/35119\n\n------------------------\n\nThe `global_asm!` macro allows the programmer to write arbitrary\nassembly outside the scope of a function body, passing it through\n`rustc` and `llvm` to the assembler. The macro is a no-frills\ninterface to LLVM's concept of [module-level inline assembly]. That is,\nall caveats applicable to LLVM's module-level inline assembly apply\nto `global_asm!`.\n\n[module-level inline assembly]: http://llvm.org/docs/LangRef.html#module-level-inline-assembly\n\n`global_asm!` fills a role not currently satisfied by either `asm!`\nor `#[naked]` functions. The programmer has _all_ features of the\nassembler at their disposal. The linker will expect to resolve any\nsymbols defined in the inline assembly, modulo any symbols marked as\nexternal. It also means syntax for directives and assembly follow the\nconventions of the assembler in your toolchain.\n\nA simple usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# you also need relevant target_arch cfgs\nglobal_asm!(include_str!(\"something_neato.s\"));\n```\n\nAnd a more complicated usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# #![cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n\npub mod sally {\n global_asm!(r#\"\n .global foo\n foo:\n jmp baz\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn baz() {}\n}\n\n// the symbols `foo` and `bar` are global, no matter where\n// `global_asm!` was used.\nextern \"C\" {\n fn foo();\n fn bar();\n}\n\npub mod harry {\n global_asm!(r#\"\n .global bar\n bar:\n jmp quux\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn quux() {}\n}\n```\n\nYou may use `global_asm!` multiple times, anywhere in your crate, in\nwhatever way suits you. The effect is as if you concatenated all\nusages and placed the larger, single usage in the crate root.\n\n------------------------\n\nIf you don't need quite as much power and flexibility as\n`global_asm!` provides, and you don't mind restricting your inline\nassembly to `fn` bodies only, you might try the\n[asm](asm.md) feature instead.\n" } , LintCompletion { label : "windows_c" , description : "# `windows_c`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "asm" , description : "# `asm`\n\nThe tracking issue for this feature is: [#72016]\n\n[#72016]: https://github.com/rust-lang/rust/issues/72016\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `asm!` macro.\n\n# Guide-level explanation\n[guide-level-explanation]: #guide-level-explanation\n\nRust provides support for inline assembly via the `asm!` macro.\nIt can be used to embed handwritten assembly in the assembly output generated by the compiler.\nGenerally this should not be necessary, but might be where the required performance or timing\ncannot be otherwise achieved. Accessing low level hardware primitives, e.g. in kernel code, may also demand this functionality.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but other architectures are also supported.\n\nInline assembly is currently supported on the following architectures:\n- x86 and x86-64\n- ARM\n- AArch64\n- RISC-V\n- NVPTX\n- Hexagon\n- MIPS32r2 and MIPS64r2\n\n## Basic usage\n\nLet us start with the simplest possible example:\n\n```rust,allow_fail\n# #![feature(asm)]\nunsafe {\n asm!(\"nop\");\n}\n```\n\nThis will insert a NOP (no operation) instruction into the assembly generated by the compiler.\nNote that all `asm!` invocations have to be inside an `unsafe` block, as they could insert\narbitrary instructions and break various invariants. The instructions to be inserted are listed\nin the first argument of the `asm!` macro as a string literal.\n\n## Inputs and outputs\n\nNow inserting an instruction that does nothing is rather boring. Let us do something that\nactually acts on data:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64;\nunsafe {\n asm!(\"mov {}, 5\", out(reg) x);\n}\nassert_eq!(x, 5);\n```\n\nThis will write the value `5` into the `u64` variable `x`.\nYou can see that the string literal we use to specify instructions is actually a template string.\nIt is governed by the same rules as Rust [format strings][format-syntax].\nThe arguments that are inserted into the template however look a bit different then you may\nbe familiar with. First we need to specify if the variable is an input or an output of the\ninline assembly. In this case it is an output. We declared this by writing `out`.\nWe also need to specify in what kind of register the assembly expects the variable.\nIn this case we put it in an arbitrary general purpose register by specifying `reg`.\nThe compiler will choose an appropriate register to insert into\nthe template and will read the variable from there after the inline assembly finishes executing.\n\nLet us see another example that also uses an input:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet i: u64 = 3;\nlet o: u64;\nunsafe {\n asm!(\n \"mov {0}, {1}\",\n \"add {0}, {number}\",\n out(reg) o,\n in(reg) i,\n number = const 5,\n );\n}\nassert_eq!(o, 8);\n```\n\nThis will add `5` to the input in variable `i` and write the result to variable `o`.\nThe particular way this assembly does this is first copying the value from `i` to the output,\nand then adding `5` to it.\n\nThe example shows a few things:\n\nFirst, we can see that `asm!` allows multiple template string arguments; each\none is treated as a separate line of assembly code, as if they were all joined\ntogether with newlines between them. This makes it easy to format assembly\ncode.\n\nSecond, we can see that inputs are declared by writing `in` instead of `out`.\n\nThird, one of our operands has a type we haven't seen yet, `const`.\nThis tells the compiler to expand this argument to value directly inside the assembly template.\nThis is only possible for constants and literals.\n\nFourth, we can see that we can specify an argument number, or name as in any format string.\nFor inline assembly templates this is particularly useful as arguments are often used more than once.\nFor more complex inline assembly using this facility is generally recommended, as it improves\nreadability, and allows reordering instructions without changing the argument order.\n\nWe can further refine the above example to avoid the `mov` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u64 = 3;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x, number = const 5);\n}\nassert_eq!(x, 8);\n```\n\nWe can see that `inout` is used to specify an argument that is both input and output.\nThis is different from specifying an input and output separately in that it is guaranteed to assign both to the same register.\n\nIt is also possible to specify different variables for the input and output parts of an `inout` operand:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64 = 3;\nlet y: u64;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x => y, number = const 5);\n}\nassert_eq!(y, 8);\n```\n\n## Late output operands\n\nThe Rust compiler is conservative with its allocation of operands. It is assumed that an `out`\ncan be written at any time, and can therefore not share its location with any other argument.\nHowever, to guarantee optimal performance it is important to use as few registers as possible,\nso they won't have to be saved and reloaded around the inline assembly block.\nTo achieve this Rust provides a `lateout` specifier. This can be used on any output that is\nwritten only after all inputs have been consumed.\nThere is also a `inlateout` variant of this specifier.\n\nHere is an example where `inlateout` *cannot* be used:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nlet c: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n \"add {0}, {2}\",\n inout(reg) a,\n in(reg) b,\n in(reg) c,\n );\n}\nassert_eq!(a, 12);\n```\n\nHere the compiler is free to allocate the same register for inputs `b` and `c` since it knows they have the same value. However it must allocate a separate register for `a` since it uses `inout` and not `inlateout`. If `inlateout` was used, then `a` and `c` could be allocated to the same register, in which case the first instruction to overwrite the value of `c` and cause the assembly code to produce the wrong result.\n\nHowever the following example can use `inlateout` since the output is only modified after all input registers have been read:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\"add {0}, {1}\", inlateout(reg) a, in(reg) b);\n}\nassert_eq!(a, 8);\n```\n\nAs you can see, this assembly fragment will still work correctly if `a` and `b` are assigned to the same register.\n\n## Explicit register operands\n\nSome instructions require that the operands be in a specific register.\nTherefore, Rust inline assembly provides some more specific constraint specifiers.\nWhile `reg` is generally available on any architecture, these are highly architecture specific. E.g. for x86 the general purpose registers `eax`, `ebx`, `ecx`, `edx`, `ebp`, `esi`, and `edi`\namong others can be addressed by their name.\n\n```rust,allow_fail,no_run\n# #![feature(asm)]\nlet cmd = 0xd1;\nunsafe {\n asm!(\"out 0x64, eax\", in(\"eax\") cmd);\n}\n```\n\nIn this example we call the `out` instruction to output the content of the `cmd` variable\nto port `0x64`. Since the `out` instruction only accepts `eax` (and its sub registers) as operand\nwe had to use the `eax` constraint specifier.\n\nNote that unlike other operand types, explicit register operands cannot be used in the template string: you can't use `{}` and should write the register name directly instead. Also, they must appear at the end of the operand list after all other operand types.\n\nConsider this example which uses the x86 `mul` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nfn mul(a: u64, b: u64) -> u128 {\n let lo: u64;\n let hi: u64;\n\n unsafe {\n asm!(\n // The x86 mul instruction takes rax as an implicit input and writes\n // the 128-bit result of the multiplication to rax:rdx.\n \"mul {}\",\n in(reg) a,\n inlateout(\"rax\") b => lo,\n lateout(\"rdx\") hi\n );\n }\n\n ((hi as u128) << 64) + lo as u128\n}\n```\n\nThis uses the `mul` instruction to multiply two 64-bit inputs with a 128-bit result.\nThe only explicit operand is a register, that we fill from the variable `a`.\nThe second operand is implicit, and must be the `rax` register, which we fill from the variable `b`.\nThe lower 64 bits of the result are stored in `rax` from which we fill the variable `lo`.\nThe higher 64 bits are stored in `rdx` from which we fill the variable `hi`.\n\n## Clobbered registers\n\nIn many cases inline assembly will modify state that is not needed as an output.\nUsually this is either because we have to use a scratch register in the assembly,\nor instructions modify state that we don't need to further examine.\nThis state is generally referred to as being \"clobbered\".\nWe need to tell the compiler about this since it may need to save and restore this state\naround the inline assembly block.\n\n```rust,allow_fail\n# #![feature(asm)]\nlet ebx: u32;\nlet ecx: u32;\n\nunsafe {\n asm!(\n \"cpuid\",\n // EAX 4 selects the \"Deterministic Cache Parameters\" CPUID leaf\n inout(\"eax\") 4 => _,\n // ECX 0 selects the L0 cache information.\n inout(\"ecx\") 0 => ecx,\n lateout(\"ebx\") ebx,\n lateout(\"edx\") _,\n );\n}\n\nprintln!(\n \"L1 Cache: {}\",\n ((ebx >> 22) + 1) * (((ebx >> 12) & 0x3ff) + 1) * ((ebx & 0xfff) + 1) * (ecx + 1)\n);\n```\n\nIn the example above we use the `cpuid` instruction to get the L1 cache size.\nThis instruction writes to `eax`, `ebx`, `ecx`, and `edx`, but for the cache size we only care about the contents of `ebx` and `ecx`.\n\nHowever we still need to tell the compiler that `eax` and `edx` have been modified so that it can save any values that were in these registers before the asm. This is done by declaring these as outputs but with `_` instead of a variable name, which indicates that the output value is to be discarded.\n\nThis can also be used with a general register class (e.g. `reg`) to obtain a scratch register for use inside the asm code:\n\n```rust,allow_fail\n# #![feature(asm)]\n// Multiply x by 6 using shifts and adds\nlet mut x: u64 = 4;\nunsafe {\n asm!(\n \"mov {tmp}, {x}\",\n \"shl {tmp}, 1\",\n \"shl {x}, 2\",\n \"add {x}, {tmp}\",\n x = inout(reg) x,\n tmp = out(reg) _,\n );\n}\nassert_eq!(x, 4 * 6);\n```\n\n## Symbol operands\n\nA special operand type, `sym`, allows you to use the symbol name of a `fn` or `static` in inline assembly code.\nThis allows you to call a function or access a global variable without needing to keep its address in a register.\n\n```rust,allow_fail\n# #![feature(asm)]\nextern \"C\" fn foo(arg: i32) {\n println!(\"arg = {}\", arg);\n}\n\nfn call_foo(arg: i32) {\n unsafe {\n asm!(\n \"call {}\",\n sym foo,\n // 1st argument in rdi, which is caller-saved\n inout(\"rdi\") arg => _,\n // All caller-saved registers must be marked as clobberred\n out(\"rax\") _, out(\"rcx\") _, out(\"rdx\") _, out(\"rsi\") _,\n out(\"r8\") _, out(\"r9\") _, out(\"r10\") _, out(\"r11\") _,\n out(\"xmm0\") _, out(\"xmm1\") _, out(\"xmm2\") _, out(\"xmm3\") _,\n out(\"xmm4\") _, out(\"xmm5\") _, out(\"xmm6\") _, out(\"xmm7\") _,\n out(\"xmm8\") _, out(\"xmm9\") _, out(\"xmm10\") _, out(\"xmm11\") _,\n out(\"xmm12\") _, out(\"xmm13\") _, out(\"xmm14\") _, out(\"xmm15\") _,\n )\n }\n}\n```\n\nNote that the `fn` or `static` item does not need to be public or `#[no_mangle]`:\nthe compiler will automatically insert the appropriate mangled symbol name into the assembly code.\n\n## Register template modifiers\n\nIn some cases, fine control is needed over the way a register name is formatted when inserted into the template string. This is needed when an architecture's assembly language has several names for the same register, each typically being a \"view\" over a subset of the register (e.g. the low 32 bits of a 64-bit register).\n\nBy default the compiler will always choose the name that refers to the full register size (e.g. `rax` on x86-64, `eax` on x86, etc).\n\nThis default can be overriden by using modifiers on the template string operands, just like you would with format strings:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u16 = 0xab;\n\nunsafe {\n asm!(\"mov {0:h}, {0:l}\", inout(reg_abcd) x);\n}\n\nassert_eq!(x, 0xabab);\n```\n\nIn this example, we use the `reg_abcd` register class to restrict the register allocator to the 4 legacy x86 register (`ax`, `bx`, `cx`, `dx`) of which the first two bytes can be addressed independently.\n\nLet us assume that the register allocator has chosen to allocate `x` in the `ax` register.\nThe `h` modifier will emit the register name for the high byte of that register and the `l` modifier will emit the register name for the low byte. The asm code will therefore be expanded as `mov ah, al` which copies the low byte of the value into the high byte.\n\nIf you use a smaller data type (e.g. `u16`) with an operand and forget the use template modifiers, the compiler will emit a warning and suggest the correct modifier to use.\n\n## Memory address operands\n\nSometimes assembly instructions require operands passed via memory addresses/memory locations.\nYou have to manually use the memory address syntax specified by the respectively architectures.\nFor example, in x86/x86_64 and intel assembly syntax, you should wrap inputs/outputs in `[]`\nto indicate they are memory operands:\n\n```rust,allow_fail\n# #![feature(asm, llvm_asm)]\n# fn load_fpu_control_word(control: u16) {\nunsafe {\n asm!(\"fldcw [{}]\", in(reg) &control, options(nostack));\n\n // Previously this would have been written with the deprecated `llvm_asm!` like this\n llvm_asm!(\"fldcw $0\" :: \"m\" (control) :: \"volatile\");\n}\n# }\n```\n\n## Options\n\nBy default, an inline assembly block is treated the same way as an external FFI function call with a custom calling convention: it may read/write memory, have observable side effects, etc. However in many cases, it is desirable to give the compiler more information about what the assembly code is actually doing so that it can optimize better.\n\nLet's take our previous example of an `add` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n inlateout(reg) a, in(reg) b,\n options(pure, nomem, nostack),\n );\n}\nassert_eq!(a, 8);\n```\n\nOptions can be provided as an optional final argument to the `asm!` macro. We specified three options here:\n- `pure` means that the asm code has no observable side effects and that its output depends only on its inputs. This allows the compiler optimizer to call the inline asm fewer times or even eliminate it entirely.\n- `nomem` means that the asm code does not read or write to memory. By default the compiler will assume that inline assembly can read or write any memory address that is accessible to it (e.g. through a pointer passed as an operand, or a global).\n- `nostack` means that the asm code does not push any data onto the stack. This allows the compiler to use optimizations such as the stack red zone on x86-64 to avoid stack pointer adjustments.\n\nThese allow the compiler to better optimize code using `asm!`, for example by eliminating pure `asm!` blocks whose outputs are not needed.\n\nSee the reference for the full list of available options and their effects.\n\n# Reference-level explanation\n[reference-level-explanation]: #reference-level-explanation\n\nInline assembler is implemented as an unsafe macro `asm!()`.\nThe first argument to this macro is a template string literal used to build the final assembly.\nThe following arguments specify input and output operands.\nWhen required, options are specified as the final argument.\n\nThe following ABNF specifies the general syntax:\n\n```ignore\ndir_spec := \"in\" / \"out\" / \"lateout\" / \"inout\" / \"inlateout\"\nreg_spec := <register class> / \"<explicit register>\"\noperand_expr := expr / \"_\" / expr \"=>\" expr / expr \"=>\" \"_\"\nreg_operand := dir_spec \"(\" reg_spec \")\" operand_expr\noperand := reg_operand / \"const\" const_expr / \"sym\" path\noption := \"pure\" / \"nomem\" / \"readonly\" / \"preserves_flags\" / \"noreturn\" / \"nostack\" / \"att_syntax\"\noptions := \"options(\" option *[\",\" option] [\",\"] \")\"\nasm := \"asm!(\" format_string *(\",\" format_string) *(\",\" [ident \"=\"] operand) [\",\" options] [\",\"] \")\"\n```\n\nThe macro will initially be supported only on ARM, AArch64, Hexagon, x86, x86-64 and RISC-V targets. Support for more targets may be added in the future. The compiler will emit an error if `asm!` is used on an unsupported target.\n\n[format-syntax]: https://doc.rust-lang.org/std/fmt/#syntax\n\n## Template string arguments\n\nThe assembler template uses the same syntax as [format strings][format-syntax] (i.e. placeholders are specified by curly braces). The corresponding arguments are accessed in order, by index, or by name. However, implicit named arguments (introduced by [RFC #2795][rfc-2795]) are not supported.\n\nAn `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code. All template string arguments must appear before any other arguments.\n\nAs with format strings, named arguments must appear after positional arguments. Explicit register operands must appear at the end of the operand list, after named arguments if any.\n\nExplicit register operands cannot be used by placeholders in the template string. All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.\n\nThe exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler.\n\nThe 5 targets specified in this RFC (x86, ARM, AArch64, RISC-V, Hexagon) all use the assembly code syntax of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior.\n\n[rfc-2795]: https://github.com/rust-lang/rfcs/pull/2795\n\n## Operand type\n\nSeveral types of operands are supported:\n\n* `in(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - The allocated register must contain the same value at the end of the asm code (except if a `lateout` is allocated to the same register).\n* `out(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain an undefined value at the start of the asm code.\n - `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n* `lateout(<reg>) <expr>`\n - Identical to `out` except that the register allocator can reuse a register allocated to an `in`.\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `inout(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register is written to at the end of the asm code.\n* `inout(<reg>) <in expr> => <out expr>`\n - Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`.\n - `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n - `<in expr>` and `<out expr>` may have different types.\n* `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>`\n - Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`).\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `const <expr>`\n - `<expr>` must be an integer or floating-point constant expression.\n - The value of the expression is formatted as a string and substituted directly into the asm template string.\n* `sym <path>`\n - `<path>` must refer to a `fn` or `static`.\n - A mangled symbol name referring to the item is substituted into the asm template string.\n - The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).\n - `<path>` is allowed to point to a `#[thread_local]` static, in which case the asm code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.\n\nOperand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output.\n\n## Register operands\n\nInput and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `\"eax\"`) while register classes are specified as identifiers (e.g. `reg`). Using string literals for register names enables support for architectures that use special characters in register names, such as MIPS (`$0`, `$1`, etc).\n\nNote that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register. It is a compile-time error to use the same explicit register for two input operands or two output operands. Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.\n\nOnly the following types are allowed as operands for inline assembly:\n- Integers (signed and unsigned)\n- Floating-point numbers\n- Pointers (thin only)\n- Function pointers\n- SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM).\n\nHere is the list of currently supported register classes:\n\n| Architecture | Register class | Registers | LLVM constraint code |\n| ------------ | -------------- | --------- | -------------------- |\n| x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `r[8-15]` (x86-64 only) | `r` |\n| x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` |\n| x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` |\n| x86-64 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `r[8-15]b`, `ah`\\*, `bh`\\*, `ch`\\*, `dh`\\* | `q` |\n| x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` |\n| x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` |\n| x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` |\n| x86 | `kreg` | `k[1-7]` | `Yk` |\n| AArch64 | `reg` | `x[0-28]`, `x30` | `r` |\n| AArch64 | `vreg` | `v[0-31]` | `w` |\n| AArch64 | `vreg_low16` | `v[0-15]` | `x` |\n| ARM | `reg` | `r[0-5]` `r7`\\*, `r[8-10]`, `r11`\\*, `r12`, `r14` | `r` |\n| ARM (Thumb) | `reg_thumb` | `r[0-r7]` | `l` |\n| ARM (ARM) | `reg_thumb` | `r[0-r10]`, `r12`, `r14` | `l` |\n| ARM | `sreg` | `s[0-31]` | `t` |\n| ARM | `sreg_low16` | `s[0-15]` | `x` |\n| ARM | `dreg` | `d[0-31]` | `w` |\n| ARM | `dreg_low16` | `d[0-15]` | `t` |\n| ARM | `dreg_low8` | `d[0-8]` | `x` |\n| ARM | `qreg` | `q[0-15]` | `w` |\n| ARM | `qreg_low8` | `q[0-7]` | `t` |\n| ARM | `qreg_low4` | `q[0-3]` | `x` |\n| MIPS | `reg` | `$[2-25]` | `r` |\n| MIPS | `freg` | `$f[0-31]` | `f` |\n| NVPTX | `reg16` | None\\* | `h` |\n| NVPTX | `reg32` | None\\* | `r` |\n| NVPTX | `reg64` | None\\* | `l` |\n| RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` |\n| RISC-V | `freg` | `f[0-31]` | `f` |\n| Hexagon | `reg` | `r[0-28]` | `r` |\n\n> **Note**: On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.\n>\n> Note #2: On x86-64 the high byte registers (e.g. `ah`) are only available when used as an explicit register. Specifying the `reg_byte` register class for an operand will always allocate a low byte register.\n>\n> Note #3: NVPTX doesn't have a fixed register set, so named registers are not supported.\n>\n> Note #4: On ARM the frame pointer is either `r7` or `r11` depending on the platform.\n\nAdditional register classes may be added in the future based on demand (e.g. MMX, x87, etc).\n\nEach register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled.\n\n| Architecture | Register class | Target feature | Allowed types |\n| ------------ | -------------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `i16`, `i32`, `f32` |\n| x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` |\n| x86 | `reg_byte` | None | `i8` |\n| x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` |\n| x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` <br> `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8` |\n| x86 | `kreg` | `axv512f` | `i8`, `i16` |\n| x86 | `kreg` | `axv512bw` | `i32`, `i64` |\n| AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| AArch64 | `vreg` | `fp` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, <br> `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| ARM | `sreg` | `vfp2` | `i32`, `f32` |\n| ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` |\n| ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` |\n| MIPS32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| MIPS32 | `freg` | None | `f32`, `f64` |\n| MIPS64 | `reg` | None | `i8`, `i16`, `i32`, `i64`, `f32`, `f64` |\n| MIPS64 | `freg` | None | `f32`, `f64` |\n| NVPTX | `reg16` | None | `i8`, `i16` |\n| NVPTX | `reg32` | None | `i8`, `i16`, `i32`, `f32` |\n| NVPTX | `reg64` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V | `freg` | `f` | `f32` |\n| RISC-V | `freg` | `d` | `f64` |\n| Hexagon | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n\n> **Note**: For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target).\n\nIf a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture.\n\nWhen separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types.\n\n## Register names\n\nSome registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases:\n\n| Architecture | Base register | Aliases |\n| ------------ | ------------- | ------- |\n| x86 | `ax` | `eax`, `rax` |\n| x86 | `bx` | `ebx`, `rbx` |\n| x86 | `cx` | `ecx`, `rcx` |\n| x86 | `dx` | `edx`, `rdx` |\n| x86 | `si` | `esi`, `rsi` |\n| x86 | `di` | `edi`, `rdi` |\n| x86 | `bp` | `bpl`, `ebp`, `rbp` |\n| x86 | `sp` | `spl`, `esp`, `rsp` |\n| x86 | `ip` | `eip`, `rip` |\n| x86 | `st(0)` | `st` |\n| x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` |\n| x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` |\n| AArch64 | `x[0-30]` | `w[0-30]` |\n| AArch64 | `x29` | `fp` |\n| AArch64 | `x30` | `lr` |\n| AArch64 | `sp` | `wsp` |\n| AArch64 | `xzr` | `wzr` |\n| AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` |\n| ARM | `r[0-3]` | `a[1-4]` |\n| ARM | `r[4-9]` | `v[1-6]` |\n| ARM | `r9` | `rfp` |\n| ARM | `r10` | `sl` |\n| ARM | `r11` | `fp` |\n| ARM | `r12` | `ip` |\n| ARM | `r13` | `sp` |\n| ARM | `r14` | `lr` |\n| ARM | `r15` | `pc` |\n| RISC-V | `x0` | `zero` |\n| RISC-V | `x1` | `ra` |\n| RISC-V | `x2` | `sp` |\n| RISC-V | `x3` | `gp` |\n| RISC-V | `x4` | `tp` |\n| RISC-V | `x[5-7]` | `t[0-2]` |\n| RISC-V | `x8` | `fp`, `s0` |\n| RISC-V | `x9` | `s1` |\n| RISC-V | `x[10-17]` | `a[0-7]` |\n| RISC-V | `x[18-27]` | `s[2-11]` |\n| RISC-V | `x[28-31]` | `t[3-6]` |\n| RISC-V | `f[0-7]` | `ft[0-7]` |\n| RISC-V | `f[8-9]` | `fs[0-1]` |\n| RISC-V | `f[10-17]` | `fa[0-7]` |\n| RISC-V | `f[18-27]` | `fs[2-11]` |\n| RISC-V | `f[28-31]` | `ft[8-11]` |\n| Hexagon | `r29` | `sp` |\n| Hexagon | `r30` | `fr` |\n| Hexagon | `r31` | `lr` |\n\nSome registers cannot be used for input or output operands:\n\n| Architecture | Unsupported register | Reason |\n| ------------ | -------------------- | ------ |\n| All | `sp` | The stack pointer must be restored to its original value at the end of an asm code block. |\n| All | `bp` (x86), `x29` (AArch64), `x8` (RISC-V), `fr` (Hexagon), `$fp` (MIPS) | The frame pointer cannot be used as an input or output. |\n| ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output. |\n| ARM | `r6` | `r6` is used internally by LLVM as a base pointer and therefore cannot be used as an input or output. |\n| x86 | `k0` | This is a constant zero register which can't be modified. |\n| x86 | `ip` | This is the program counter, not a real register. |\n| x86 | `mm[0-7]` | MMX registers are not currently supported (but may be in the future). |\n| x86 | `st([0-7])` | x87 registers are not currently supported (but may be in the future). |\n| AArch64 | `xzr` | This is a constant zero register which can't be modified. |\n| ARM | `pc` | This is the program counter, not a real register. |\n| MIPS | `$0` or `$zero` | This is a constant zero register which can't be modified. |\n| MIPS | `$1` or `$at` | Reserved for assembler. |\n| MIPS | `$26`/`$k0`, `$27`/`$k1` | OS-reserved registers. |\n| MIPS | `$28`/`$gp` | Global pointer cannot be used as inputs or outputs. |\n| MIPS | `$ra` | Return address cannot be used as inputs or outputs. |\n| RISC-V | `x0` | This is a constant zero register which can't be modified. |\n| RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. |\n| Hexagon | `lr` | This is the link register which cannot be used as an input or output. |\n\nIn some cases LLVM will allocate a \"reserved register\" for `reg` operands even though this register cannot be explicitly specified. Assembly code making use of reserved registers should be careful since `reg` operands may alias with those registers. Reserved registers are:\n- The frame pointer on all architectures.\n- `r6` on ARM.\n\n## Template modifiers\n\nThe placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string. Only one modifier is allowed per template placeholder.\n\nThe supported modifiers are a subset of LLVM's (and GCC's) [asm template argument modifiers][llvm-argmod], but do not use the same letter codes.\n\n| Architecture | Register class | Modifier | Example output | LLVM modifier |\n| ------------ | -------------- | -------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `eax` | `k` |\n| x86-64 | `reg` | None | `rax` | `q` |\n| x86-32 | `reg_abcd` | `l` | `al` | `b` |\n| x86-64 | `reg` | `l` | `al` | `b` |\n| x86 | `reg_abcd` | `h` | `ah` | `h` |\n| x86 | `reg` | `x` | `ax` | `w` |\n| x86 | `reg` | `e` | `eax` | `k` |\n| x86-64 | `reg` | `r` | `rax` | `q` |\n| x86 | `reg_byte` | None | `al` / `ah` | None |\n| x86 | `xmm_reg` | None | `xmm0` | `x` |\n| x86 | `ymm_reg` | None | `ymm0` | `t` |\n| x86 | `zmm_reg` | None | `zmm0` | `g` |\n| x86 | `*mm_reg` | `x` | `xmm0` | `x` |\n| x86 | `*mm_reg` | `y` | `ymm0` | `t` |\n| x86 | `*mm_reg` | `z` | `zmm0` | `g` |\n| x86 | `kreg` | None | `k1` | None |\n| AArch64 | `reg` | None | `x0` | `x` |\n| AArch64 | `reg` | `w` | `w0` | `w` |\n| AArch64 | `reg` | `x` | `x0` | `x` |\n| AArch64 | `vreg` | None | `v0` | None |\n| AArch64 | `vreg` | `v` | `v0` | None |\n| AArch64 | `vreg` | `b` | `b0` | `b` |\n| AArch64 | `vreg` | `h` | `h0` | `h` |\n| AArch64 | `vreg` | `s` | `s0` | `s` |\n| AArch64 | `vreg` | `d` | `d0` | `d` |\n| AArch64 | `vreg` | `q` | `q0` | `q` |\n| ARM | `reg` | None | `r0` | None |\n| ARM | `sreg` | None | `s0` | None |\n| ARM | `dreg` | None | `d0` | `P` |\n| ARM | `qreg` | None | `q0` | `q` |\n| ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` |\n| MIPS | `reg` | None | `$2` | None |\n| MIPS | `freg` | None | `$f0` | None |\n| NVPTX | `reg16` | None | `rs0` | None |\n| NVPTX | `reg32` | None | `r0` | None |\n| NVPTX | `reg64` | None | `rd0` | None |\n| RISC-V | `reg` | None | `x1` | None |\n| RISC-V | `freg` | None | `f0` | None |\n| Hexagon | `reg` | None | `r0` | None |\n\n> Notes:\n> - on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.\n> - on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size.\n> - on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change.\n\nAs stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the asm code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand.\n\n[llvm-argmod]: http://llvm.org/docs/LangRef.html#asm-template-argument-modifiers\n\n## Options\n\nFlags are used to further influence the behavior of the inline assembly block.\nCurrently the following options are defined:\n- `pure`: The `asm` block has no side effects, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the `asm` block fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used.\n- `nomem`: The `asm` blocks does not read or write to any memory. This allows the compiler to cache the values of modified global variables in registers across the `asm` block since it knows that they are not read or written to by the `asm`.\n- `readonly`: The `asm` block does not write to any memory. This allows the compiler to cache the values of unmodified global variables in registers across the `asm` block since it knows that they are not written to by the `asm`.\n- `preserves_flags`: The `asm` block does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after the `asm` block.\n- `noreturn`: The `asm` block never returns, and its return type is defined as `!` (never). Behavior is undefined if execution falls through past the end of the asm code. A `noreturn` asm block behaves just like a function which doesn't return; notably, local variables in scope are not dropped before it is invoked.\n- `nostack`: The `asm` block does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is *not* used then the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n- `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`.\n\nThe compiler performs some additional checks on options:\n- The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.\n- The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.\n- It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).\n- It is a compile-time error to specify `noreturn` on an asm block with outputs.\n\n## Rules for inline assembly\n\n- Any registers not specified as inputs will contain an undefined value on entry to the asm block.\n - An \"undefined value\" in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).\n- Any registers not specified as outputs must have the same value upon exiting the asm block as they had on entry, otherwise behavior is undefined.\n - This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.\n - Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation.\n- Behavior is undefined if execution unwinds out of an asm block.\n - This also applies if the assembly code calls a function which then unwinds.\n- The set of memory locations that assembly code is allowed the read and write are the same as those allowed for an FFI function.\n - Refer to the unsafe code guidelines for the exact rules.\n - If the `readonly` option is set, then only memory reads are allowed.\n - If the `nomem` option is set then no reads or writes to memory are allowed.\n - These rules do not apply to memory which is private to the asm code, such as stack space allocated within the asm block.\n- The compiler cannot assume that the instructions in the asm are the ones that will actually end up executed.\n - This effectively means that the compiler must treat the `asm!` as a black box and only take the interface specification into account, not the instructions themselves.\n - Runtime code patching is allowed, via target-specific mechanisms (outside the scope of this RFC).\n- Unless the `nostack` option is set, asm code is allowed to use stack space below the stack pointer.\n - On entry to the asm block the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n - You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page).\n - You should adjust the stack pointer when allocating stack memory as required by the target ABI.\n - The stack pointer must be restored to its original value before leaving the asm block.\n- If the `noreturn` option is set then behavior is undefined if execution falls through to the end of the asm block.\n- If the `pure` option is set then behavior is undefined if the `asm` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm` code with the same inputs result in different outputs.\n - When used with the `nomem` option, \"inputs\" are just the direct inputs of the `asm!`.\n - When used with the `readonly` option, \"inputs\" comprise the direct inputs of the `asm!` and any memory that the `asm!` block is allowed to read.\n- These flags registers must be restored upon exiting the asm block if the `preserves_flags` option is set:\n - x86\n - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).\n - Floating-point status word (all).\n - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).\n - ARM\n - Condition flags in `CPSR` (N, Z, C, V)\n - Saturation flag in `CPSR` (Q)\n - Greater than or equal flags in `CPSR` (GE).\n - Condition flags in `FPSCR` (N, Z, C, V)\n - Saturation flag in `FPSCR` (QC)\n - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).\n - AArch64\n - Condition flags (`NZCV` register).\n - Floating-point status (`FPSR` register).\n - RISC-V\n - Floating-point exception flags in `fcsr` (`fflags`).\n- On x86, the direction flag (DF in `EFLAGS`) is clear on entry to an asm block and must be clear on exit.\n - Behavior is undefined if the direction flag is set on exiting an asm block.\n- The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting an `asm!` block.\n - This means that `asm!` blocks that never return (even if not marked `noreturn`) don't need to preserve these registers.\n - When returning to a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are *exiting*.\n - You cannot exit an `asm!` block that has not been entered. Neither can you exit an `asm!` block that has already been exited.\n - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).\n - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.\n- You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places.\n - As a consequence, you should only use [local labels] inside inline assembly code. Defining symbols in assembly code may lead to assembler and/or linker errors due to duplicate symbol definitions.\n\n> **Note**: As a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call.\n\n[local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels\n" } , LintCompletion { label : "allocator_api" , description : "# `allocator_api`\n\nThe tracking issue for this feature is [#32838]\n\n[#32838]: https://github.com/rust-lang/rust/issues/32838\n\n------------------------\n\nSometimes you want the memory for one collection to use a different\nallocator than the memory for another collection. In this case,\nreplacing the global allocator is not a workable option. Instead,\nyou need to pass in an instance of an `AllocRef` to each collection\nfor which you want a custom allocator.\n\nTBD\n" } , LintCompletion { label : "set_stdio" , description : "# `set_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_sys_internals" , description : "# `libstd_sys_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "concat_idents" , description : "# `concat_idents`\n\nThe tracking issue for this feature is: [#29599]\n\n[#29599]: https://github.com/rust-lang/rust/issues/29599\n\n------------------------\n\nThe `concat_idents` feature adds a macro for concatenating multiple identifiers\ninto one identifier.\n\n## Examples\n\n```rust\n#![feature(concat_idents)]\n\nfn main() {\n fn foobar() -> u32 { 23 }\n let f = concat_idents!(foo, bar);\n assert_eq!(f(), 23);\n}\n```" } , LintCompletion { label : "format_args_capture" , description : "# `format_args_capture`\n\nThe tracking issue for this feature is: [#67984]\n\n[#67984]: https://github.com/rust-lang/rust/issues/67984\n\n------------------------\n\nEnables `format_args!` (and macros which use `format_args!` in their implementation, such\nas `format!`, `print!` and `panic!`) to capture variables from the surrounding scope.\nThis avoids the need to pass named parameters when the binding in question\nalready exists in scope.\n\n```rust\n#![feature(format_args_capture)]\n\nlet (person, species, name) = (\"Charlie Brown\", \"dog\", \"Snoopy\");\n\n// captures named argument `person`\nprint!(\"Hello {person}\");\n\n// captures named arguments `species` and `name`\nformat!(\"The {species}'s name is {name}.\");\n```\n\nThis also works for formatting parameters such as width and precision:\n\n```rust\n#![feature(format_args_capture)]\n\nlet precision = 2;\nlet s = format!(\"{:.precision$}\", 1.324223);\n\nassert_eq!(&s, \"1.32\");\n```\n\nA non-exhaustive list of macros which benefit from this functionality include:\n- `format!`\n- `print!` and `println!`\n- `eprint!` and `eprintln!`\n- `write!` and `writeln!`\n- `panic!`\n- `unreachable!`\n- `unimplemented!`\n- `todo!`\n- `assert!` and similar\n- macros in many thirdparty crates, such as `log`\n" } , LintCompletion { label : "is_sorted" , description : "# `is_sorted`\n\nThe tracking issue for this feature is: [#53485]\n\n[#53485]: https://github.com/rust-lang/rust/issues/53485\n\n------------------------\n\nAdd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to `[T]`;\nadd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to\n`Iterator`.\n" } , LintCompletion { label : "sort_internals" , description : "# `sort_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` library feature exposes the `VaList` structure,\nRust's analogue of C's `va_list` type.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\nuse std::ffi::VaList;\n\npub unsafe extern \"C\" fn vadd(n: usize, mut args: VaList) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "trace_macros" , description : "# `trace_macros`\n\nThe tracking issue for this feature is [#29598].\n\n[#29598]: https://github.com/rust-lang/rust/issues/29598\n\n------------------------\n\nWith `trace_macros` you can trace the expansion of macros in your code.\n\n## Examples\n\n```rust\n#![feature(trace_macros)]\n\nfn main() {\n trace_macros!(true);\n println!(\"Hello, Rust!\");\n trace_macros!(false);\n}\n```\n\nThe `cargo build` output:\n\n```txt\nnote: trace_macro\n --> src/main.rs:5:5\n |\n5 | println!(\"Hello, Rust!\");\n | ^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: expanding `println! { \"Hello, Rust!\" }`\n = note: to `print ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )`\n = note: expanding `print! { concat ! ( \"Hello, Rust!\" , \"\\n\" ) }`\n = note: to `$crate :: io :: _print ( format_args ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )\n )`\n\n Finished dev [unoptimized + debuginfo] target(s) in 0.60 secs\n```\n" } , LintCompletion { label : "c_void_variant" , description : "# `c_void_variant`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_panic" , description : "# `core_panic`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fmt_internals" , description : "# `fmt_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "rt" , description : "# `rt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "thread_local_internals" , description : "# `thread_local_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_intrinsics" , description : "# `core_intrinsics`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "update_panic_count" , description : "# `update_panic_count`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "profiler_runtime_lib" , description : "# `profiler_runtime_lib`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_bignum" , description : "# `core_private_bignum`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_diy_float" , description : "# `core_private_diy_float`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "str_internals" , description : "# `str_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "derive_clone_copy" , description : "# `derive_clone_copy`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fn_traits" , description : "# `fn_traits`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`unboxed_closures`](../language-features/unboxed-closures.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `fn_traits` feature allows for implementation of the [`Fn*`] traits\nfor creating custom closure-like types.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n#![feature(fn_traits)]\n\nstruct Adder {\n a: u32\n}\n\nimpl FnOnce<(u32, )> for Adder {\n type Output = u32;\n extern \"rust-call\" fn call_once(self, b: (u32, )) -> Self::Output {\n self.a + b.0\n }\n}\n\nfn main() {\n let adder = Adder { a: 3 };\n assert_eq!(adder(2), 5);\n}\n```\n" } , LintCompletion { label : "fd_read" , description : "# `fd_read`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_net" , description : "# `windows_net`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "derive_eq" , description : "# `derive_eq`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_stdio" , description : "# `windows_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "test" , description : "# `test`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe internals of the `test` crate are unstable, behind the `test` flag. The\nmost widely used part of the `test` crate are benchmark tests, which can test\nthe performance of your code. Let's make our `src/lib.rs` look like this\n(comments elided):\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\n\npub fn add_two(a: i32) -> i32 {\n a + 2\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn it_works() {\n assert_eq!(4, add_two(2));\n }\n\n #[bench]\n fn bench_add_two(b: &mut Bencher) {\n b.iter(|| add_two(2));\n }\n}\n```\n\nNote the `test` feature gate, which enables this unstable feature.\n\nWe've imported the `test` crate, which contains our benchmarking support.\nWe have a new function as well, with the `bench` attribute. Unlike regular\ntests, which take no arguments, benchmark tests take a `&mut Bencher`. This\n`Bencher` provides an `iter` method, which takes a closure. This closure\ncontains the code we'd like to benchmark.\n\nWe can run benchmark tests with `cargo bench`:\n\n```bash\n$ cargo bench\n Compiling adder v0.0.1 (file:///home/steve/tmp/adder)\n Running target/release/adder-91b3e234d4ed382a\n\nrunning 2 tests\ntest tests::it_works ... ignored\ntest tests::bench_add_two ... bench: 1 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 1 ignored; 1 measured\n```\n\nOur non-benchmark test was ignored. You may have noticed that `cargo bench`\ntakes a bit longer than `cargo test`. This is because Rust runs our benchmark\na number of times, and then takes the average. Because we're doing so little\nwork in this example, we have a `1 ns/iter (+/- 0)`, but this would show\nthe variance if there was one.\n\nAdvice on writing benchmarks:\n\n\n* Move setup code outside the `iter` loop; only put the part you want to measure inside\n* Make the code do \"the same thing\" on each iteration; do not accumulate or change state\n* Make the outer function idempotent too; the benchmark runner is likely to run\n it many times\n* Make the inner `iter` loop short and fast so benchmark runs are fast and the\n calibrator can adjust the run-length at fine resolution\n* Make the code in the `iter` loop do something simple, to assist in pinpointing\n performance improvements (or regressions)\n\n## Gotcha: optimizations\n\nThere's another tricky part to writing benchmarks: benchmarks compiled with\noptimizations activated can be dramatically changed by the optimizer so that\nthe benchmark is no longer benchmarking what one expects. For example, the\ncompiler might recognize that some calculation has no external effects and\nremove it entirely.\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\nuse test::Bencher;\n\n#[bench]\nfn bench_xor_1000_ints(b: &mut Bencher) {\n b.iter(|| {\n (0..1000).fold(0, |old, new| old ^ new);\n });\n}\n```\n\ngives the following results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 0 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nThe benchmarking runner offers two ways to avoid this. Either, the closure that\nthe `iter` method receives can return an arbitrary value which forces the\noptimizer to consider the result used and ensures it cannot remove the\ncomputation entirely. This could be done for the example above by adjusting the\n`b.iter` call to\n\n```rust\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n // Note lack of `;` (could also use an explicit `return`).\n (0..1000).fold(0, |old, new| old ^ new)\n});\n```\n\nOr, the other option is to call the generic `test::black_box` function, which\nis an opaque \"black box\" to the optimizer and so forces it to consider any\nargument as used.\n\n```rust\n#![feature(test)]\n\nextern crate test;\n\n# fn main() {\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n let n = test::black_box(1000);\n\n (0..n).fold(0, |a, b| a ^ b)\n})\n# }\n```\n\nNeither of these read or modify the value, and are very cheap for small values.\nLarger values can be passed indirectly to reduce overhead (e.g.\n`black_box(&huge_struct)`).\n\nPerforming either of the above changes gives the following benchmarking results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nHowever, the optimizer can still modify a testcase in an undesirable manner\neven when using either of the above.\n" } , LintCompletion { label : "flt2dec" , description : "# `flt2dec`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_io_internals" , description : "# `libstd_io_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fd" , description : "# `fd`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "print_internals" , description : "# `print_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "range_bounds_assert_len" , description : "# `range_bounds_assert_len`\n\nThe tracking issue for this feature is: [#76393]\n\n------------------------\n\nThis adds [`RangeBounds::assert_len`].\n\n[#76393]: https://github.com/rust-lang/rust/issues/76393\n[`RangeBounds::assert_len`]: https://doc.rust-lang.org/nightly/std/ops/trait.RangeBounds.html#method.assert_len\n" } , LintCompletion { label : "try_trait" , description : "# `try_trait`\n\nThe tracking issue for this feature is: [#42327]\n\n[#42327]: https://github.com/rust-lang/rust/issues/42327\n\n------------------------\n\nThis introduces a new trait `Try` for extending the `?` operator to types\nother than `Result` (a part of [RFC 1859]). The trait provides the canonical\nway to _view_ a type in terms of a success/failure dichotomy. This will\nallow `?` to supplant the `try_opt!` macro on `Option` and the `try_ready!`\nmacro on `Poll`, among other things.\n\n[RFC 1859]: https://github.com/rust-lang/rfcs/pull/1859\n\nHere's an example implementation of the trait:\n\n```rust,ignore\n/// A distinct type to represent the `None` value of an `Option`.\n///\n/// This enables using the `?` operator on `Option`; it's rarely useful alone.\n#[derive(Debug)]\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\npub struct None { _priv: () }\n\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\nimpl<T> ops::Try for Option<T> {\n type Ok = T;\n type Error = None;\n\n fn into_result(self) -> Result<T, None> {\n self.ok_or(None { _priv: () })\n }\n\n fn from_ok(v: T) -> Self {\n Some(v)\n }\n\n fn from_error(_: None) -> Self {\n None\n }\n}\n```\n\nNote the `Error` associated type here is a new marker. The `?` operator\nallows interconversion between different `Try` implementers only when\nthe error type can be converted `Into` the error type of the enclosing\nfunction (or catch block). Having a distinct error type (as opposed to\njust `()`, or similar) restricts this to where it's semantically meaningful.\n" }] ; | ||
5 | pub (super) const CLIPPY_LINTS : & [LintCompletion] = & [LintCompletion { label : "clippy::absurd_extreme_comparisons" , description : "Checks for comparisons where one side of the relation is\\neither the minimum or maximum value for its type and warns if it involves a\\ncase that is always true or always false. Only integer and boolean types are\\nchecked." } , LintCompletion { label : "clippy::almost_swapped" , description : "Checks for `foo = bar; bar = foo` sequences." } , LintCompletion { label : "clippy::approx_constant" , description : "Checks for floating point literals that approximate\\nconstants which are defined in\\n[`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)\\nor\\n[`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),\\nrespectively, suggesting to use the predefined constant." } , LintCompletion { label : "clippy::as_conversions" , description : "Checks for usage of `as` conversions." } , LintCompletion { label : "clippy::assertions_on_constants" , description : "Checks for `assert!(true)` and `assert!(false)` calls." } , LintCompletion { label : "clippy::assign_op_pattern" , description : "Checks for `a = a op b` or `a = b commutative_op a`\\npatterns." } , LintCompletion { label : "clippy::assign_ops" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::async_yields_async" , description : "Checks for async blocks that yield values of types\\nthat can themselves be awaited." } , LintCompletion { label : "clippy::await_holding_lock" , description : "Checks for calls to await while holding a\\nnon-async-aware MutexGuard." } , LintCompletion { label : "clippy::bad_bit_mask" , description : "Checks for incompatible bit masks in comparisons.\\n\\nThe formula for detecting if an expression of the type `_ <bit_op> m\\n<cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of\\n{`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following\\ntable:\\n\\n|Comparison |Bit Op|Example |is always|Formula |\\n|------------|------|------------|---------|----------------------|\\n|`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |\\n|`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |\\n|`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |\\n|`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |\\n|`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |\\n|`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |" } , LintCompletion { label : "clippy::bind_instead_of_map" , description : "Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or\\n`_.or_else(|x| Err(y))`." } , LintCompletion { label : "clippy::blacklisted_name" , description : "Checks for usage of blacklisted names for variables, such\\nas `foo`." } , LintCompletion { label : "clippy::blanket_clippy_restriction_lints" , description : "Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category." } , LintCompletion { label : "clippy::blocks_in_if_conditions" , description : "Checks for `if` conditions that use blocks containing an\\nexpression, statements or conditions that use closures with blocks." } , LintCompletion { label : "clippy::bool_comparison" , description : "Checks for expressions of the form `x == true`,\\n`x != true` and order comparisons such as `x < true` (or vice versa) and\\nsuggest using the variable directly." } , LintCompletion { label : "clippy::borrow_interior_mutable_const" , description : "Checks if `const` items which is interior mutable (e.g.,\\ncontains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly." } , LintCompletion { label : "clippy::borrowed_box" , description : "Checks for use of `&Box<T>` anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::box_vec" , description : "Checks for use of `Box<Vec<_>>` anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::boxed_local" , description : "Checks for usage of `Box<T>` where an unboxed `T` would\\nwork fine." } , LintCompletion { label : "clippy::builtin_type_shadow" , description : "Warns if a generic shadows a built-in type." } , LintCompletion { label : "clippy::cargo_common_metadata" , description : "Checks to see if all common metadata is defined in\\n`Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata" } , LintCompletion { label : "clippy::cast_lossless" , description : "Checks for casts between numerical types that may\\nbe replaced by safe conversion functions." } , LintCompletion { label : "clippy::cast_possible_truncation" , description : "Checks for casts between numerical types that may\\ntruncate large values. This is expected behavior, so the cast is `Allow` by\\ndefault." } , LintCompletion { label : "clippy::cast_possible_wrap" , description : "Checks for casts from an unsigned type to a signed type of\\nthe same size. Performing such a cast is a 'no-op' for the compiler,\\ni.e., nothing is changed at the bit level, and the binary representation of\\nthe value is reinterpreted. This can cause wrapping if the value is too big\\nfor the target signed type. However, the cast works as defined, so this lint\\nis `Allow` by default." } , LintCompletion { label : "clippy::cast_precision_loss" , description : "Checks for casts from any numerical to a float type where\\nthe receiving type cannot store all values from the original type without\\nrounding errors. This possible rounding is to be expected, so this lint is\\n`Allow` by default.\\n\\nBasically, this warns on casting any integer with 32 or more bits to `f32`\\nor any 64-bit integer to `f64`." } , LintCompletion { label : "clippy::cast_ptr_alignment" , description : "Checks for casts from a less-strictly-aligned pointer to a\\nmore-strictly-aligned pointer" } , LintCompletion { label : "clippy::cast_ref_to_mut" , description : "Checks for casts of `&T` to `&mut T` anywhere in the code." } , LintCompletion { label : "clippy::cast_sign_loss" , description : "Checks for casts from a signed to an unsigned numerical\\ntype. In this case, negative values wrap around to large positive values,\\nwhich can be quite surprising in practice. However, as the cast works as\\ndefined, this lint is `Allow` by default." } , LintCompletion { label : "clippy::char_lit_as_u8" , description : "Checks for expressions where a character literal is cast\\nto `u8` and suggests using a byte literal instead." } , LintCompletion { label : "clippy::chars_last_cmp" , description : "Checks for usage of `_.chars().last()` or\\n`_.chars().next_back()` on a `str` to check if it ends with a given char." } , LintCompletion { label : "clippy::chars_next_cmp" , description : "Checks for usage of `.chars().next()` on a `str` to check\\nif it starts with a given char." } , LintCompletion { label : "clippy::checked_conversions" , description : "Checks for explicit bounds checking when casting." } , LintCompletion { label : "clippy::clone_double_ref" , description : "Checks for usage of `.clone()` on an `&&T`." } , LintCompletion { label : "clippy::clone_on_copy" , description : "Checks for usage of `.clone()` on a `Copy` type." } , LintCompletion { label : "clippy::clone_on_ref_ptr" , description : "Checks for usage of `.clone()` on a ref-counted pointer,\\n(`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified\\nfunction syntax instead (e.g., `Rc::clone(foo)`)." } , LintCompletion { label : "clippy::cmp_nan" , description : "Checks for comparisons to NaN." } , LintCompletion { label : "clippy::cmp_null" , description : "This lint checks for equality comparisons with `ptr::null`" } , LintCompletion { label : "clippy::cmp_owned" , description : "Checks for conversions to owned values just for the sake\\nof a comparison." } , LintCompletion { label : "clippy::cognitive_complexity" , description : "Checks for methods with high cognitive complexity." } , LintCompletion { label : "clippy::collapsible_if" , description : "Checks for nested `if` statements which can be collapsed\\nby `&&`-combining their conditions and for `else { if ... }` expressions\\nthat\\ncan be collapsed to `else if ...`." } , LintCompletion { label : "clippy::comparison_chain" , description : "Checks comparison chains written with `if` that can be\\nrewritten with `match` and `cmp`." } , LintCompletion { label : "clippy::copy_iterator" , description : "Checks for types that implement `Copy` as well as\\n`Iterator`." } , LintCompletion { label : "clippy::create_dir" , description : "Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead." } , LintCompletion { label : "clippy::crosspointer_transmute" , description : "Checks for transmutes between a type `T` and `*T`." } , LintCompletion { label : "clippy::dbg_macro" , description : "Checks for usage of dbg!() macro." } , LintCompletion { label : "clippy::debug_assert_with_mut_call" , description : "Checks for function/method calls with a mutable\\nparameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros." } , LintCompletion { label : "clippy::decimal_literal_representation" , description : "Warns if there is a better representation for a numeric literal." } , LintCompletion { label : "clippy::declare_interior_mutable_const" , description : "Checks for declaration of `const` items which is interior\\nmutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.)." } , LintCompletion { label : "clippy::default_trait_access" , description : "Checks for literal calls to `Default::default()`." } , LintCompletion { label : "clippy::deprecated_cfg_attr" , description : "Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it\\nwith `#[rustfmt::skip]`." } , LintCompletion { label : "clippy::deprecated_semver" , description : "Checks for `#[deprecated]` annotations with a `since`\\nfield that is not a valid semantic version." } , LintCompletion { label : "clippy::deref_addrof" , description : "Checks for usage of `*&` and `*&mut` in expressions." } , LintCompletion { label : "clippy::derive_hash_xor_eq" , description : "Checks for deriving `Hash` but implementing `PartialEq`\\nexplicitly or vice versa." } , LintCompletion { label : "clippy::derive_ord_xor_partial_ord" , description : "Checks for deriving `Ord` but implementing `PartialOrd`\\nexplicitly or vice versa." } , LintCompletion { label : "clippy::disallowed_method" , description : "Lints for specific trait methods defined in clippy.toml" } , LintCompletion { label : "clippy::diverging_sub_expression" , description : "Checks for diverging calls that are not match arms or\\nstatements." } , LintCompletion { label : "clippy::doc_markdown" , description : "Checks for the presence of `_`, `::` or camel-case words\\noutside ticks in documentation." } , LintCompletion { label : "clippy::double_comparisons" , description : "Checks for double comparisons that could be simplified to a single expression." } , LintCompletion { label : "clippy::double_must_use" , description : "Checks for a [`#[must_use]`] attribute without\\nfurther information on functions and methods that return a type already\\nmarked as `#[must_use]`.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::double_neg" , description : "Detects expressions of the form `--x`." } , LintCompletion { label : "clippy::double_parens" , description : "Checks for unnecessary double parentheses." } , LintCompletion { label : "clippy::drop_bounds" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::drop_copy" , description : "Checks for calls to `std::mem::drop` with a value\\nthat derives the Copy trait" } , LintCompletion { label : "clippy::drop_ref" , description : "Checks for calls to `std::mem::drop` with a reference\\ninstead of an owned value." } , LintCompletion { label : "clippy::duplicate_underscore_argument" , description : "Checks for function arguments having the similar names\\ndiffering by an underscore." } , LintCompletion { label : "clippy::duration_subsec" , description : "Checks for calculation of subsecond microseconds or milliseconds\\nfrom other `Duration` methods." } , LintCompletion { label : "clippy::else_if_without_else" , description : "Checks for usage of if expressions with an `else if` branch,\\nbut without a final `else` branch." } , LintCompletion { label : "clippy::empty_enum" , description : "Checks for `enum`s with no variants." } , LintCompletion { label : "clippy::empty_line_after_outer_attr" , description : "Checks for empty lines after outer attributes" } , LintCompletion { label : "clippy::empty_loop" , description : "Checks for empty `loop` expressions." } , LintCompletion { label : "clippy::enum_clike_unportable_variant" , description : "Checks for C-like enumerations that are\\n`repr(isize/usize)` and have values that don't fit into an `i32`." } , LintCompletion { label : "clippy::enum_glob_use" , description : "Checks for `use Enum::*`." } , LintCompletion { label : "clippy::enum_variant_names" , description : "Detects enumeration variants that are prefixed or suffixed\\nby the same characters." } , LintCompletion { label : "clippy::eq_op" , description : "Checks for equal operands to comparison, logical and\\nbitwise, difference and division binary operators (`==`, `>`, etc., `&&`,\\n`||`, `&`, `|`, `^`, `-` and `/`)." } , LintCompletion { label : "clippy::erasing_op" , description : "Checks for erasing operations, e.g., `x * 0`." } , LintCompletion { label : "clippy::eval_order_dependence" , description : "Checks for a read and a write to the same variable where\\nwhether the read occurs before or after the write depends on the evaluation\\norder of sub-expressions." } , LintCompletion { label : "clippy::excessive_precision" , description : "Checks for float literals with a precision greater\\nthan that supported by the underlying type." } , LintCompletion { label : "clippy::exit" , description : "`exit()` terminates the program and doesn't provide a\\nstack trace." } , LintCompletion { label : "clippy::expect_fun_call" , description : "Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,\\netc., and suggests to use `unwrap_or_else` instead" } , LintCompletion { label : "clippy::expect_used" , description : "Checks for `.expect()` calls on `Option`s and `Result`s." } , LintCompletion { label : "clippy::expl_impl_clone_on_copy" , description : "Checks for explicit `Clone` implementations for `Copy`\\ntypes." } , LintCompletion { label : "clippy::explicit_counter_loop" , description : "Checks `for` loops over slices with an explicit counter\\nand suggests the use of `.enumerate()`." } , LintCompletion { label : "clippy::explicit_deref_methods" , description : "Checks for explicit `deref()` or `deref_mut()` method calls." } , LintCompletion { label : "clippy::explicit_into_iter_loop" , description : "Checks for loops on `y.into_iter()` where `y` will do, and\\nsuggests the latter." } , LintCompletion { label : "clippy::explicit_iter_loop" , description : "Checks for loops on `x.iter()` where `&x` will do, and\\nsuggests the latter." } , LintCompletion { label : "clippy::explicit_write" , description : "Checks for usage of `write!()` / `writeln()!` which can be\\nreplaced with `(e)print!()` / `(e)println!()`" } , LintCompletion { label : "clippy::extend_from_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::extra_unused_lifetimes" , description : "Checks for lifetimes in generics that are never used\\nanywhere else." } , LintCompletion { label : "clippy::fallible_impl_from" , description : "Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`" } , LintCompletion { label : "clippy::filetype_is_file" , description : "Checks for `FileType::is_file()`." } , LintCompletion { label : "clippy::filter_map" , description : "Checks for usage of `_.filter(_).map(_)`,\\n`_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar." } , LintCompletion { label : "clippy::filter_map_next" , description : "Checks for usage of `_.filter_map(_).next()`." } , LintCompletion { label : "clippy::filter_next" , description : "Checks for usage of `_.filter(_).next()`." } , LintCompletion { label : "clippy::find_map" , description : "Checks for usage of `_.find(_).map(_)`." } , LintCompletion { label : "clippy::flat_map_identity" , description : "Checks for usage of `flat_map(|x| x)`." } , LintCompletion { label : "clippy::float_arithmetic" , description : "Checks for float arithmetic." } , LintCompletion { label : "clippy::float_cmp" , description : "Checks for (in-)equality comparisons on floating-point\\nvalues (apart from zero), except in functions called `*eq*` (which probably\\nimplement equality for a type involving floats)." } , LintCompletion { label : "clippy::float_cmp_const" , description : "Checks for (in-)equality comparisons on floating-point\\nvalue and constant, except in functions called `*eq*` (which probably\\nimplement equality for a type involving floats)." } , LintCompletion { label : "clippy::float_equality_without_abs" , description : "Checks for statements of the form `(a - b) < f32::EPSILON` or\\n`(a - b) < f64::EPSILON`. Notes the missing `.abs()`." } , LintCompletion { label : "clippy::fn_address_comparisons" , description : "Checks for comparisons with an address of a function item." } , LintCompletion { label : "clippy::fn_params_excessive_bools" , description : "Checks for excessive use of\\nbools in function definitions." } , LintCompletion { label : "clippy::fn_to_numeric_cast" , description : "Checks for casts of function pointers to something other than usize" } , LintCompletion { label : "clippy::fn_to_numeric_cast_with_truncation" , description : "Checks for casts of a function pointer to a numeric type not wide enough to\\nstore address." } , LintCompletion { label : "clippy::for_kv_map" , description : "Checks for iterating a map (`HashMap` or `BTreeMap`) and\\nignoring either the keys or values." } , LintCompletion { label : "clippy::for_loops_over_fallibles" , description : "Checks for `for` loops over `Option` or `Result` values." } , LintCompletion { label : "clippy::forget_copy" , description : "Checks for calls to `std::mem::forget` with a value that\\nderives the Copy trait" } , LintCompletion { label : "clippy::forget_ref" , description : "Checks for calls to `std::mem::forget` with a reference\\ninstead of an owned value." } , LintCompletion { label : "clippy::future_not_send" , description : "This lint requires Future implementations returned from\\nfunctions and methods to implement the `Send` marker trait. It is mostly\\nused by library authors (public and internal) that target an audience where\\nmultithreaded executors are likely to be used for running these Futures." } , LintCompletion { label : "clippy::get_last_with_len" , description : "Checks for using `x.get(x.len() - 1)` instead of\\n`x.last()`." } , LintCompletion { label : "clippy::get_unwrap" , description : "Checks for use of `.get().unwrap()` (or\\n`.get_mut().unwrap`) on a standard library type which implements `Index`" } , LintCompletion { label : "clippy::identity_op" , description : "Checks for identity operations, e.g., `x + 0`." } , LintCompletion { label : "clippy::if_let_mutex" , description : "Checks for `Mutex::lock` calls in `if let` expression\\nwith lock calls in any of the else blocks." } , LintCompletion { label : "clippy::if_let_redundant_pattern_matching" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::if_let_some_result" , description : "* Checks for unnecessary `ok()` in if let." } , LintCompletion { label : "clippy::if_not_else" , description : "Checks for usage of `!` or `!=` in an if condition with an\\nelse branch." } , LintCompletion { label : "clippy::if_same_then_else" , description : "Checks for `if/else` with the same body as the *then* part\\nand the *else* part." } , LintCompletion { label : "clippy::ifs_same_cond" , description : "Checks for consecutive `if`s with the same condition." } , LintCompletion { label : "clippy::implicit_hasher" , description : "Checks for public `impl` or `fn` missing generalization\\nover different hashers and implicitly defaulting to the default hashing\\nalgorithm (`SipHash`)." } , LintCompletion { label : "clippy::implicit_return" , description : "Checks for missing return statements at the end of a block." } , LintCompletion { label : "clippy::implicit_saturating_sub" , description : "Checks for implicit saturating subtraction." } , LintCompletion { label : "clippy::imprecise_flops" , description : "Looks for floating-point expressions that\\ncan be expressed using built-in methods to improve accuracy\\nat the cost of performance." } , LintCompletion { label : "clippy::inconsistent_digit_grouping" , description : "Warns if an integral or floating-point constant is\\ngrouped inconsistently with underscores." } , LintCompletion { label : "clippy::indexing_slicing" , description : "Checks for usage of indexing or slicing. Arrays are special cases, this lint\\ndoes report on arrays if we can tell that slicing operations are in bounds and does not\\nlint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint." } , LintCompletion { label : "clippy::ineffective_bit_mask" , description : "Checks for bit masks in comparisons which can be removed\\nwithout changing the outcome. The basic structure can be seen in the\\nfollowing table:\\n\\n|Comparison| Bit Op |Example |equals |\\n|----------|---------|-----------|-------|\\n|`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|\\n|`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|" } , LintCompletion { label : "clippy::inefficient_to_string" , description : "Checks for usage of `.to_string()` on an `&&T` where\\n`T` implements `ToString` directly (like `&&str` or `&&String`)." } , LintCompletion { label : "clippy::infallible_destructuring_match" , description : "Checks for matches being used to destructure a single-variant enum\\nor tuple struct where a `let` will suffice." } , LintCompletion { label : "clippy::infinite_iter" , description : "Checks for iteration that is guaranteed to be infinite." } , LintCompletion { label : "clippy::inherent_to_string" , description : "Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`." } , LintCompletion { label : "clippy::inherent_to_string_shadow_display" , description : "Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait." } , LintCompletion { label : "clippy::inline_always" , description : "Checks for items annotated with `#[inline(always)]`,\\nunless the annotated function is empty or simply panics." } , LintCompletion { label : "clippy::inline_asm_x86_att_syntax" , description : "Checks for usage of AT&T x86 assembly syntax." } , LintCompletion { label : "clippy::inline_asm_x86_intel_syntax" , description : "Checks for usage of Intel x86 assembly syntax." } , LintCompletion { label : "clippy::inline_fn_without_body" , description : "Checks for `#[inline]` on trait methods without bodies" } , LintCompletion { label : "clippy::int_plus_one" , description : "Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block" } , LintCompletion { label : "clippy::integer_arithmetic" , description : "Checks for integer arithmetic operations which could overflow or panic.\\n\\nSpecifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable\\nof overflowing according to the [Rust\\nReference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),\\nor which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is\\nattempted." } , LintCompletion { label : "clippy::integer_division" , description : "Checks for division of integers" } , LintCompletion { label : "clippy::into_iter_on_array" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::into_iter_on_ref" , description : "Checks for `into_iter` calls on references which should be replaced by `iter`\\nor `iter_mut`." } , LintCompletion { label : "clippy::invalid_atomic_ordering" , description : "Checks for usage of invalid atomic\\nordering in atomic loads/stores/exchanges/updates and\\nmemory fences." } , LintCompletion { label : "clippy::invalid_ref" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::invalid_regex" , description : "Checks [regex](https://crates.io/crates/regex) creation\\n(with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct\\nregex syntax." } , LintCompletion { label : "clippy::invalid_upcast_comparisons" , description : "Checks for comparisons where the relation is always either\\ntrue or false, but where one side has been upcast so that the comparison is\\nnecessary. Only integer types are checked." } , LintCompletion { label : "clippy::invisible_characters" , description : "Checks for invisible Unicode characters in the code." } , LintCompletion { label : "clippy::items_after_statements" , description : "Checks for items declared after some statement in a block." } , LintCompletion { label : "clippy::iter_cloned_collect" , description : "Checks for the use of `.cloned().collect()` on slice to\\ncreate a `Vec`." } , LintCompletion { label : "clippy::iter_next_loop" , description : "Checks for loops on `x.next()`." } , LintCompletion { label : "clippy::iter_next_slice" , description : "Checks for usage of `iter().next()` on a Slice or an Array" } , LintCompletion { label : "clippy::iter_nth" , description : "Checks for use of `.iter().nth()` (and the related\\n`.iter_mut().nth()`) on standard library types with O(1) element access." } , LintCompletion { label : "clippy::iter_nth_zero" , description : "Checks for the use of `iter.nth(0)`." } , LintCompletion { label : "clippy::iter_skip_next" , description : "Checks for use of `.skip(x).next()` on iterators." } , LintCompletion { label : "clippy::iterator_step_by_zero" , description : "Checks for calling `.step_by(0)` on iterators which panics." } , LintCompletion { label : "clippy::just_underscores_and_digits" , description : "Checks if you have variables whose name consists of just\\nunderscores and digits." } , LintCompletion { label : "clippy::large_const_arrays" , description : "Checks for large `const` arrays that should\\nbe defined as `static` instead." } , LintCompletion { label : "clippy::large_digit_groups" , description : "Warns if the digits of an integral or floating-point\\nconstant are grouped into groups that\\nare too large." } , LintCompletion { label : "clippy::large_enum_variant" , description : "Checks for large size differences between variants on\\n`enum`s." } , LintCompletion { label : "clippy::large_stack_arrays" , description : "Checks for local arrays that may be too large." } , LintCompletion { label : "clippy::large_types_passed_by_value" , description : "Checks for functions taking arguments by value, where\\nthe argument type is `Copy` and large enough to be worth considering\\npassing by reference. Does not trigger if the function is being exported,\\nbecause that might induce API breakage, if the parameter is declared as mutable,\\nor if the argument is a `self`." } , LintCompletion { label : "clippy::len_without_is_empty" , description : "Checks for items that implement `.len()` but not\\n`.is_empty()`." } , LintCompletion { label : "clippy::len_zero" , description : "Checks for getting the length of something via `.len()`\\njust to compare to zero, and suggests using `.is_empty()` where applicable." } , LintCompletion { label : "clippy::let_and_return" , description : "Checks for `let`-bindings, which are subsequently\\nreturned." } , LintCompletion { label : "clippy::let_underscore_lock" , description : "Checks for `let _ = sync_lock`" } , LintCompletion { label : "clippy::let_underscore_must_use" , description : "Checks for `let _ = <expr>`\\nwhere expr is #[must_use]" } , LintCompletion { label : "clippy::let_unit_value" , description : "Checks for binding a unit value." } , LintCompletion { label : "clippy::linkedlist" , description : "Checks for usage of any `LinkedList`, suggesting to use a\\n`Vec` or a `VecDeque` (formerly called `RingBuf`)." } , LintCompletion { label : "clippy::logic_bug" , description : "Checks for boolean expressions that contain terminals that\\ncan be eliminated." } , LintCompletion { label : "clippy::lossy_float_literal" , description : "Checks for whole number float literals that\\ncannot be represented as the underlying type without loss." } , LintCompletion { label : "clippy::macro_use_imports" , description : "Checks for `#[macro_use] use...`." } , LintCompletion { label : "clippy::main_recursion" , description : "Checks for recursion using the entrypoint." } , LintCompletion { label : "clippy::manual_async_fn" , description : "It checks for manual implementations of `async` functions." } , LintCompletion { label : "clippy::manual_memcpy" , description : "Checks for for-loops that manually copy items between\\nslices that could be optimized by having a memcpy." } , LintCompletion { label : "clippy::manual_non_exhaustive" , description : "Checks for manual implementations of the non-exhaustive pattern." } , LintCompletion { label : "clippy::manual_saturating_arithmetic" , description : "Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`." } , LintCompletion { label : "clippy::manual_strip" , description : "Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using\\nthe pattern's length." } , LintCompletion { label : "clippy::manual_swap" , description : "Checks for manual swapping." } , LintCompletion { label : "clippy::manual_unwrap_or" , description : "Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`." } , LintCompletion { label : "clippy::many_single_char_names" , description : "Checks for too many variables whose name consists of a\\nsingle character." } , LintCompletion { label : "clippy::map_clone" , description : "Checks for usage of `iterator.map(|x| x.clone())` and suggests\\n`iterator.cloned()` instead" } , LintCompletion { label : "clippy::map_entry" , description : "Checks for uses of `contains_key` + `insert` on `HashMap`\\nor `BTreeMap`." } , LintCompletion { label : "clippy::map_err_ignore" , description : "Checks for instances of `map_err(|_| Some::Enum)`" } , LintCompletion { label : "clippy::map_flatten" , description : "Checks for usage of `_.map(_).flatten(_)`," } , LintCompletion { label : "clippy::map_identity" , description : "Checks for instances of `map(f)` where `f` is the identity function." } , LintCompletion { label : "clippy::map_unwrap_or" , description : "Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or\\n`result.map(_).unwrap_or_else(_)`." } , LintCompletion { label : "clippy::match_as_ref" , description : "Checks for match which is used to add a reference to an\\n`Option` value." } , LintCompletion { label : "clippy::match_bool" , description : "Checks for matches where match expression is a `bool`. It\\nsuggests to replace the expression with an `if...else` block." } , LintCompletion { label : "clippy::match_like_matches_macro" , description : "Checks for `match` or `if let` expressions producing a\\n`bool` that could be written using `matches!`" } , LintCompletion { label : "clippy::match_on_vec_items" , description : "Checks for `match vec[idx]` or `match vec[n..m]`." } , LintCompletion { label : "clippy::match_overlapping_arm" , description : "Checks for overlapping match arms." } , LintCompletion { label : "clippy::match_ref_pats" , description : "Checks for matches where all arms match a reference,\\nsuggesting to remove the reference and deref the matched expression\\ninstead. It also checks for `if let &foo = bar` blocks." } , LintCompletion { label : "clippy::match_same_arms" , description : "Checks for `match` with identical arm bodies." } , LintCompletion { label : "clippy::match_single_binding" , description : "Checks for useless match that binds to only one value." } , LintCompletion { label : "clippy::match_wild_err_arm" , description : "Checks for arm which matches all errors with `Err(_)`\\nand take drastic actions like `panic!`." } , LintCompletion { label : "clippy::match_wildcard_for_single_variants" , description : "Checks for wildcard enum matches for a single variant." } , LintCompletion { label : "clippy::maybe_infinite_iter" , description : "Checks for iteration that may be infinite." } , LintCompletion { label : "clippy::mem_discriminant_non_enum" , description : "Checks for calls of `mem::discriminant()` on a non-enum type." } , LintCompletion { label : "clippy::mem_forget" , description : "Checks for usage of `std::mem::forget(t)` where `t` is\\n`Drop`." } , LintCompletion { label : "clippy::mem_replace_option_with_none" , description : "Checks for `mem::replace()` on an `Option` with\\n`None`." } , LintCompletion { label : "clippy::mem_replace_with_default" , description : "Checks for `std::mem::replace` on a value of type\\n`T` with `T::default()`." } , LintCompletion { label : "clippy::mem_replace_with_uninit" , description : "Checks for `mem::replace(&mut _, mem::uninitialized())`\\nand `mem::replace(&mut _, mem::zeroed())`." } , LintCompletion { label : "clippy::min_max" , description : "Checks for expressions where `std::cmp::min` and `max` are\\nused to clamp values, but switched so that the result is constant." } , LintCompletion { label : "clippy::misaligned_transmute" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::mismatched_target_os" , description : "Checks for cfg attributes having operating systems used in target family position." } , LintCompletion { label : "clippy::misrefactored_assign_op" , description : "Checks for `a op= a op b` or `a op= b op a` patterns." } , LintCompletion { label : "clippy::missing_const_for_fn" , description : "Suggests the use of `const` in functions and methods where possible." } , LintCompletion { label : "clippy::missing_docs_in_private_items" , description : "Warns if there is missing doc for any documentable item\\n(public or private)." } , LintCompletion { label : "clippy::missing_errors_doc" , description : "Checks the doc comments of publicly visible functions that\\nreturn a `Result` type and warns if there is no `# Errors` section." } , LintCompletion { label : "clippy::missing_inline_in_public_items" , description : "it lints if an exported function, method, trait method with default impl,\\nor trait method impl is not `#[inline]`." } , LintCompletion { label : "clippy::missing_safety_doc" , description : "Checks for the doc comments of publicly visible\\nunsafe functions and warns if there is no `# Safety` section." } , LintCompletion { label : "clippy::mistyped_literal_suffixes" , description : "Warns for mistyped suffix in literals" } , LintCompletion { label : "clippy::mixed_case_hex_literals" , description : "Warns on hexadecimal literals with mixed-case letter\\ndigits." } , LintCompletion { label : "clippy::module_inception" , description : "Checks for modules that have the same name as their\\nparent module" } , LintCompletion { label : "clippy::module_name_repetitions" , description : "Detects type names that are prefixed or suffixed by the\\ncontaining module's name." } , LintCompletion { label : "clippy::modulo_arithmetic" , description : "Checks for modulo arithmetic." } , LintCompletion { label : "clippy::modulo_one" , description : "Checks for getting the remainder of a division by one." } , LintCompletion { label : "clippy::multiple_crate_versions" , description : "Checks to see if multiple versions of a crate are being\\nused." } , LintCompletion { label : "clippy::multiple_inherent_impl" , description : "Checks for multiple inherent implementations of a struct" } , LintCompletion { label : "clippy::must_use_candidate" , description : "Checks for public functions that have no\\n[`#[must_use]`] attribute, but return something not already marked\\nmust-use, have no mutable arg and mutate no statics.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::must_use_unit" , description : "Checks for a [`#[must_use]`] attribute on\\nunit-returning functions and methods.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::mut_from_ref" , description : "This lint checks for functions that take immutable\\nreferences and return mutable ones." } , LintCompletion { label : "clippy::mut_mut" , description : "Checks for instances of `mut mut` references." } , LintCompletion { label : "clippy::mut_range_bound" , description : "Checks for loops which have a range bound that is a mutable variable" } , LintCompletion { label : "clippy::mutable_key_type" , description : "Checks for sets/maps with mutable key types." } , LintCompletion { label : "clippy::mutex_atomic" , description : "Checks for usages of `Mutex<X>` where an atomic will do." } , LintCompletion { label : "clippy::mutex_integer" , description : "Checks for usages of `Mutex<X>` where `X` is an integral\\ntype." } , LintCompletion { label : "clippy::naive_bytecount" , description : "Checks for naive byte counts" } , LintCompletion { label : "clippy::needless_arbitrary_self_type" , description : "The lint checks for `self` in fn parameters that\\nspecify the `Self`-type explicitly" } , LintCompletion { label : "clippy::needless_bool" , description : "Checks for expressions of the form `if c { true } else {\\nfalse }` (or vice versa) and suggests using the condition directly." } , LintCompletion { label : "clippy::needless_borrow" , description : "Checks for address of operations (`&`) that are going to\\nbe dereferenced immediately by the compiler." } , LintCompletion { label : "clippy::needless_borrowed_reference" , description : "Checks for useless borrowed references." } , LintCompletion { label : "clippy::needless_collect" , description : "Checks for functions collecting an iterator when collect\\nis not needed." } , LintCompletion { label : "clippy::needless_continue" , description : "The lint checks for `if`-statements appearing in loops\\nthat contain a `continue` statement in either their main blocks or their\\n`else`-blocks, when omitting the `else`-block possibly with some\\nrearrangement of code can make the code easier to understand." } , LintCompletion { label : "clippy::needless_doctest_main" , description : "Checks for `fn main() { .. }` in doctests" } , LintCompletion { label : "clippy::needless_lifetimes" , description : "Checks for lifetime annotations which can be removed by\\nrelying on lifetime elision." } , LintCompletion { label : "clippy::needless_pass_by_value" , description : "Checks for functions taking arguments by value, but not\\nconsuming them in its\\nbody." } , LintCompletion { label : "clippy::needless_range_loop" , description : "Checks for looping over the range of `0..len` of some\\ncollection just to get the values by index." } , LintCompletion { label : "clippy::needless_return" , description : "Checks for return statements at the end of a block." } , LintCompletion { label : "clippy::needless_update" , description : "Checks for needlessly including a base struct on update\\nwhen all fields are changed anyway." } , LintCompletion { label : "clippy::neg_cmp_op_on_partial_ord" , description : "Checks for the usage of negated comparison operators on types which only implement\\n`PartialOrd` (e.g., `f64`)." } , LintCompletion { label : "clippy::neg_multiply" , description : "Checks for multiplication by -1 as a form of negation." } , LintCompletion { label : "clippy::never_loop" , description : "Checks for loops that will always `break`, `return` or\\n`continue` an outer loop." } , LintCompletion { label : "clippy::new_ret_no_self" , description : "Checks for `new` not returning a type that contains `Self`." } , LintCompletion { label : "clippy::new_without_default" , description : "Checks for types with a `fn new() -> Self` method and no\\nimplementation of\\n[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)." } , LintCompletion { label : "clippy::no_effect" , description : "Checks for statements which have no effect." } , LintCompletion { label : "clippy::non_ascii_literal" , description : "Checks for non-ASCII characters in string literals." } , LintCompletion { label : "clippy::nonminimal_bool" , description : "Checks for boolean expressions that can be written more\\nconcisely." } , LintCompletion { label : "clippy::nonsensical_open_options" , description : "Checks for duplicate open options as well as combinations\\nthat make no sense." } , LintCompletion { label : "clippy::not_unsafe_ptr_arg_deref" , description : "Checks for public functions that dereference raw pointer\\narguments but are not marked unsafe." } , LintCompletion { label : "clippy::ok_expect" , description : "Checks for usage of `ok().expect(..)`." } , LintCompletion { label : "clippy::op_ref" , description : "Checks for arguments to `==` which have their address\\ntaken to satisfy a bound\\nand suggests to dereference the other argument instead" } , LintCompletion { label : "clippy::option_as_ref_deref" , description : "Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str)." } , LintCompletion { label : "clippy::option_env_unwrap" , description : "Checks for usage of `option_env!(...).unwrap()` and\\nsuggests usage of the `env!` macro." } , LintCompletion { label : "clippy::option_if_let_else" , description : "Lints usage of `if let Some(v) = ... { y } else { x }` which is more\\nidiomatically done with `Option::map_or` (if the else bit is a pure\\nexpression) or `Option::map_or_else` (if the else bit is an impure\\nexpression)." } , LintCompletion { label : "clippy::option_map_or_none" , description : "Checks for usage of `_.map_or(None, _)`." } , LintCompletion { label : "clippy::option_map_unit_fn" , description : "Checks for usage of `option.map(f)` where f is a function\\nor closure that returns the unit type `()`." } , LintCompletion { label : "clippy::option_option" , description : "Checks for use of `Option<Option<_>>` in function signatures and type\\ndefinitions" } , LintCompletion { label : "clippy::or_fun_call" , description : "Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,\\netc., and suggests to use `or_else`, `unwrap_or_else`, etc., or\\n`unwrap_or_default` instead." } , LintCompletion { label : "clippy::out_of_bounds_indexing" , description : "Checks for out of bounds array indexing with a constant\\nindex." } , LintCompletion { label : "clippy::overflow_check_conditional" , description : "Detects classic underflow/overflow checks." } , LintCompletion { label : "clippy::panic" , description : "Checks for usage of `panic!`." } , LintCompletion { label : "clippy::panic_in_result_fn" , description : "Checks for usage of `panic!`, `unimplemented!`, `todo!` or `unreachable!` in a function of type result." } , LintCompletion { label : "clippy::panic_params" , description : "Checks for missing parameters in `panic!`." } , LintCompletion { label : "clippy::panicking_unwrap" , description : "Checks for calls of `unwrap[_err]()` that will always fail." } , LintCompletion { label : "clippy::partialeq_ne_impl" , description : "Checks for manual re-implementations of `PartialEq::ne`." } , LintCompletion { label : "clippy::path_buf_push_overwrite" , description : "* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)\\ncalls on `PathBuf` that can cause overwrites." } , LintCompletion { label : "clippy::pattern_type_mismatch" , description : "Checks for patterns that aren't exact representations of the types\\nthey are applied to.\\n\\nTo satisfy this lint, you will have to adjust either the expression that is matched\\nagainst or the pattern itself, as well as the bindings that are introduced by the\\nadjusted patterns. For matching you will have to either dereference the expression\\nwith the `*` operator, or amend the patterns to explicitly match against `&<pattern>`\\nor `&mut <pattern>` depending on the reference mutability. For the bindings you need\\nto use the inverse. You can leave them as plain bindings if you wish for the value\\nto be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct\\na reference into the matched structure.\\n\\nIf you are looking for a way to learn about ownership semantics in more detail, it\\nis recommended to look at IDE options available to you to highlight types, lifetimes\\nand reference semantics in your code. The available tooling would expose these things\\nin a general way even outside of the various pattern matching mechanics. Of course\\nthis lint can still be used to highlight areas of interest and ensure a good understanding\\nof ownership semantics." } , LintCompletion { label : "clippy::possible_missing_comma" , description : "Checks for possible missing comma in an array. It lints if\\nan array element is a binary operator expression and it lies on two lines." } , LintCompletion { label : "clippy::precedence" , description : "Checks for operations where precedence may be unclear\\nand suggests to add parentheses. Currently it catches the following:\\n* mixed usage of arithmetic and bit shifting/combining operators without\\nparentheses\\n* a \\\"negative\\\" numeric literal (which is really a unary `-` followed by a\\nnumeric literal)\\n followed by a method call" } , LintCompletion { label : "clippy::print_literal" , description : "This lint warns about the use of literals as `print!`/`println!` args." } , LintCompletion { label : "clippy::print_stdout" , description : "Checks for printing on *stdout*. The purpose of this lint\\nis to catch debugging remnants." } , LintCompletion { label : "clippy::print_with_newline" , description : "This lint warns when you use `print!()` with a format\\nstring that ends in a newline." } , LintCompletion { label : "clippy::println_empty_string" , description : "This lint warns when you use `println!(\\\"\\\")` to\\nprint a newline." } , LintCompletion { label : "clippy::ptr_arg" , description : "This lint checks for function arguments of type `&String`\\nor `&Vec` unless the references are mutable. It will also suggest you\\nreplace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`\\ncalls." } , LintCompletion { label : "clippy::ptr_eq" , description : "Use `std::ptr::eq` when applicable" } , LintCompletion { label : "clippy::ptr_offset_with_cast" , description : "Checks for usage of the `offset` pointer method with a `usize` casted to an\\n`isize`." } , LintCompletion { label : "clippy::pub_enum_variant_names" , description : "Detects public enumeration variants that are\\nprefixed or suffixed by the same characters." } , LintCompletion { label : "clippy::question_mark" , description : "Checks for expressions that could be replaced by the question mark operator." } , LintCompletion { label : "clippy::range_minus_one" , description : "Checks for inclusive ranges where 1 is subtracted from\\nthe upper bound, e.g., `x..=(y-1)`." } , LintCompletion { label : "clippy::range_plus_one" , description : "Checks for exclusive ranges where 1 is added to the\\nupper bound, e.g., `x..(y+1)`." } , LintCompletion { label : "clippy::range_step_by_zero" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::range_zip_with_len" , description : "Checks for zipping a collection with the range of\\n`0.._.len()`." } , LintCompletion { label : "clippy::rc_buffer" , description : "Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`." } , LintCompletion { label : "clippy::redundant_allocation" , description : "Checks for use of redundant allocations anywhere in the code." } , LintCompletion { label : "clippy::redundant_clone" , description : "Checks for a redundant `clone()` (and its relatives) which clones an owned\\nvalue that is going to be dropped without further use." } , LintCompletion { label : "clippy::redundant_closure" , description : "Checks for closures which just call another function where\\nthe function can be called directly. `unsafe` functions or calls where types\\nget adjusted are ignored." } , LintCompletion { label : "clippy::redundant_closure_call" , description : "Detects closures called in the same expression where they\\nare defined." } , LintCompletion { label : "clippy::redundant_closure_for_method_calls" , description : "Checks for closures which only invoke a method on the closure\\nargument and can be replaced by referencing the method directly." } , LintCompletion { label : "clippy::redundant_field_names" , description : "Checks for fields in struct literals where shorthands\\ncould be used." } , LintCompletion { label : "clippy::redundant_pattern" , description : "Checks for patterns in the form `name @ _`." } , LintCompletion { label : "clippy::redundant_pattern_matching" , description : "Lint for redundant pattern matching over `Result` or\\n`Option`" } , LintCompletion { label : "clippy::redundant_pub_crate" , description : "Checks for items declared `pub(crate)` that are not crate visible because they\\nare inside a private module." } , LintCompletion { label : "clippy::redundant_static_lifetimes" , description : "Checks for constants and statics with an explicit `'static` lifetime." } , LintCompletion { label : "clippy::ref_in_deref" , description : "Checks for references in expressions that use\\nauto dereference." } , LintCompletion { label : "clippy::regex_macro" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::repeat_once" , description : "Checks for usage of `.repeat(1)` and suggest the following method for each types.\\n- `.to_string()` for `str`\\n- `.clone()` for `String`\\n- `.to_vec()` for `slice`" } , LintCompletion { label : "clippy::replace_consts" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::rest_pat_in_fully_bound_structs" , description : "Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched." } , LintCompletion { label : "clippy::result_map_or_into_option" , description : "Checks for usage of `_.map_or(None, Some)`." } , LintCompletion { label : "clippy::result_map_unit_fn" , description : "Checks for usage of `result.map(f)` where f is a function\\nor closure that returns the unit type `()`." } , LintCompletion { label : "clippy::result_unit_err" , description : "Checks for public functions that return a `Result`\\nwith an `Err` type of `()`. It suggests using a custom type that\\nimplements [`std::error::Error`]." } , LintCompletion { label : "clippy::reversed_empty_ranges" , description : "Checks for range expressions `x..y` where both `x` and `y`\\nare constant and `x` is greater or equal to `y`." } , LintCompletion { label : "clippy::same_functions_in_if_condition" , description : "Checks for consecutive `if`s with the same function call." } , LintCompletion { label : "clippy::same_item_push" , description : "Checks whether a for loop is being used to push a constant\\nvalue into a Vec." } , LintCompletion { label : "clippy::search_is_some" , description : "Checks for an iterator search (such as `find()`,\\n`position()`, or `rposition()`) followed by a call to `is_some()`." } , LintCompletion { label : "clippy::self_assignment" , description : "Checks for explicit self-assignments." } , LintCompletion { label : "clippy::serde_api_misuse" , description : "Checks for mis-uses of the serde API." } , LintCompletion { label : "clippy::shadow_reuse" , description : "Checks for bindings that shadow other bindings already in\\nscope, while reusing the original value." } , LintCompletion { label : "clippy::shadow_same" , description : "Checks for bindings that shadow other bindings already in\\nscope, while just changing reference level or mutability." } , LintCompletion { label : "clippy::shadow_unrelated" , description : "Checks for bindings that shadow other bindings already in\\nscope, either without a initialization or with one that does not even use\\nthe original value." } , LintCompletion { label : "clippy::short_circuit_statement" , description : "Checks for the use of short circuit boolean conditions as\\na\\nstatement." } , LintCompletion { label : "clippy::should_assert_eq" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::should_implement_trait" , description : "Checks for methods that should live in a trait\\nimplementation of a `std` trait (see [llogiq's blog\\npost](http://llogiq.github.io/2015/07/30/traits.html) for further\\ninformation) instead of an inherent implementation." } , LintCompletion { label : "clippy::similar_names" , description : "Checks for names that are very similar and thus confusing." } , LintCompletion { label : "clippy::single_char_pattern" , description : "Checks for string methods that receive a single-character\\n`str` as an argument, e.g., `_.split(\\\"x\\\")`." } , LintCompletion { label : "clippy::single_char_push_str" , description : "Warns when using `push_str` with a single-character string literal,\\nand `push` with a `char` would work fine." } , LintCompletion { label : "clippy::single_component_path_imports" , description : "Checking for imports with single component use path." } , LintCompletion { label : "clippy::single_match" , description : "Checks for matches with a single arm where an `if let`\\nwill usually suffice." } , LintCompletion { label : "clippy::single_match_else" , description : "Checks for matches with two arms where an `if let else` will\\nusually suffice." } , LintCompletion { label : "clippy::skip_while_next" , description : "Checks for usage of `_.skip_while(condition).next()`." } , LintCompletion { label : "clippy::slow_vector_initialization" , description : "Checks slow zero-filled vector initialization" } , LintCompletion { label : "clippy::stable_sort_primitive" , description : "When sorting primitive values (integers, bools, chars, as well\\nas arrays, slices, and tuples of such items), it is better to\\nuse an unstable sort than a stable sort." } , LintCompletion { label : "clippy::str_to_string" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::string_add" , description : "Checks for all instances of `x + _` where `x` is of type\\n`String`, but only if [`string_add_assign`](#string_add_assign) does *not*\\nmatch." } , LintCompletion { label : "clippy::string_add_assign" , description : "Checks for string appends of the form `x = x + y` (without\\n`let`!)." } , LintCompletion { label : "clippy::string_extend_chars" , description : "Checks for the use of `.extend(s.chars())` where s is a\\n`&str` or `String`." } , LintCompletion { label : "clippy::string_lit_as_bytes" , description : "Checks for the `as_bytes` method called on string literals\\nthat contain only ASCII characters." } , LintCompletion { label : "clippy::string_to_string" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::struct_excessive_bools" , description : "Checks for excessive\\nuse of bools in structs." } , LintCompletion { label : "clippy::suboptimal_flops" , description : "Looks for floating-point expressions that\\ncan be expressed using built-in methods to improve both\\naccuracy and performance." } , LintCompletion { label : "clippy::suspicious_arithmetic_impl" , description : "Lints for suspicious operations in impls of arithmetic operators, e.g.\\nsubtracting elements in an Add impl." } , LintCompletion { label : "clippy::suspicious_assignment_formatting" , description : "Checks for use of the non-existent `=*`, `=!` and `=-`\\noperators." } , LintCompletion { label : "clippy::suspicious_else_formatting" , description : "Checks for formatting of `else`. It lints if the `else`\\nis followed immediately by a newline or the `else` seems to be missing." } , LintCompletion { label : "clippy::suspicious_map" , description : "Checks for calls to `map` followed by a `count`." } , LintCompletion { label : "clippy::suspicious_op_assign_impl" , description : "Lints for suspicious operations in impls of OpAssign, e.g.\\nsubtracting elements in an AddAssign impl." } , LintCompletion { label : "clippy::suspicious_unary_op_formatting" , description : "Checks the formatting of a unary operator on the right hand side\\nof a binary operator. It lints if there is no space between the binary and unary operators,\\nbut there is a space between the unary and its operand." } , LintCompletion { label : "clippy::tabs_in_doc_comments" , description : "Checks doc comments for usage of tab characters." } , LintCompletion { label : "clippy::temporary_assignment" , description : "Checks for construction of a structure or tuple just to\\nassign a value in it." } , LintCompletion { label : "clippy::temporary_cstring_as_ptr" , description : "Checks for getting the inner pointer of a temporary\\n`CString`." } , LintCompletion { label : "clippy::to_digit_is_some" , description : "Checks for `.to_digit(..).is_some()` on `char`s." } , LintCompletion { label : "clippy::to_string_in_display" , description : "Checks for uses of `to_string()` in `Display` traits." } , LintCompletion { label : "clippy::todo" , description : "Checks for usage of `todo!`." } , LintCompletion { label : "clippy::too_many_arguments" , description : "Checks for functions with too many parameters." } , LintCompletion { label : "clippy::too_many_lines" , description : "Checks for functions with a large amount of lines." } , LintCompletion { label : "clippy::toplevel_ref_arg" , description : "Checks for function arguments and let bindings denoted as\\n`ref`." } , LintCompletion { label : "clippy::trait_duplication_in_bounds" , description : "Checks for cases where generics are being used and multiple\\nsyntax specifications for trait bounds are used simultaneously." } , LintCompletion { label : "clippy::transmute_bytes_to_str" , description : "Checks for transmutes from a `&[u8]` to a `&str`." } , LintCompletion { label : "clippy::transmute_float_to_int" , description : "Checks for transmutes from a float to an integer." } , LintCompletion { label : "clippy::transmute_int_to_bool" , description : "Checks for transmutes from an integer to a `bool`." } , LintCompletion { label : "clippy::transmute_int_to_char" , description : "Checks for transmutes from an integer to a `char`." } , LintCompletion { label : "clippy::transmute_int_to_float" , description : "Checks for transmutes from an integer to a float." } , LintCompletion { label : "clippy::transmute_ptr_to_ptr" , description : "Checks for transmutes from a pointer to a pointer, or\\nfrom a reference to a reference." } , LintCompletion { label : "clippy::transmute_ptr_to_ref" , description : "Checks for transmutes from a pointer to a reference." } , LintCompletion { label : "clippy::transmutes_expressible_as_ptr_casts" , description : "Checks for transmutes that could be a pointer cast." } , LintCompletion { label : "clippy::transmuting_null" , description : "Checks for transmute calls which would receive a null pointer." } , LintCompletion { label : "clippy::trivial_regex" , description : "Checks for trivial [regex](https://crates.io/crates/regex)\\ncreation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`)." } , LintCompletion { label : "clippy::trivially_copy_pass_by_ref" , description : "Checks for functions taking arguments by reference, where\\nthe argument type is `Copy` and small enough to be more efficient to always\\npass by value." } , LintCompletion { label : "clippy::try_err" , description : "Checks for usages of `Err(x)?`." } , LintCompletion { label : "clippy::type_complexity" , description : "Checks for types used in structs, parameters and `let`\\ndeclarations above a certain complexity threshold." } , LintCompletion { label : "clippy::type_repetition_in_bounds" , description : "This lint warns about unnecessary type repetitions in trait bounds" } , LintCompletion { label : "clippy::unicode_not_nfc" , description : "Checks for string literals that contain Unicode in a form\\nthat is not equal to its\\n[NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms)." } , LintCompletion { label : "clippy::unimplemented" , description : "Checks for usage of `unimplemented!`." } , LintCompletion { label : "clippy::uninit_assumed_init" , description : "Checks for `MaybeUninit::uninit().assume_init()`." } , LintCompletion { label : "clippy::unit_arg" , description : "Checks for passing a unit value as an argument to a function without using a\\nunit literal (`()`)." } , LintCompletion { label : "clippy::unit_cmp" , description : "Checks for comparisons to unit. This includes all binary\\ncomparisons (like `==` and `<`) and asserts." } , LintCompletion { label : "clippy::unit_return_expecting_ord" , description : "Checks for functions that expect closures of type\\nFn(...) -> Ord where the implemented closure returns the unit type.\\nThe lint also suggests to remove the semi-colon at the end of the statement if present." } , LintCompletion { label : "clippy::unknown_clippy_lints" , description : "Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy\\nlints and if those lints exist in clippy. If there is an uppercase letter in the lint name\\n(not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase\\nthe lint name." } , LintCompletion { label : "clippy::unnecessary_cast" , description : "Checks for casts to the same type, casts of int literals to integer types\\nand casts of float literals to float types." } , LintCompletion { label : "clippy::unnecessary_filter_map" , description : "Checks for `filter_map` calls which could be replaced by `filter` or `map`.\\nMore specifically it checks if the closure provided is only performing one of the\\nfilter or map operations and suggests the appropriate option." } , LintCompletion { label : "clippy::unnecessary_fold" , description : "Checks for using `fold` when a more succinct alternative exists.\\nSpecifically, this checks for `fold`s which could be replaced by `any`, `all`,\\n`sum` or `product`." } , LintCompletion { label : "clippy::unnecessary_lazy_evaluations" , description : "As the counterpart to `or_fun_call`, this lint looks for unnecessary\\nlazily evaluated closures on `Option` and `Result`.\\n\\nThis lint suggests changing the following functions, when eager evaluation results in\\nsimpler code:\\n - `unwrap_or_else` to `unwrap_or`\\n - `and_then` to `and`\\n - `or_else` to `or`\\n - `get_or_insert_with` to `get_or_insert`\\n - `ok_or_else` to `ok_or`" } , LintCompletion { label : "clippy::unnecessary_mut_passed" , description : "Detects passing a mutable reference to a function that only\\nrequires an immutable reference." } , LintCompletion { label : "clippy::unnecessary_operation" , description : "Checks for expression statements that can be reduced to a\\nsub-expression." } , LintCompletion { label : "clippy::unnecessary_sort_by" , description : "Detects uses of `Vec::sort_by` passing in a closure\\nwhich compares the two arguments, either directly or indirectly." } , LintCompletion { label : "clippy::unnecessary_unwrap" , description : "Checks for calls of `unwrap[_err]()` that cannot fail." } , LintCompletion { label : "clippy::unneeded_field_pattern" , description : "Checks for structure field patterns bound to wildcards." } , LintCompletion { label : "clippy::unneeded_wildcard_pattern" , description : "Checks for tuple patterns with a wildcard\\npattern (`_`) is next to a rest pattern (`..`).\\n\\n_NOTE_: While `_, ..` means there is at least one element left, `..`\\nmeans there are 0 or more elements left. This can make a difference\\nwhen refactoring, but shouldn't result in errors in the refactored code,\\nsince the wildcard pattern isn't used anyway." } , LintCompletion { label : "clippy::unnested_or_patterns" , description : "Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and\\nsuggests replacing the pattern with a nested one, `Some(0 | 2)`.\\n\\nAnother way to think of this is that it rewrites patterns in\\n*disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*." } , LintCompletion { label : "clippy::unreachable" , description : "Checks for usage of `unreachable!`." } , LintCompletion { label : "clippy::unreadable_literal" , description : "Warns if a long integral or floating-point constant does\\nnot contain underscores." } , LintCompletion { label : "clippy::unsafe_derive_deserialize" , description : "Checks for deriving `serde::Deserialize` on a type that\\nhas methods using `unsafe`." } , LintCompletion { label : "clippy::unsafe_removed_from_name" , description : "Checks for imports that remove \\\"unsafe\\\" from an item's\\nname." } , LintCompletion { label : "clippy::unsafe_vector_initialization" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unseparated_literal_suffix" , description : "Warns if literal suffixes are not separated by an\\nunderscore." } , LintCompletion { label : "clippy::unsound_collection_transmute" , description : "Checks for transmutes between collections whose\\ntypes have different ABI, size or alignment." } , LintCompletion { label : "clippy::unstable_as_mut_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unstable_as_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_collect" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_io_amount" , description : "Checks for unused written/read amount." } , LintCompletion { label : "clippy::unused_label" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_self" , description : "Checks methods that contain a `self` argument but don't use it" } , LintCompletion { label : "clippy::unused_unit" , description : "Checks for unit (`()`) expressions that can be removed." } , LintCompletion { label : "clippy::unwrap_in_result" , description : "Checks for functions of type Result that contain `expect()` or `unwrap()`" } , LintCompletion { label : "clippy::unwrap_used" , description : "Checks for `.unwrap()` calls on `Option`s and on `Result`s." } , LintCompletion { label : "clippy::use_debug" , description : "Checks for use of `Debug` formatting. The purpose of this\\nlint is to catch debugging remnants." } , LintCompletion { label : "clippy::use_self" , description : "Checks for unnecessary repetition of structure name when a\\nreplacement with `Self` is applicable." } , LintCompletion { label : "clippy::used_underscore_binding" , description : "Checks for the use of bindings with a single leading\\nunderscore." } , LintCompletion { label : "clippy::useless_asref" , description : "Checks for usage of `.as_ref()` or `.as_mut()` where the\\ntypes before and after the call are the same." } , LintCompletion { label : "clippy::useless_attribute" , description : "Checks for `extern crate` and `use` items annotated with\\nlint attributes.\\n\\nThis lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,\\n`#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and\\n`#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on\\n`extern crate` items with a `#[macro_use]` attribute." } , LintCompletion { label : "clippy::useless_conversion" , description : "Checks for `Into`, `TryInto`, `From`, `TryFrom`,`IntoIter` calls\\nthat useless converts to the same type as caller." } , LintCompletion { label : "clippy::useless_format" , description : "Checks for the use of `format!(\\\"string literal with no\\nargument\\\")` and `format!(\\\"{}\\\", foo)` where `foo` is a string." } , LintCompletion { label : "clippy::useless_let_if_seq" , description : "Checks for variable declarations immediately followed by a\\nconditional affectation." } , LintCompletion { label : "clippy::useless_transmute" , description : "Checks for transmutes to the original type of the object\\nand transmutes that could be a cast." } , LintCompletion { label : "clippy::useless_vec" , description : "Checks for usage of `&vec![..]` when using `&[..]` would\\nbe possible." } , LintCompletion { label : "clippy::vec_box" , description : "Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::vec_resize_to_zero" , description : "Finds occurrences of `Vec::resize(0, an_int)`" } , LintCompletion { label : "clippy::verbose_bit_mask" , description : "Checks for bit masks that can be replaced by a call\\nto `trailing_zeros`" } , LintCompletion { label : "clippy::verbose_file_reads" , description : "Checks for use of File::read_to_end and File::read_to_string." } , LintCompletion { label : "clippy::vtable_address_comparisons" , description : "Checks for comparisons with an address of a trait vtable." } , LintCompletion { label : "clippy::while_immutable_condition" , description : "Checks whether variables used within while loop condition\\ncan be (and are) mutated in the body." } , LintCompletion { label : "clippy::while_let_loop" , description : "Detects `loop + match` combinations that are easier\\nwritten as a `while let` loop." } , LintCompletion { label : "clippy::while_let_on_iterator" , description : "Checks for `while let` expressions on iterators." } , LintCompletion { label : "clippy::wildcard_dependencies" , description : "Checks for wildcard dependencies in the `Cargo.toml`." } , LintCompletion { label : "clippy::wildcard_enum_match_arm" , description : "Checks for wildcard enum matches using `_`." } , LintCompletion { label : "clippy::wildcard_imports" , description : "Checks for wildcard imports `use _::*`." } , LintCompletion { label : "clippy::wildcard_in_or_patterns" , description : "Checks for wildcard pattern used with others patterns in same match arm." } , LintCompletion { label : "clippy::write_literal" , description : "This lint warns about the use of literals as `write!`/`writeln!` args." } , LintCompletion { label : "clippy::write_with_newline" , description : "This lint warns when you use `write!()` with a format\\nstring that\\nends in a newline." } , LintCompletion { label : "clippy::writeln_empty_string" , description : "This lint warns when you use `writeln!(buf, \\\"\\\")` to\\nprint a newline." } , LintCompletion { label : "clippy::wrong_pub_self_convention" , description : "This is the same as\\n[`wrong_self_convention`](#wrong_self_convention), but for public items." } , LintCompletion { label : "clippy::wrong_self_convention" , description : "Checks for methods with certain name prefixes and which\\ndoesn't match how self is taken. The actual rules are:\\n\\n|Prefix |`self` taken |\\n|-------|----------------------|\\n|`as_` |`&self` or `&mut self`|\\n|`from_`| none |\\n|`into_`|`self` |\\n|`is_` |`&self` or none |\\n|`to_` |`&self` |" } , LintCompletion { label : "clippy::wrong_transmute" , description : "Checks for transmutes that can't ever be correct on any\\narchitecture." } , LintCompletion { label : "clippy::zero_divided_by_zero" , description : "Checks for `0.0 / 0.0`." } , LintCompletion { label : "clippy::zero_prefixed_literal" , description : "Warns if an integral constant literal starts with `0`." } , LintCompletion { label : "clippy::zero_ptr" , description : "Catch casts from `0` to some pointer type" } , LintCompletion { label : "clippy::zst_offset" , description : "Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to\\nzero-sized types" }] ; | ||
diff --git a/crates/ide/src/completion/completion_item.rs b/crates/completion/src/item.rs index 9377cdc57..6d1d085f4 100644 --- a/crates/ide/src/completion/completion_item.rs +++ b/crates/completion/src/item.rs | |||
@@ -1,12 +1,12 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! See `CompletionItem` structure. |
2 | 2 | ||
3 | use std::fmt; | 3 | use std::fmt; |
4 | 4 | ||
5 | use hir::Documentation; | 5 | use hir::{Documentation, Mutability}; |
6 | use syntax::TextRange; | 6 | use syntax::TextRange; |
7 | use text_edit::TextEdit; | 7 | use text_edit::TextEdit; |
8 | 8 | ||
9 | use crate::completion::completion_config::SnippetCap; | 9 | use crate::config::SnippetCap; |
10 | 10 | ||
11 | /// `CompletionItem` describes a single completion variant in the editor pop-up. | 11 | /// `CompletionItem` describes a single completion variant in the editor pop-up. |
12 | /// It is basically a POD with various properties. To construct a | 12 | /// It is basically a POD with various properties. To construct a |
@@ -56,6 +56,10 @@ pub struct CompletionItem { | |||
56 | 56 | ||
57 | /// Score is useful to pre select or display in better order completion items | 57 | /// Score is useful to pre select or display in better order completion items |
58 | score: Option<CompletionScore>, | 58 | score: Option<CompletionScore>, |
59 | |||
60 | /// Indicates that a reference or mutable reference to this variable is a | ||
61 | /// possible match. | ||
62 | ref_match: Option<(Mutability, CompletionScore)>, | ||
59 | } | 63 | } |
60 | 64 | ||
61 | // We use custom debug for CompletionItem to make snapshot tests more readable. | 65 | // We use custom debug for CompletionItem to make snapshot tests more readable. |
@@ -194,6 +198,7 @@ impl CompletionItem { | |||
194 | deprecated: None, | 198 | deprecated: None, |
195 | trigger_call_info: None, | 199 | trigger_call_info: None, |
196 | score: None, | 200 | score: None, |
201 | ref_match: None, | ||
197 | } | 202 | } |
198 | } | 203 | } |
199 | /// What user sees in pop-up in the UI. | 204 | /// What user sees in pop-up in the UI. |
@@ -240,10 +245,15 @@ impl CompletionItem { | |||
240 | pub fn trigger_call_info(&self) -> bool { | 245 | pub fn trigger_call_info(&self) -> bool { |
241 | self.trigger_call_info | 246 | self.trigger_call_info |
242 | } | 247 | } |
248 | |||
249 | pub fn ref_match(&self) -> Option<(Mutability, CompletionScore)> { | ||
250 | self.ref_match | ||
251 | } | ||
243 | } | 252 | } |
244 | 253 | ||
245 | /// A helper to make `CompletionItem`s. | 254 | /// A helper to make `CompletionItem`s. |
246 | #[must_use] | 255 | #[must_use] |
256 | #[derive(Clone)] | ||
247 | pub(crate) struct Builder { | 257 | pub(crate) struct Builder { |
248 | source_range: TextRange, | 258 | source_range: TextRange, |
249 | completion_kind: CompletionKind, | 259 | completion_kind: CompletionKind, |
@@ -258,13 +268,10 @@ pub(crate) struct Builder { | |||
258 | deprecated: Option<bool>, | 268 | deprecated: Option<bool>, |
259 | trigger_call_info: Option<bool>, | 269 | trigger_call_info: Option<bool>, |
260 | score: Option<CompletionScore>, | 270 | score: Option<CompletionScore>, |
271 | ref_match: Option<(Mutability, CompletionScore)>, | ||
261 | } | 272 | } |
262 | 273 | ||
263 | impl Builder { | 274 | impl Builder { |
264 | pub(crate) fn add_to(self, acc: &mut Completions) { | ||
265 | acc.add(self.build()) | ||
266 | } | ||
267 | |||
268 | pub(crate) fn build(self) -> CompletionItem { | 275 | pub(crate) fn build(self) -> CompletionItem { |
269 | let label = self.label; | 276 | let label = self.label; |
270 | let text_edit = match self.text_edit { | 277 | let text_edit = match self.text_edit { |
@@ -288,6 +295,7 @@ impl Builder { | |||
288 | deprecated: self.deprecated.unwrap_or(false), | 295 | deprecated: self.deprecated.unwrap_or(false), |
289 | trigger_call_info: self.trigger_call_info.unwrap_or(false), | 296 | trigger_call_info: self.trigger_call_info.unwrap_or(false), |
290 | score: self.score, | 297 | score: self.score, |
298 | ref_match: self.ref_match, | ||
291 | } | 299 | } |
292 | } | 300 | } |
293 | pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder { | 301 | pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder { |
@@ -350,6 +358,13 @@ impl Builder { | |||
350 | self.trigger_call_info = Some(true); | 358 | self.trigger_call_info = Some(true); |
351 | self | 359 | self |
352 | } | 360 | } |
361 | pub(crate) fn set_ref_match( | ||
362 | mut self, | ||
363 | ref_match: Option<(Mutability, CompletionScore)>, | ||
364 | ) -> Builder { | ||
365 | self.ref_match = ref_match; | ||
366 | self | ||
367 | } | ||
353 | } | 368 | } |
354 | 369 | ||
355 | impl<'a> Into<CompletionItem> for Builder { | 370 | impl<'a> Into<CompletionItem> for Builder { |
@@ -357,28 +372,3 @@ impl<'a> Into<CompletionItem> for Builder { | |||
357 | self.build() | 372 | self.build() |
358 | } | 373 | } |
359 | } | 374 | } |
360 | |||
361 | /// Represents an in-progress set of completions being built. | ||
362 | #[derive(Debug, Default)] | ||
363 | pub(crate) struct Completions { | ||
364 | buf: Vec<CompletionItem>, | ||
365 | } | ||
366 | |||
367 | impl Completions { | ||
368 | pub(crate) fn add(&mut self, item: impl Into<CompletionItem>) { | ||
369 | self.buf.push(item.into()) | ||
370 | } | ||
371 | pub(crate) fn add_all<I>(&mut self, items: I) | ||
372 | where | ||
373 | I: IntoIterator, | ||
374 | I::Item: Into<CompletionItem>, | ||
375 | { | ||
376 | items.into_iter().for_each(|item| self.add(item.into())) | ||
377 | } | ||
378 | } | ||
379 | |||
380 | impl Into<Vec<CompletionItem>> for Completions { | ||
381 | fn into(self) -> Vec<CompletionItem> { | ||
382 | self.buf | ||
383 | } | ||
384 | } | ||
diff --git a/crates/ide/src/completion.rs b/crates/completion/src/lib.rs index b0e35b2bd..89c0a9978 100644 --- a/crates/ide/src/completion.rs +++ b/crates/completion/src/lib.rs | |||
@@ -1,39 +1,23 @@ | |||
1 | mod completion_config; | 1 | //! `completions` crate provides utilities for generating completions of user input. |
2 | mod completion_item; | 2 | |
3 | mod completion_context; | 3 | mod config; |
4 | mod presentation; | 4 | mod item; |
5 | mod context; | ||
5 | mod patterns; | 6 | mod patterns; |
6 | mod generated_features; | 7 | mod generated_lint_completions; |
7 | #[cfg(test)] | 8 | #[cfg(test)] |
8 | mod test_utils; | 9 | mod test_utils; |
9 | 10 | ||
10 | mod complete_attribute; | 11 | mod completions; |
11 | mod complete_dot; | ||
12 | mod complete_record; | ||
13 | mod complete_pattern; | ||
14 | mod complete_fn_param; | ||
15 | mod complete_keyword; | ||
16 | mod complete_snippet; | ||
17 | mod complete_qualified_path; | ||
18 | mod complete_unqualified_path; | ||
19 | mod complete_postfix; | ||
20 | mod complete_macro_in_item_position; | ||
21 | mod complete_trait_impl; | ||
22 | mod complete_mod; | ||
23 | 12 | ||
13 | use ide_db::base_db::FilePosition; | ||
24 | use ide_db::RootDatabase; | 14 | use ide_db::RootDatabase; |
25 | 15 | ||
26 | use crate::{ | 16 | use crate::{completions::Completions, context::CompletionContext, item::CompletionKind}; |
27 | completion::{ | ||
28 | completion_context::CompletionContext, | ||
29 | completion_item::{CompletionKind, Completions}, | ||
30 | }, | ||
31 | FilePosition, | ||
32 | }; | ||
33 | 17 | ||
34 | pub use crate::completion::{ | 18 | pub use crate::{ |
35 | completion_config::CompletionConfig, | 19 | config::CompletionConfig, |
36 | completion_item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat}, | 20 | item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat}, |
37 | }; | 21 | }; |
38 | 22 | ||
39 | //FIXME: split the following feature into fine-grained features. | 23 | //FIXME: split the following feature into fine-grained features. |
@@ -105,37 +89,42 @@ pub use crate::completion::{ | |||
105 | /// `foo` *should* be present among the completion variants. Filtering by | 89 | /// `foo` *should* be present among the completion variants. Filtering by |
106 | /// identifier prefix/fuzzy match should be done higher in the stack, together | 90 | /// identifier prefix/fuzzy match should be done higher in the stack, together |
107 | /// with ordering of completions (currently this is done by the client). | 91 | /// with ordering of completions (currently this is done by the client). |
108 | pub(crate) fn completions( | 92 | pub fn completions( |
109 | db: &RootDatabase, | 93 | db: &RootDatabase, |
110 | config: &CompletionConfig, | 94 | config: &CompletionConfig, |
111 | position: FilePosition, | 95 | position: FilePosition, |
112 | ) -> Option<Completions> { | 96 | ) -> Option<Completions> { |
113 | let ctx = CompletionContext::new(db, position, config)?; | 97 | let ctx = CompletionContext::new(db, position, config)?; |
114 | 98 | ||
99 | if ctx.no_completion_required() { | ||
100 | // No work required here. | ||
101 | return None; | ||
102 | } | ||
103 | |||
115 | let mut acc = Completions::default(); | 104 | let mut acc = Completions::default(); |
116 | complete_attribute::complete_attribute(&mut acc, &ctx); | 105 | completions::attribute::complete_attribute(&mut acc, &ctx); |
117 | complete_fn_param::complete_fn_param(&mut acc, &ctx); | 106 | completions::fn_param::complete_fn_param(&mut acc, &ctx); |
118 | complete_keyword::complete_expr_keyword(&mut acc, &ctx); | 107 | completions::keyword::complete_expr_keyword(&mut acc, &ctx); |
119 | complete_keyword::complete_use_tree_keyword(&mut acc, &ctx); | 108 | completions::keyword::complete_use_tree_keyword(&mut acc, &ctx); |
120 | complete_snippet::complete_expr_snippet(&mut acc, &ctx); | 109 | completions::snippet::complete_expr_snippet(&mut acc, &ctx); |
121 | complete_snippet::complete_item_snippet(&mut acc, &ctx); | 110 | completions::snippet::complete_item_snippet(&mut acc, &ctx); |
122 | complete_qualified_path::complete_qualified_path(&mut acc, &ctx); | 111 | completions::qualified_path::complete_qualified_path(&mut acc, &ctx); |
123 | complete_unqualified_path::complete_unqualified_path(&mut acc, &ctx); | 112 | completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx); |
124 | complete_dot::complete_dot(&mut acc, &ctx); | 113 | completions::dot::complete_dot(&mut acc, &ctx); |
125 | complete_record::complete_record(&mut acc, &ctx); | 114 | completions::record::complete_record(&mut acc, &ctx); |
126 | complete_pattern::complete_pattern(&mut acc, &ctx); | 115 | completions::pattern::complete_pattern(&mut acc, &ctx); |
127 | complete_postfix::complete_postfix(&mut acc, &ctx); | 116 | completions::postfix::complete_postfix(&mut acc, &ctx); |
128 | complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx); | 117 | completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx); |
129 | complete_trait_impl::complete_trait_impl(&mut acc, &ctx); | 118 | completions::trait_impl::complete_trait_impl(&mut acc, &ctx); |
130 | complete_mod::complete_mod(&mut acc, &ctx); | 119 | completions::mod_::complete_mod(&mut acc, &ctx); |
131 | 120 | ||
132 | Some(acc) | 121 | Some(acc) |
133 | } | 122 | } |
134 | 123 | ||
135 | #[cfg(test)] | 124 | #[cfg(test)] |
136 | mod tests { | 125 | mod tests { |
137 | use crate::completion::completion_config::CompletionConfig; | 126 | use crate::config::CompletionConfig; |
138 | use crate::fixture; | 127 | use crate::test_utils; |
139 | 128 | ||
140 | struct DetailAndDocumentation<'a> { | 129 | struct DetailAndDocumentation<'a> { |
141 | detail: &'a str, | 130 | detail: &'a str, |
@@ -143,9 +132,9 @@ mod tests { | |||
143 | } | 132 | } |
144 | 133 | ||
145 | fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) { | 134 | fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) { |
146 | let (analysis, position) = fixture::position(ra_fixture); | 135 | let (db, position) = test_utils::position(ra_fixture); |
147 | let config = CompletionConfig::default(); | 136 | let config = CompletionConfig::default(); |
148 | let completions = analysis.completions(&config, position).unwrap().unwrap(); | 137 | let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into(); |
149 | for item in completions { | 138 | for item in completions { |
150 | if item.detail() == Some(expected.detail) { | 139 | if item.detail() == Some(expected.detail) { |
151 | let opt = item.documentation(); | 140 | let opt = item.documentation(); |
@@ -157,6 +146,27 @@ mod tests { | |||
157 | panic!("completion detail not found: {}", expected.detail) | 146 | panic!("completion detail not found: {}", expected.detail) |
158 | } | 147 | } |
159 | 148 | ||
149 | fn check_no_completion(ra_fixture: &str) { | ||
150 | let (db, position) = test_utils::position(ra_fixture); | ||
151 | let config = CompletionConfig::default(); | ||
152 | |||
153 | let completions: Option<Vec<String>> = crate::completions(&db, &config, position) | ||
154 | .and_then(|completions| { | ||
155 | let completions: Vec<_> = completions.into(); | ||
156 | if completions.is_empty() { | ||
157 | None | ||
158 | } else { | ||
159 | Some(completions) | ||
160 | } | ||
161 | }) | ||
162 | .map(|completions| { | ||
163 | completions.into_iter().map(|completion| format!("{:?}", completion)).collect() | ||
164 | }); | ||
165 | |||
166 | // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic. | ||
167 | assert_eq!(completions, None, "Completions were generated, but weren't expected"); | ||
168 | } | ||
169 | |||
160 | #[test] | 170 | #[test] |
161 | fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() { | 171 | fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() { |
162 | check_detail_and_documentation( | 172 | check_detail_and_documentation( |
@@ -208,4 +218,31 @@ mod tests { | |||
208 | DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" }, | 218 | DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" }, |
209 | ); | 219 | ); |
210 | } | 220 | } |
221 | |||
222 | #[test] | ||
223 | fn test_no_completions_required() { | ||
224 | // There must be no hint for 'in' keyword. | ||
225 | check_no_completion( | ||
226 | r#" | ||
227 | fn foo() { | ||
228 | for i i<|> | ||
229 | } | ||
230 | "#, | ||
231 | ); | ||
232 | // After 'in' keyword hints may be spawned. | ||
233 | check_detail_and_documentation( | ||
234 | r#" | ||
235 | /// Do the foo | ||
236 | fn foo() -> &'static str { "foo" } | ||
237 | |||
238 | fn bar() { | ||
239 | for c in fo<|> | ||
240 | } | ||
241 | "#, | ||
242 | DetailAndDocumentation { | ||
243 | detail: "fn foo() -> &'static str", | ||
244 | documentation: "Do the foo", | ||
245 | }, | ||
246 | ); | ||
247 | } | ||
211 | } | 248 | } |
diff --git a/crates/ide/src/completion/patterns.rs b/crates/completion/src/patterns.rs index b17ddf133..b0f35f9bf 100644 --- a/crates/ide/src/completion/patterns.rs +++ b/crates/completion/src/patterns.rs | |||
@@ -9,7 +9,7 @@ use syntax::{ | |||
9 | }; | 9 | }; |
10 | 10 | ||
11 | #[cfg(test)] | 11 | #[cfg(test)] |
12 | use crate::completion::test_utils::check_pattern_is_applicable; | 12 | use crate::test_utils::{check_pattern_is_applicable, check_pattern_is_not_applicable}; |
13 | 13 | ||
14 | pub(crate) fn has_trait_parent(element: SyntaxElement) -> bool { | 14 | pub(crate) fn has_trait_parent(element: SyntaxElement) -> bool { |
15 | not_same_range_ancestor(element) | 15 | not_same_range_ancestor(element) |
@@ -34,6 +34,25 @@ pub(crate) fn has_impl_parent(element: SyntaxElement) -> bool { | |||
34 | fn test_has_impl_parent() { | 34 | fn test_has_impl_parent() { |
35 | check_pattern_is_applicable(r"impl A { f<|> }", has_impl_parent); | 35 | check_pattern_is_applicable(r"impl A { f<|> }", has_impl_parent); |
36 | } | 36 | } |
37 | |||
38 | pub(crate) fn inside_impl_trait_block(element: SyntaxElement) -> bool { | ||
39 | // Here we search `impl` keyword up through the all ancestors, unlike in `has_impl_parent`, | ||
40 | // where we only check the first parent with different text range. | ||
41 | element | ||
42 | .ancestors() | ||
43 | .find(|it| it.kind() == IMPL) | ||
44 | .map(|it| ast::Impl::cast(it).unwrap()) | ||
45 | .map(|it| it.trait_().is_some()) | ||
46 | .unwrap_or(false) | ||
47 | } | ||
48 | #[test] | ||
49 | fn test_inside_impl_trait_block() { | ||
50 | check_pattern_is_applicable(r"impl Foo for Bar { f<|> }", inside_impl_trait_block); | ||
51 | check_pattern_is_applicable(r"impl Foo for Bar { fn f<|> }", inside_impl_trait_block); | ||
52 | check_pattern_is_not_applicable(r"impl A { f<|> }", inside_impl_trait_block); | ||
53 | check_pattern_is_not_applicable(r"impl A { fn f<|> }", inside_impl_trait_block); | ||
54 | } | ||
55 | |||
37 | pub(crate) fn has_field_list_parent(element: SyntaxElement) -> bool { | 56 | pub(crate) fn has_field_list_parent(element: SyntaxElement) -> bool { |
38 | not_same_range_ancestor(element).filter(|it| it.kind() == RECORD_FIELD_LIST).is_some() | 57 | not_same_range_ancestor(element).filter(|it| it.kind() == RECORD_FIELD_LIST).is_some() |
39 | } | 58 | } |
@@ -116,6 +135,33 @@ pub(crate) fn if_is_prev(element: SyntaxElement) -> bool { | |||
116 | .is_some() | 135 | .is_some() |
117 | } | 136 | } |
118 | 137 | ||
138 | pub(crate) fn fn_is_prev(element: SyntaxElement) -> bool { | ||
139 | element | ||
140 | .into_token() | ||
141 | .and_then(|it| previous_non_trivia_token(it)) | ||
142 | .filter(|it| it.kind() == FN_KW) | ||
143 | .is_some() | ||
144 | } | ||
145 | #[test] | ||
146 | fn test_fn_is_prev() { | ||
147 | check_pattern_is_applicable(r"fn l<|>", fn_is_prev); | ||
148 | } | ||
149 | |||
150 | /// Check if the token previous to the previous one is `for`. | ||
151 | /// For example, `for _ i<|>` => true. | ||
152 | pub(crate) fn for_is_prev2(element: SyntaxElement) -> bool { | ||
153 | element | ||
154 | .into_token() | ||
155 | .and_then(|it| previous_non_trivia_token(it)) | ||
156 | .and_then(|it| previous_non_trivia_token(it)) | ||
157 | .filter(|it| it.kind() == FOR_KW) | ||
158 | .is_some() | ||
159 | } | ||
160 | #[test] | ||
161 | fn test_for_is_prev2() { | ||
162 | check_pattern_is_applicable(r"for i i<|>", for_is_prev2); | ||
163 | } | ||
164 | |||
119 | #[test] | 165 | #[test] |
120 | fn test_if_is_prev() { | 166 | fn test_if_is_prev() { |
121 | check_pattern_is_applicable(r"if l<|>", if_is_prev); | 167 | check_pattern_is_applicable(r"if l<|>", if_is_prev); |
diff --git a/crates/ide/src/completion/test_utils.rs b/crates/completion/src/test_utils.rs index feb8cd2a6..4c1b1a839 100644 --- a/crates/ide/src/completion/test_utils.rs +++ b/crates/completion/src/test_utils.rs | |||
@@ -1,15 +1,27 @@ | |||
1 | //! Runs completion for testing purposes. | 1 | //! Runs completion for testing purposes. |
2 | 2 | ||
3 | use hir::Semantics; | 3 | use hir::Semantics; |
4 | use ide_db::base_db::{fixture::ChangeFixture, FileLoader, FilePosition}; | ||
5 | use ide_db::RootDatabase; | ||
4 | use itertools::Itertools; | 6 | use itertools::Itertools; |
5 | use stdx::{format_to, trim_indent}; | 7 | use stdx::{format_to, trim_indent}; |
6 | use syntax::{AstNode, NodeOrToken, SyntaxElement}; | 8 | use syntax::{AstNode, NodeOrToken, SyntaxElement}; |
7 | use test_utils::assert_eq_text; | 9 | use test_utils::{assert_eq_text, RangeOrOffset}; |
8 | 10 | ||
9 | use crate::{ | 11 | use crate::{item::CompletionKind, CompletionConfig, CompletionItem}; |
10 | completion::{completion_item::CompletionKind, CompletionConfig}, | 12 | |
11 | fixture, CompletionItem, | 13 | /// Creates analysis from a multi-file fixture, returns positions marked with <|>. |
12 | }; | 14 | pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) { |
15 | let change_fixture = ChangeFixture::parse(ra_fixture); | ||
16 | let mut database = RootDatabase::default(); | ||
17 | database.apply_change(change_fixture.change); | ||
18 | let (file_id, range_or_offset) = change_fixture.file_position.expect("expected a marker (<|>)"); | ||
19 | let offset = match range_or_offset { | ||
20 | RangeOrOffset::Range(_) => panic!(), | ||
21 | RangeOrOffset::Offset(it) => it, | ||
22 | }; | ||
23 | (database, FilePosition { file_id, offset }) | ||
24 | } | ||
13 | 25 | ||
14 | pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> { | 26 | pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> { |
15 | do_completion_with_config(CompletionConfig::default(), code, kind) | 27 | do_completion_with_config(CompletionConfig::default(), code, kind) |
@@ -20,10 +32,8 @@ pub(crate) fn do_completion_with_config( | |||
20 | code: &str, | 32 | code: &str, |
21 | kind: CompletionKind, | 33 | kind: CompletionKind, |
22 | ) -> Vec<CompletionItem> { | 34 | ) -> Vec<CompletionItem> { |
23 | let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code) | 35 | let mut kind_completions: Vec<CompletionItem> = |
24 | .into_iter() | 36 | get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect(); |
25 | .filter(|c| c.completion_kind == kind) | ||
26 | .collect(); | ||
27 | kind_completions.sort_by(|l, r| l.label().cmp(r.label())); | 37 | kind_completions.sort_by(|l, r| l.label().cmp(r.label())); |
28 | kind_completions | 38 | kind_completions |
29 | } | 39 | } |
@@ -37,10 +47,8 @@ pub(crate) fn completion_list_with_config( | |||
37 | code: &str, | 47 | code: &str, |
38 | kind: CompletionKind, | 48 | kind: CompletionKind, |
39 | ) -> String { | 49 | ) -> String { |
40 | let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code) | 50 | let mut kind_completions: Vec<CompletionItem> = |
41 | .into_iter() | 51 | get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect(); |
42 | .filter(|c| c.completion_kind == kind) | ||
43 | .collect(); | ||
44 | kind_completions.sort_by_key(|c| c.label().to_owned()); | 52 | kind_completions.sort_by_key(|c| c.label().to_owned()); |
45 | let label_width = kind_completions | 53 | let label_width = kind_completions |
46 | .iter() | 54 | .iter() |
@@ -79,35 +87,37 @@ pub(crate) fn check_edit_with_config( | |||
79 | ra_fixture_after: &str, | 87 | ra_fixture_after: &str, |
80 | ) { | 88 | ) { |
81 | let ra_fixture_after = trim_indent(ra_fixture_after); | 89 | let ra_fixture_after = trim_indent(ra_fixture_after); |
82 | let (analysis, position) = fixture::position(ra_fixture_before); | 90 | let (db, position) = position(ra_fixture_before); |
83 | let completions: Vec<CompletionItem> = | 91 | let completions: Vec<CompletionItem> = |
84 | analysis.completions(&config, position).unwrap().unwrap().into(); | 92 | crate::completions(&db, &config, position).unwrap().into(); |
85 | let (completion,) = completions | 93 | let (completion,) = completions |
86 | .iter() | 94 | .iter() |
87 | .filter(|it| it.lookup() == what) | 95 | .filter(|it| it.lookup() == what) |
88 | .collect_tuple() | 96 | .collect_tuple() |
89 | .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions)); | 97 | .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions)); |
90 | let mut actual = analysis.file_text(position.file_id).unwrap().to_string(); | 98 | let mut actual = db.file_text(position.file_id).to_string(); |
91 | completion.text_edit().apply(&mut actual); | 99 | completion.text_edit().apply(&mut actual); |
92 | assert_eq_text!(&ra_fixture_after, &actual) | 100 | assert_eq_text!(&ra_fixture_after, &actual) |
93 | } | 101 | } |
94 | 102 | ||
95 | pub(crate) fn check_pattern_is_applicable(code: &str, check: fn(SyntaxElement) -> bool) { | 103 | pub(crate) fn check_pattern_is_applicable(code: &str, check: fn(SyntaxElement) -> bool) { |
96 | let (analysis, pos) = fixture::position(code); | 104 | let (db, pos) = position(code); |
97 | analysis | 105 | |
98 | .with_db(|db| { | 106 | let sema = Semantics::new(&db); |
99 | let sema = Semantics::new(db); | 107 | let original_file = sema.parse(pos.file_id); |
100 | let original_file = sema.parse(pos.file_id); | 108 | let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap(); |
101 | let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap(); | 109 | assert!(check(NodeOrToken::Token(token))); |
102 | assert!(check(NodeOrToken::Token(token))); | ||
103 | }) | ||
104 | .unwrap(); | ||
105 | } | 110 | } |
106 | 111 | ||
107 | pub(crate) fn get_all_completion_items( | 112 | pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) { |
108 | config: CompletionConfig, | 113 | let (db, pos) = position(code); |
109 | code: &str, | 114 | let sema = Semantics::new(&db); |
110 | ) -> Vec<CompletionItem> { | 115 | let original_file = sema.parse(pos.file_id); |
111 | let (analysis, position) = fixture::position(code); | 116 | let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap(); |
112 | analysis.completions(&config, position).unwrap().unwrap().into() | 117 | assert!(!check(NodeOrToken::Token(token))); |
118 | } | ||
119 | |||
120 | pub(crate) fn get_all_items(config: CompletionConfig, code: &str) -> Vec<CompletionItem> { | ||
121 | let (db, position) = position(code); | ||
122 | crate::completions(&db, &config, position).unwrap().into() | ||
113 | } | 123 | } |
diff --git a/crates/flycheck/Cargo.toml b/crates/flycheck/Cargo.toml index 4e2b60b73..44499bc79 100644 --- a/crates/flycheck/Cargo.toml +++ b/crates/flycheck/Cargo.toml | |||
@@ -12,7 +12,7 @@ doctest = false | |||
12 | [dependencies] | 12 | [dependencies] |
13 | crossbeam-channel = "0.5.0" | 13 | crossbeam-channel = "0.5.0" |
14 | log = "0.4.8" | 14 | log = "0.4.8" |
15 | cargo_metadata = "0.11.1" | 15 | cargo_metadata = "0.12.0" |
16 | serde_json = "1.0.48" | 16 | serde_json = "1.0.48" |
17 | jod-thread = "0.1.1" | 17 | jod-thread = "0.1.1" |
18 | 18 | ||
diff --git a/crates/hir/src/code_model.rs b/crates/hir/src/code_model.rs index b65be4fe1..63c1a8ebf 100644 --- a/crates/hir/src/code_model.rs +++ b/crates/hir/src/code_model.rs | |||
@@ -2,7 +2,7 @@ | |||
2 | use std::{iter, sync::Arc}; | 2 | use std::{iter, sync::Arc}; |
3 | 3 | ||
4 | use arrayvec::ArrayVec; | 4 | use arrayvec::ArrayVec; |
5 | use base_db::{CrateId, CrateName, Edition, FileId}; | 5 | use base_db::{CrateDisplayName, CrateId, Edition, FileId}; |
6 | use either::Either; | 6 | use either::Either; |
7 | use hir_def::find_path::PrefixKind; | 7 | use hir_def::find_path::PrefixKind; |
8 | use hir_def::{ | 8 | use hir_def::{ |
@@ -31,8 +31,7 @@ use hir_ty::{ | |||
31 | autoderef, | 31 | autoderef, |
32 | display::{HirDisplayError, HirFormatter}, | 32 | display::{HirDisplayError, HirFormatter}, |
33 | method_resolution, | 33 | method_resolution, |
34 | traits::Solution, | 34 | traits::{FnTrait, Solution, SolutionVariables}, |
35 | traits::SolutionVariables, | ||
36 | ApplicationTy, BoundVar, CallableDefId, Canonical, DebruijnIndex, FnSig, GenericPredicate, | 35 | ApplicationTy, BoundVar, CallableDefId, Canonical, DebruijnIndex, FnSig, GenericPredicate, |
37 | InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, Ty, | 36 | InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, Ty, |
38 | TyDefId, TyKind, TypeCtor, | 37 | TyDefId, TyKind, TypeCtor, |
@@ -103,8 +102,8 @@ impl Crate { | |||
103 | db.crate_graph()[self.id].edition | 102 | db.crate_graph()[self.id].edition |
104 | } | 103 | } |
105 | 104 | ||
106 | pub fn declaration_name(self, db: &dyn HirDatabase) -> Option<CrateName> { | 105 | pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> { |
107 | db.crate_graph()[self.id].declaration_name.clone() | 106 | db.crate_graph()[self.id].display_name.clone() |
108 | } | 107 | } |
109 | 108 | ||
110 | pub fn query_external_importables( | 109 | pub fn query_external_importables( |
@@ -781,6 +780,7 @@ impl Function { | |||
781 | } | 780 | } |
782 | 781 | ||
783 | pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { | 782 | pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { |
783 | hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink); | ||
784 | hir_ty::diagnostics::validate_module_item(db, self.id.into(), sink); | 784 | hir_ty::diagnostics::validate_module_item(db, self.id.into(), sink); |
785 | hir_ty::diagnostics::validate_body(db, self.id.into(), sink); | 785 | hir_ty::diagnostics::validate_body(db, self.id.into(), sink); |
786 | } | 786 | } |
@@ -1385,6 +1385,28 @@ impl Type { | |||
1385 | ) | 1385 | ) |
1386 | } | 1386 | } |
1387 | 1387 | ||
1388 | /// Checks that particular type `ty` implements `std::ops::FnOnce`. | ||
1389 | /// | ||
1390 | /// This function can be used to check if a particular type is callable, since FnOnce is a | ||
1391 | /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce. | ||
1392 | pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool { | ||
1393 | let krate = self.krate; | ||
1394 | |||
1395 | let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) { | ||
1396 | Some(it) => it, | ||
1397 | None => return false, | ||
1398 | }; | ||
1399 | |||
1400 | let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1401 | method_resolution::implements_trait( | ||
1402 | &canonical_ty, | ||
1403 | db, | ||
1404 | self.ty.environment.clone(), | ||
1405 | krate, | ||
1406 | fnonce_trait, | ||
1407 | ) | ||
1408 | } | ||
1409 | |||
1388 | pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool { | 1410 | pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool { |
1389 | let trait_ref = hir_ty::TraitRef { | 1411 | let trait_ref = hir_ty::TraitRef { |
1390 | trait_: trait_.id, | 1412 | trait_: trait_.id, |
diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs index da2b40849..c18c1c587 100644 --- a/crates/hir/src/diagnostics.rs +++ b/crates/hir/src/diagnostics.rs | |||
@@ -1,5 +1,5 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | pub use hir_def::diagnostics::UnresolvedModule; | 2 | pub use hir_def::diagnostics::{InactiveCode, UnresolvedModule}; |
3 | pub use hir_expand::diagnostics::{Diagnostic, DiagnosticSink, DiagnosticSinkBuilder}; | 3 | pub use hir_expand::diagnostics::{Diagnostic, DiagnosticSink, DiagnosticSinkBuilder}; |
4 | pub use hir_ty::diagnostics::{ | 4 | pub use hir_ty::diagnostics::{ |
5 | IncorrectCase, MismatchedArgCount, MissingFields, MissingMatchArms, MissingOkInTailExpr, | 5 | IncorrectCase, MismatchedArgCount, MissingFields, MissingMatchArms, MissingOkInTailExpr, |
diff --git a/crates/hir_def/src/attr.rs b/crates/hir_def/src/attr.rs index dea552a60..b2ce7ca3c 100644 --- a/crates/hir_def/src/attr.rs +++ b/crates/hir_def/src/attr.rs | |||
@@ -125,12 +125,20 @@ impl Attrs { | |||
125 | AttrQuery { attrs: self, key } | 125 | AttrQuery { attrs: self, key } |
126 | } | 126 | } |
127 | 127 | ||
128 | pub fn cfg(&self) -> impl Iterator<Item = CfgExpr> + '_ { | 128 | pub fn cfg(&self) -> Option<CfgExpr> { |
129 | // FIXME: handle cfg_attr :-) | 129 | // FIXME: handle cfg_attr :-) |
130 | self.by_key("cfg").tt_values().map(CfgExpr::parse) | 130 | let mut cfgs = self.by_key("cfg").tt_values().map(CfgExpr::parse).collect::<Vec<_>>(); |
131 | match cfgs.len() { | ||
132 | 0 => None, | ||
133 | 1 => Some(cfgs.pop().unwrap()), | ||
134 | _ => Some(CfgExpr::All(cfgs)), | ||
135 | } | ||
131 | } | 136 | } |
132 | pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool { | 137 | pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> bool { |
133 | self.cfg().all(|cfg| cfg_options.check(&cfg) != Some(false)) | 138 | match self.cfg() { |
139 | None => true, | ||
140 | Some(cfg) => cfg_options.check(&cfg) != Some(false), | ||
141 | } | ||
134 | } | 142 | } |
135 | } | 143 | } |
136 | 144 | ||
diff --git a/crates/hir_def/src/body.rs b/crates/hir_def/src/body.rs index 9a9a605dd..d10b1af01 100644 --- a/crates/hir_def/src/body.rs +++ b/crates/hir_def/src/body.rs | |||
@@ -1,6 +1,9 @@ | |||
1 | //! Defines `Body`: a lowered representation of bodies of functions, statics and | 1 | //! Defines `Body`: a lowered representation of bodies of functions, statics and |
2 | //! consts. | 2 | //! consts. |
3 | mod lower; | 3 | mod lower; |
4 | mod diagnostics; | ||
5 | #[cfg(test)] | ||
6 | mod tests; | ||
4 | pub mod scope; | 7 | pub mod scope; |
5 | 8 | ||
6 | use std::{mem, ops::Index, sync::Arc}; | 9 | use std::{mem, ops::Index, sync::Arc}; |
@@ -10,7 +13,10 @@ use base_db::CrateId; | |||
10 | use cfg::CfgOptions; | 13 | use cfg::CfgOptions; |
11 | use drop_bomb::DropBomb; | 14 | use drop_bomb::DropBomb; |
12 | use either::Either; | 15 | use either::Either; |
13 | use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, AstId, HirFileId, InFile, MacroDefId}; | 16 | use hir_expand::{ |
17 | ast_id_map::AstIdMap, diagnostics::DiagnosticSink, hygiene::Hygiene, AstId, HirFileId, InFile, | ||
18 | MacroDefId, | ||
19 | }; | ||
14 | use rustc_hash::FxHashMap; | 20 | use rustc_hash::FxHashMap; |
15 | use syntax::{ast, AstNode, AstPtr}; | 21 | use syntax::{ast, AstNode, AstPtr}; |
16 | use test_utils::mark; | 22 | use test_utils::mark; |
@@ -105,14 +111,16 @@ impl Expander { | |||
105 | 111 | ||
106 | let macro_call = InFile::new(self.current_file_id, ¯o_call); | 112 | let macro_call = InFile::new(self.current_file_id, ¯o_call); |
107 | 113 | ||
108 | if let Some(call_id) = macro_call.as_call_id(db, self.crate_def_map.krate, |path| { | 114 | let resolver = |path: ModPath| -> Option<MacroDefId> { |
109 | if let Some(local_scope) = local_scope { | 115 | if let Some(local_scope) = local_scope { |
110 | if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) { | 116 | if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) { |
111 | return Some(def); | 117 | return Some(def); |
112 | } | 118 | } |
113 | } | 119 | } |
114 | self.resolve_path_as_macro(db, &path) | 120 | self.resolve_path_as_macro(db, &path) |
115 | }) { | 121 | }; |
122 | |||
123 | if let Some(call_id) = macro_call.as_call_id(db, self.crate_def_map.krate, resolver) { | ||
116 | let file_id = call_id.as_file(); | 124 | let file_id = call_id.as_file(); |
117 | if let Some(node) = db.parse_or_expand(file_id) { | 125 | if let Some(node) = db.parse_or_expand(file_id) { |
118 | if let Some(expr) = T::cast(node) { | 126 | if let Some(expr) = T::cast(node) { |
@@ -148,8 +156,12 @@ impl Expander { | |||
148 | InFile { file_id: self.current_file_id, value } | 156 | InFile { file_id: self.current_file_id, value } |
149 | } | 157 | } |
150 | 158 | ||
151 | pub(crate) fn is_cfg_enabled(&self, owner: &dyn ast::AttrsOwner) -> bool { | 159 | pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs { |
152 | self.cfg_expander.is_cfg_enabled(owner) | 160 | self.cfg_expander.parse_attrs(owner) |
161 | } | ||
162 | |||
163 | pub(crate) fn cfg_options(&self) -> &CfgOptions { | ||
164 | &self.cfg_expander.cfg_options | ||
153 | } | 165 | } |
154 | 166 | ||
155 | fn parse_path(&mut self, path: ast::Path) -> Option<Path> { | 167 | fn parse_path(&mut self, path: ast::Path) -> Option<Path> { |
@@ -217,6 +229,10 @@ pub struct BodySourceMap { | |||
217 | pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>, | 229 | pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>, |
218 | field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>, | 230 | field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>, |
219 | expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>, | 231 | expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>, |
232 | |||
233 | /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in | ||
234 | /// the source map (since they're just as volatile). | ||
235 | diagnostics: Vec<diagnostics::BodyDiagnostic>, | ||
220 | } | 236 | } |
221 | 237 | ||
222 | #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)] | 238 | #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)] |
@@ -316,45 +332,10 @@ impl BodySourceMap { | |||
316 | pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> { | 332 | pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> { |
317 | self.field_map[&(expr, field)].clone() | 333 | self.field_map[&(expr, field)].clone() |
318 | } | 334 | } |
319 | } | ||
320 | 335 | ||
321 | #[cfg(test)] | 336 | pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) { |
322 | mod tests { | 337 | for diag in &self.diagnostics { |
323 | use base_db::{fixture::WithFixture, SourceDatabase}; | 338 | diag.add_to(sink); |
324 | use test_utils::mark; | 339 | } |
325 | |||
326 | use crate::ModuleDefId; | ||
327 | |||
328 | use super::*; | ||
329 | |||
330 | fn lower(ra_fixture: &str) -> Arc<Body> { | ||
331 | let (db, file_id) = crate::test_db::TestDB::with_single_file(ra_fixture); | ||
332 | |||
333 | let krate = db.crate_graph().iter().next().unwrap(); | ||
334 | let def_map = db.crate_def_map(krate); | ||
335 | let module = def_map.modules_for_file(file_id).next().unwrap(); | ||
336 | let module = &def_map[module]; | ||
337 | let fn_def = match module.scope.declarations().next().unwrap() { | ||
338 | ModuleDefId::FunctionId(it) => it, | ||
339 | _ => panic!(), | ||
340 | }; | ||
341 | |||
342 | db.body(fn_def.into()) | ||
343 | } | ||
344 | |||
345 | #[test] | ||
346 | fn your_stack_belongs_to_me() { | ||
347 | mark::check!(your_stack_belongs_to_me); | ||
348 | lower( | ||
349 | " | ||
350 | macro_rules! n_nuple { | ||
351 | ($e:tt) => (); | ||
352 | ($($rest:tt)*) => {{ | ||
353 | (n_nuple!($($rest)*)None,) | ||
354 | }}; | ||
355 | } | ||
356 | fn main() { n_nuple!(1,2,3); } | ||
357 | ", | ||
358 | ); | ||
359 | } | 340 | } |
360 | } | 341 | } |
diff --git a/crates/hir_def/src/body/diagnostics.rs b/crates/hir_def/src/body/diagnostics.rs new file mode 100644 index 000000000..cfa47d189 --- /dev/null +++ b/crates/hir_def/src/body/diagnostics.rs | |||
@@ -0,0 +1,20 @@ | |||
1 | //! Diagnostics emitted during body lowering. | ||
2 | |||
3 | use hir_expand::diagnostics::DiagnosticSink; | ||
4 | |||
5 | use crate::diagnostics::InactiveCode; | ||
6 | |||
7 | #[derive(Debug, Eq, PartialEq)] | ||
8 | pub enum BodyDiagnostic { | ||
9 | InactiveCode(InactiveCode), | ||
10 | } | ||
11 | |||
12 | impl BodyDiagnostic { | ||
13 | pub fn add_to(&self, sink: &mut DiagnosticSink<'_>) { | ||
14 | match self { | ||
15 | BodyDiagnostic::InactiveCode(diag) => { | ||
16 | sink.push(diag.clone()); | ||
17 | } | ||
18 | } | ||
19 | } | ||
20 | } | ||
diff --git a/crates/hir_def/src/body/lower.rs b/crates/hir_def/src/body/lower.rs index 01e72690a..ddc267b83 100644 --- a/crates/hir_def/src/body/lower.rs +++ b/crates/hir_def/src/body/lower.rs | |||
@@ -16,7 +16,7 @@ use syntax::{ | |||
16 | self, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner, | 16 | self, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner, |
17 | SlicePatComponents, | 17 | SlicePatComponents, |
18 | }, | 18 | }, |
19 | AstNode, AstPtr, | 19 | AstNode, AstPtr, SyntaxNodePtr, |
20 | }; | 20 | }; |
21 | use test_utils::mark; | 21 | use test_utils::mark; |
22 | 22 | ||
@@ -25,6 +25,7 @@ use crate::{ | |||
25 | body::{Body, BodySourceMap, Expander, PatPtr, SyntheticSyntax}, | 25 | body::{Body, BodySourceMap, Expander, PatPtr, SyntheticSyntax}, |
26 | builtin_type::{BuiltinFloat, BuiltinInt}, | 26 | builtin_type::{BuiltinFloat, BuiltinInt}, |
27 | db::DefDatabase, | 27 | db::DefDatabase, |
28 | diagnostics::InactiveCode, | ||
28 | expr::{ | 29 | expr::{ |
29 | dummy_expr_id, ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, | 30 | dummy_expr_id, ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, |
30 | LogicOp, MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, | 31 | LogicOp, MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, |
@@ -37,7 +38,7 @@ use crate::{ | |||
37 | StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc, | 38 | StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc, |
38 | }; | 39 | }; |
39 | 40 | ||
40 | use super::{ExprSource, PatSource}; | 41 | use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource}; |
41 | 42 | ||
42 | pub(crate) struct LowerCtx { | 43 | pub(crate) struct LowerCtx { |
43 | hygiene: Hygiene, | 44 | hygiene: Hygiene, |
@@ -176,7 +177,7 @@ impl ExprCollector<'_> { | |||
176 | 177 | ||
177 | fn collect_expr(&mut self, expr: ast::Expr) -> ExprId { | 178 | fn collect_expr(&mut self, expr: ast::Expr) -> ExprId { |
178 | let syntax_ptr = AstPtr::new(&expr); | 179 | let syntax_ptr = AstPtr::new(&expr); |
179 | if !self.expander.is_cfg_enabled(&expr) { | 180 | if self.check_cfg(&expr).is_none() { |
180 | return self.missing_expr(); | 181 | return self.missing_expr(); |
181 | } | 182 | } |
182 | 183 | ||
@@ -354,13 +355,15 @@ impl ExprCollector<'_> { | |||
354 | let arms = if let Some(match_arm_list) = e.match_arm_list() { | 355 | let arms = if let Some(match_arm_list) = e.match_arm_list() { |
355 | match_arm_list | 356 | match_arm_list |
356 | .arms() | 357 | .arms() |
357 | .map(|arm| MatchArm { | 358 | .filter_map(|arm| { |
358 | pat: self.collect_pat_opt(arm.pat()), | 359 | self.check_cfg(&arm).map(|()| MatchArm { |
359 | expr: self.collect_expr_opt(arm.expr()), | 360 | pat: self.collect_pat_opt(arm.pat()), |
360 | guard: arm | 361 | expr: self.collect_expr_opt(arm.expr()), |
361 | .guard() | 362 | guard: arm |
362 | .and_then(|guard| guard.expr()) | 363 | .guard() |
363 | .map(|e| self.collect_expr(e)), | 364 | .and_then(|guard| guard.expr()) |
365 | .map(|e| self.collect_expr(e)), | ||
366 | }) | ||
364 | }) | 367 | }) |
365 | .collect() | 368 | .collect() |
366 | } else { | 369 | } else { |
@@ -406,9 +409,8 @@ impl ExprCollector<'_> { | |||
406 | .fields() | 409 | .fields() |
407 | .inspect(|field| field_ptrs.push(AstPtr::new(field))) | 410 | .inspect(|field| field_ptrs.push(AstPtr::new(field))) |
408 | .filter_map(|field| { | 411 | .filter_map(|field| { |
409 | if !self.expander.is_cfg_enabled(&field) { | 412 | self.check_cfg(&field)?; |
410 | return None; | 413 | |
411 | } | ||
412 | let name = field.field_name()?.as_name(); | 414 | let name = field.field_name()?.as_name(); |
413 | 415 | ||
414 | Some(RecordLitField { | 416 | Some(RecordLitField { |
@@ -620,15 +622,23 @@ impl ExprCollector<'_> { | |||
620 | .filter_map(|s| { | 622 | .filter_map(|s| { |
621 | let stmt = match s { | 623 | let stmt = match s { |
622 | ast::Stmt::LetStmt(stmt) => { | 624 | ast::Stmt::LetStmt(stmt) => { |
625 | self.check_cfg(&stmt)?; | ||
626 | |||
623 | let pat = self.collect_pat_opt(stmt.pat()); | 627 | let pat = self.collect_pat_opt(stmt.pat()); |
624 | let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it)); | 628 | let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it)); |
625 | let initializer = stmt.initializer().map(|e| self.collect_expr(e)); | 629 | let initializer = stmt.initializer().map(|e| self.collect_expr(e)); |
626 | Statement::Let { pat, type_ref, initializer } | 630 | Statement::Let { pat, type_ref, initializer } |
627 | } | 631 | } |
628 | ast::Stmt::ExprStmt(stmt) => { | 632 | ast::Stmt::ExprStmt(stmt) => { |
633 | self.check_cfg(&stmt)?; | ||
634 | |||
629 | Statement::Expr(self.collect_expr_opt(stmt.expr())) | 635 | Statement::Expr(self.collect_expr_opt(stmt.expr())) |
630 | } | 636 | } |
631 | ast::Stmt::Item(_) => return None, | 637 | ast::Stmt::Item(item) => { |
638 | self.check_cfg(&item)?; | ||
639 | |||
640 | return None; | ||
641 | } | ||
632 | }; | 642 | }; |
633 | Some(stmt) | 643 | Some(stmt) |
634 | }) | 644 | }) |
@@ -872,6 +882,28 @@ impl ExprCollector<'_> { | |||
872 | 882 | ||
873 | (args, ellipsis) | 883 | (args, ellipsis) |
874 | } | 884 | } |
885 | |||
886 | /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when | ||
887 | /// not. | ||
888 | fn check_cfg(&mut self, owner: &dyn ast::AttrsOwner) -> Option<()> { | ||
889 | match self.expander.parse_attrs(owner).cfg() { | ||
890 | Some(cfg) => { | ||
891 | if self.expander.cfg_options().check(&cfg) != Some(false) { | ||
892 | return Some(()); | ||
893 | } | ||
894 | |||
895 | self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode(InactiveCode { | ||
896 | file: self.expander.current_file_id, | ||
897 | node: SyntaxNodePtr::new(owner.syntax()), | ||
898 | cfg, | ||
899 | opts: self.expander.cfg_options().clone(), | ||
900 | })); | ||
901 | |||
902 | None | ||
903 | } | ||
904 | None => Some(()), | ||
905 | } | ||
906 | } | ||
875 | } | 907 | } |
876 | 908 | ||
877 | impl From<ast::BinOp> for BinaryOp { | 909 | impl From<ast::BinOp> for BinaryOp { |
diff --git a/crates/hir_def/src/body/tests.rs b/crates/hir_def/src/body/tests.rs new file mode 100644 index 000000000..f07df5cee --- /dev/null +++ b/crates/hir_def/src/body/tests.rs | |||
@@ -0,0 +1,75 @@ | |||
1 | use base_db::{fixture::WithFixture, SourceDatabase}; | ||
2 | use test_utils::mark; | ||
3 | |||
4 | use crate::{test_db::TestDB, ModuleDefId}; | ||
5 | |||
6 | use super::*; | ||
7 | |||
8 | fn lower(ra_fixture: &str) -> Arc<Body> { | ||
9 | let (db, file_id) = crate::test_db::TestDB::with_single_file(ra_fixture); | ||
10 | |||
11 | let krate = db.crate_graph().iter().next().unwrap(); | ||
12 | let def_map = db.crate_def_map(krate); | ||
13 | let module = def_map.modules_for_file(file_id).next().unwrap(); | ||
14 | let module = &def_map[module]; | ||
15 | let fn_def = match module.scope.declarations().next().unwrap() { | ||
16 | ModuleDefId::FunctionId(it) => it, | ||
17 | _ => panic!(), | ||
18 | }; | ||
19 | |||
20 | db.body(fn_def.into()) | ||
21 | } | ||
22 | |||
23 | fn check_diagnostics(ra_fixture: &str) { | ||
24 | let db: TestDB = TestDB::with_files(ra_fixture); | ||
25 | db.check_diagnostics(); | ||
26 | } | ||
27 | |||
28 | #[test] | ||
29 | fn your_stack_belongs_to_me() { | ||
30 | mark::check!(your_stack_belongs_to_me); | ||
31 | lower( | ||
32 | " | ||
33 | macro_rules! n_nuple { | ||
34 | ($e:tt) => (); | ||
35 | ($($rest:tt)*) => {{ | ||
36 | (n_nuple!($($rest)*)None,) | ||
37 | }}; | ||
38 | } | ||
39 | fn main() { n_nuple!(1,2,3); } | ||
40 | ", | ||
41 | ); | ||
42 | } | ||
43 | |||
44 | #[test] | ||
45 | fn cfg_diagnostics() { | ||
46 | check_diagnostics( | ||
47 | r" | ||
48 | fn f() { | ||
49 | // The three g̶e̶n̶d̶e̶r̶s̶ statements: | ||
50 | |||
51 | #[cfg(a)] fn f() {} // Item statement | ||
52 | //^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
53 | #[cfg(a)] {} // Expression statement | ||
54 | //^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
55 | #[cfg(a)] let x = 0; // let statement | ||
56 | //^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
57 | |||
58 | abc(#[cfg(a)] 0); | ||
59 | //^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
60 | let x = Struct { | ||
61 | #[cfg(a)] f: 0, | ||
62 | //^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
63 | }; | ||
64 | match () { | ||
65 | () => (), | ||
66 | #[cfg(a)] () => (), | ||
67 | //^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
68 | } | ||
69 | |||
70 | #[cfg(a)] 0 // Trailing expression of block | ||
71 | //^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled | ||
72 | } | ||
73 | ", | ||
74 | ); | ||
75 | } | ||
diff --git a/crates/hir_def/src/diagnostics.rs b/crates/hir_def/src/diagnostics.rs index 001b3c5db..b221b290c 100644 --- a/crates/hir_def/src/diagnostics.rs +++ b/crates/hir_def/src/diagnostics.rs | |||
@@ -1,12 +1,23 @@ | |||
1 | //! Diagnostics produced by `hir_def`. | 1 | //! Diagnostics produced by `hir_def`. |
2 | 2 | ||
3 | use std::any::Any; | 3 | use std::any::Any; |
4 | use stdx::format_to; | ||
4 | 5 | ||
5 | use hir_expand::diagnostics::{Diagnostic, DiagnosticCode}; | 6 | use cfg::{CfgExpr, CfgOptions, DnfExpr}; |
7 | use hir_expand::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticSink}; | ||
8 | use hir_expand::{HirFileId, InFile}; | ||
6 | use syntax::{ast, AstPtr, SyntaxNodePtr}; | 9 | use syntax::{ast, AstPtr, SyntaxNodePtr}; |
7 | 10 | ||
8 | use hir_expand::{HirFileId, InFile}; | 11 | use crate::{db::DefDatabase, DefWithBodyId}; |
9 | 12 | ||
13 | pub fn validate_body(db: &dyn DefDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) { | ||
14 | let source_map = db.body_with_source_map(owner).1; | ||
15 | source_map.add_diagnostics(db, sink); | ||
16 | } | ||
17 | |||
18 | // Diagnostic: unresolved-module | ||
19 | // | ||
20 | // This diagnostic is triggered if rust-analyzer is unable to discover referred module. | ||
10 | #[derive(Debug)] | 21 | #[derive(Debug)] |
11 | pub struct UnresolvedModule { | 22 | pub struct UnresolvedModule { |
12 | pub file: HirFileId, | 23 | pub file: HirFileId, |
@@ -29,6 +40,9 @@ impl Diagnostic for UnresolvedModule { | |||
29 | } | 40 | } |
30 | } | 41 | } |
31 | 42 | ||
43 | // Diagnostic: unresolved-extern-crate | ||
44 | // | ||
45 | // This diagnostic is triggered if rust-analyzer is unable to discover referred extern crate. | ||
32 | #[derive(Debug)] | 46 | #[derive(Debug)] |
33 | pub struct UnresolvedExternCrate { | 47 | pub struct UnresolvedExternCrate { |
34 | pub file: HirFileId, | 48 | pub file: HirFileId, |
@@ -50,6 +64,9 @@ impl Diagnostic for UnresolvedExternCrate { | |||
50 | } | 64 | } |
51 | } | 65 | } |
52 | 66 | ||
67 | // Diagnostic: unresolved-import | ||
68 | // | ||
69 | // This diagnostic is triggered if rust-analyzer is unable to discover imported module. | ||
53 | #[derive(Debug)] | 70 | #[derive(Debug)] |
54 | pub struct UnresolvedImport { | 71 | pub struct UnresolvedImport { |
55 | pub file: HirFileId, | 72 | pub file: HirFileId, |
@@ -77,3 +94,36 @@ impl Diagnostic for UnresolvedImport { | |||
77 | true | 94 | true |
78 | } | 95 | } |
79 | } | 96 | } |
97 | |||
98 | // Diagnostic: inactive-code | ||
99 | // | ||
100 | // This diagnostic is shown for code with inactive `#[cfg]` attributes. | ||
101 | #[derive(Debug, Clone, Eq, PartialEq)] | ||
102 | pub struct InactiveCode { | ||
103 | pub file: HirFileId, | ||
104 | pub node: SyntaxNodePtr, | ||
105 | pub cfg: CfgExpr, | ||
106 | pub opts: CfgOptions, | ||
107 | } | ||
108 | |||
109 | impl Diagnostic for InactiveCode { | ||
110 | fn code(&self) -> DiagnosticCode { | ||
111 | DiagnosticCode("inactive-code") | ||
112 | } | ||
113 | fn message(&self) -> String { | ||
114 | let inactive = DnfExpr::new(self.cfg.clone()).why_inactive(&self.opts); | ||
115 | let mut buf = "code is inactive due to #[cfg] directives".to_string(); | ||
116 | |||
117 | if let Some(inactive) = inactive { | ||
118 | format_to!(buf, ": {}", inactive); | ||
119 | } | ||
120 | |||
121 | buf | ||
122 | } | ||
123 | fn display_source(&self) -> InFile<SyntaxNodePtr> { | ||
124 | InFile::new(self.file, self.node.clone()) | ||
125 | } | ||
126 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
127 | self | ||
128 | } | ||
129 | } | ||
diff --git a/crates/hir_def/src/import_map.rs b/crates/hir_def/src/import_map.rs index 028cae2e7..1e24f29a8 100644 --- a/crates/hir_def/src/import_map.rs +++ b/crates/hir_def/src/import_map.rs | |||
@@ -356,7 +356,7 @@ mod tests { | |||
356 | let krate = crate_graph | 356 | let krate = crate_graph |
357 | .iter() | 357 | .iter() |
358 | .find(|krate| { | 358 | .find(|krate| { |
359 | crate_graph[*krate].declaration_name.as_ref().map(|n| n.to_string()) | 359 | crate_graph[*krate].display_name.as_ref().map(|n| n.to_string()) |
360 | == Some(crate_name.to_string()) | 360 | == Some(crate_name.to_string()) |
361 | }) | 361 | }) |
362 | .unwrap(); | 362 | .unwrap(); |
@@ -375,7 +375,7 @@ mod tests { | |||
375 | let path = map.path_of(item).unwrap(); | 375 | let path = map.path_of(item).unwrap(); |
376 | format!( | 376 | format!( |
377 | "{}::{} ({})\n", | 377 | "{}::{} ({})\n", |
378 | crate_graph[krate].declaration_name.as_ref().unwrap(), | 378 | crate_graph[krate].display_name.as_ref().unwrap(), |
379 | path, | 379 | path, |
380 | mark | 380 | mark |
381 | ) | 381 | ) |
@@ -416,7 +416,7 @@ mod tests { | |||
416 | .iter() | 416 | .iter() |
417 | .filter_map(|krate| { | 417 | .filter_map(|krate| { |
418 | let cdata = &crate_graph[krate]; | 418 | let cdata = &crate_graph[krate]; |
419 | let name = cdata.declaration_name.as_ref()?; | 419 | let name = cdata.display_name.as_ref()?; |
420 | 420 | ||
421 | let map = db.import_map(krate); | 421 | let map = db.import_map(krate); |
422 | 422 | ||
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs index 8a1121bbd..7eb388bae 100644 --- a/crates/hir_def/src/item_tree.rs +++ b/crates/hir_def/src/item_tree.rs | |||
@@ -672,6 +672,24 @@ impl ModItem { | |||
672 | pub fn downcast<N: ItemTreeNode>(self) -> Option<FileItemTreeId<N>> { | 672 | pub fn downcast<N: ItemTreeNode>(self) -> Option<FileItemTreeId<N>> { |
673 | N::id_from_mod_item(self) | 673 | N::id_from_mod_item(self) |
674 | } | 674 | } |
675 | |||
676 | pub fn ast_id(&self, tree: &ItemTree) -> FileAstId<ast::Item> { | ||
677 | match self { | ||
678 | ModItem::Import(it) => tree[it.index].ast_id().upcast(), | ||
679 | ModItem::ExternCrate(it) => tree[it.index].ast_id().upcast(), | ||
680 | ModItem::Function(it) => tree[it.index].ast_id().upcast(), | ||
681 | ModItem::Struct(it) => tree[it.index].ast_id().upcast(), | ||
682 | ModItem::Union(it) => tree[it.index].ast_id().upcast(), | ||
683 | ModItem::Enum(it) => tree[it.index].ast_id().upcast(), | ||
684 | ModItem::Const(it) => tree[it.index].ast_id().upcast(), | ||
685 | ModItem::Static(it) => tree[it.index].ast_id().upcast(), | ||
686 | ModItem::Trait(it) => tree[it.index].ast_id().upcast(), | ||
687 | ModItem::Impl(it) => tree[it.index].ast_id().upcast(), | ||
688 | ModItem::TypeAlias(it) => tree[it.index].ast_id().upcast(), | ||
689 | ModItem::Mod(it) => tree[it.index].ast_id().upcast(), | ||
690 | ModItem::MacroCall(it) => tree[it.index].ast_id().upcast(), | ||
691 | } | ||
692 | } | ||
675 | } | 693 | } |
676 | 694 | ||
677 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] | 695 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] |
diff --git a/crates/hir_def/src/item_tree/lower.rs b/crates/hir_def/src/item_tree/lower.rs index 3328639cf..ca7fb4a43 100644 --- a/crates/hir_def/src/item_tree/lower.rs +++ b/crates/hir_def/src/item_tree/lower.rs | |||
@@ -3,7 +3,7 @@ | |||
3 | use std::{collections::hash_map::Entry, mem, sync::Arc}; | 3 | use std::{collections::hash_map::Entry, mem, sync::Arc}; |
4 | 4 | ||
5 | use arena::map::ArenaMap; | 5 | use arena::map::ArenaMap; |
6 | use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, HirFileId}; | 6 | use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, name::known, HirFileId}; |
7 | use smallvec::SmallVec; | 7 | use smallvec::SmallVec; |
8 | use syntax::{ | 8 | use syntax::{ |
9 | ast::{self, ModuleItemOwner}, | 9 | ast::{self, ModuleItemOwner}, |
@@ -555,7 +555,8 @@ impl Ctx { | |||
555 | let id: ModItem = match item { | 555 | let id: ModItem = match item { |
556 | ast::ExternItem::Fn(ast) => { | 556 | ast::ExternItem::Fn(ast) => { |
557 | let func = self.lower_function(&ast)?; | 557 | let func = self.lower_function(&ast)?; |
558 | self.data().functions[func.index].is_unsafe = true; | 558 | self.data().functions[func.index].is_unsafe = |
559 | is_intrinsic_fn_unsafe(&self.data().functions[func.index].name); | ||
559 | func.into() | 560 | func.into() |
560 | } | 561 | } |
561 | ast::ExternItem::Static(ast) => { | 562 | ast::ExternItem::Static(ast) => { |
@@ -713,3 +714,45 @@ enum GenericsOwner<'a> { | |||
713 | TypeAlias, | 714 | TypeAlias, |
714 | Impl, | 715 | Impl, |
715 | } | 716 | } |
717 | |||
718 | /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise. | ||
719 | fn is_intrinsic_fn_unsafe(name: &Name) -> bool { | ||
720 | // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68 | ||
721 | ![ | ||
722 | known::abort, | ||
723 | known::min_align_of, | ||
724 | known::needs_drop, | ||
725 | known::caller_location, | ||
726 | known::size_of_val, | ||
727 | known::min_align_of_val, | ||
728 | known::add_with_overflow, | ||
729 | known::sub_with_overflow, | ||
730 | known::mul_with_overflow, | ||
731 | known::wrapping_add, | ||
732 | known::wrapping_sub, | ||
733 | known::wrapping_mul, | ||
734 | known::saturating_add, | ||
735 | known::saturating_sub, | ||
736 | known::rotate_left, | ||
737 | known::rotate_right, | ||
738 | known::ctpop, | ||
739 | known::ctlz, | ||
740 | known::cttz, | ||
741 | known::bswap, | ||
742 | known::bitreverse, | ||
743 | known::discriminant_value, | ||
744 | known::type_id, | ||
745 | known::likely, | ||
746 | known::unlikely, | ||
747 | known::ptr_guaranteed_eq, | ||
748 | known::ptr_guaranteed_ne, | ||
749 | known::minnumf32, | ||
750 | known::minnumf64, | ||
751 | known::maxnumf32, | ||
752 | known::rustc_peek, | ||
753 | known::maxnumf64, | ||
754 | known::type_name, | ||
755 | known::variant_count, | ||
756 | ] | ||
757 | .contains(&name) | ||
758 | } | ||
diff --git a/crates/hir_def/src/nameres.rs b/crates/hir_def/src/nameres.rs index 464ffef21..eb41d324e 100644 --- a/crates/hir_def/src/nameres.rs +++ b/crates/hir_def/src/nameres.rs | |||
@@ -172,11 +172,7 @@ pub struct ModuleData { | |||
172 | impl CrateDefMap { | 172 | impl CrateDefMap { |
173 | pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<CrateDefMap> { | 173 | pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<CrateDefMap> { |
174 | let _p = profile::span("crate_def_map_query").detail(|| { | 174 | let _p = profile::span("crate_def_map_query").detail(|| { |
175 | db.crate_graph()[krate] | 175 | db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string() |
176 | .declaration_name | ||
177 | .as_ref() | ||
178 | .map(ToString::to_string) | ||
179 | .unwrap_or_default() | ||
180 | }); | 176 | }); |
181 | let def_map = { | 177 | let def_map = { |
182 | let edition = db.crate_graph()[krate].edition; | 178 | let edition = db.crate_graph()[krate].edition; |
@@ -287,10 +283,11 @@ pub enum ModuleSource { | |||
287 | } | 283 | } |
288 | 284 | ||
289 | mod diagnostics { | 285 | mod diagnostics { |
286 | use cfg::{CfgExpr, CfgOptions}; | ||
290 | use hir_expand::diagnostics::DiagnosticSink; | 287 | use hir_expand::diagnostics::DiagnosticSink; |
291 | use hir_expand::hygiene::Hygiene; | 288 | use hir_expand::hygiene::Hygiene; |
292 | use hir_expand::InFile; | 289 | use hir_expand::InFile; |
293 | use syntax::{ast, AstPtr}; | 290 | use syntax::{ast, AstPtr, SyntaxNodePtr}; |
294 | 291 | ||
295 | use crate::path::ModPath; | 292 | use crate::path::ModPath; |
296 | use crate::{db::DefDatabase, diagnostics::*, nameres::LocalModuleId, AstId}; | 293 | use crate::{db::DefDatabase, diagnostics::*, nameres::LocalModuleId, AstId}; |
@@ -302,6 +299,8 @@ mod diagnostics { | |||
302 | UnresolvedExternCrate { ast: AstId<ast::ExternCrate> }, | 299 | UnresolvedExternCrate { ast: AstId<ast::ExternCrate> }, |
303 | 300 | ||
304 | UnresolvedImport { ast: AstId<ast::Use>, index: usize }, | 301 | UnresolvedImport { ast: AstId<ast::Use>, index: usize }, |
302 | |||
303 | UnconfiguredCode { ast: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions }, | ||
305 | } | 304 | } |
306 | 305 | ||
307 | #[derive(Debug, PartialEq, Eq)] | 306 | #[derive(Debug, PartialEq, Eq)] |
@@ -340,6 +339,15 @@ mod diagnostics { | |||
340 | Self { in_module: container, kind: DiagnosticKind::UnresolvedImport { ast, index } } | 339 | Self { in_module: container, kind: DiagnosticKind::UnresolvedImport { ast, index } } |
341 | } | 340 | } |
342 | 341 | ||
342 | pub(super) fn unconfigured_code( | ||
343 | container: LocalModuleId, | ||
344 | ast: InFile<SyntaxNodePtr>, | ||
345 | cfg: CfgExpr, | ||
346 | opts: CfgOptions, | ||
347 | ) -> Self { | ||
348 | Self { in_module: container, kind: DiagnosticKind::UnconfiguredCode { ast, cfg, opts } } | ||
349 | } | ||
350 | |||
343 | pub(super) fn add_to( | 351 | pub(super) fn add_to( |
344 | &self, | 352 | &self, |
345 | db: &dyn DefDatabase, | 353 | db: &dyn DefDatabase, |
@@ -389,6 +397,15 @@ mod diagnostics { | |||
389 | sink.push(UnresolvedImport { file: ast.file_id, node: AstPtr::new(&tree) }); | 397 | sink.push(UnresolvedImport { file: ast.file_id, node: AstPtr::new(&tree) }); |
390 | } | 398 | } |
391 | } | 399 | } |
400 | |||
401 | DiagnosticKind::UnconfiguredCode { ast, cfg, opts } => { | ||
402 | sink.push(InactiveCode { | ||
403 | file: ast.file_id, | ||
404 | node: ast.value.clone(), | ||
405 | cfg: cfg.clone(), | ||
406 | opts: opts.clone(), | ||
407 | }); | ||
408 | } | ||
392 | } | 409 | } |
393 | } | 410 | } |
394 | } | 411 | } |
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs index c8cd04264..1ff45d244 100644 --- a/crates/hir_def/src/nameres/collector.rs +++ b/crates/hir_def/src/nameres/collector.rs | |||
@@ -6,7 +6,7 @@ | |||
6 | use std::iter; | 6 | use std::iter; |
7 | 7 | ||
8 | use base_db::{CrateId, FileId, ProcMacroId}; | 8 | use base_db::{CrateId, FileId, ProcMacroId}; |
9 | use cfg::CfgOptions; | 9 | use cfg::{CfgExpr, CfgOptions}; |
10 | use hir_expand::InFile; | 10 | use hir_expand::InFile; |
11 | use hir_expand::{ | 11 | use hir_expand::{ |
12 | ast_id_map::FileAstId, | 12 | ast_id_map::FileAstId, |
@@ -218,15 +218,18 @@ impl DefCollector<'_> { | |||
218 | let item_tree = self.db.item_tree(file_id.into()); | 218 | let item_tree = self.db.item_tree(file_id.into()); |
219 | let module_id = self.def_map.root; | 219 | let module_id = self.def_map.root; |
220 | self.def_map.modules[module_id].origin = ModuleOrigin::CrateRoot { definition: file_id }; | 220 | self.def_map.modules[module_id].origin = ModuleOrigin::CrateRoot { definition: file_id }; |
221 | ModCollector { | 221 | let mut root_collector = ModCollector { |
222 | def_collector: &mut *self, | 222 | def_collector: &mut *self, |
223 | macro_depth: 0, | 223 | macro_depth: 0, |
224 | module_id, | 224 | module_id, |
225 | file_id: file_id.into(), | 225 | file_id: file_id.into(), |
226 | item_tree: &item_tree, | 226 | item_tree: &item_tree, |
227 | mod_dir: ModDir::root(), | 227 | mod_dir: ModDir::root(), |
228 | }; | ||
229 | if item_tree.top_level_attrs().cfg().map_or(true, |cfg| root_collector.is_cfg_enabled(&cfg)) | ||
230 | { | ||
231 | root_collector.collect(item_tree.top_level_items()); | ||
228 | } | 232 | } |
229 | .collect(item_tree.top_level_items()); | ||
230 | 233 | ||
231 | // main name resolution fixed-point loop. | 234 | // main name resolution fixed-point loop. |
232 | let mut i = 0; | 235 | let mut i = 0; |
@@ -900,7 +903,8 @@ impl ModCollector<'_, '_> { | |||
900 | // `#[macro_use] extern crate` is hoisted to imports macros before collecting | 903 | // `#[macro_use] extern crate` is hoisted to imports macros before collecting |
901 | // any other items. | 904 | // any other items. |
902 | for item in items { | 905 | for item in items { |
903 | if self.is_cfg_enabled(self.item_tree.attrs((*item).into())) { | 906 | let attrs = self.item_tree.attrs((*item).into()); |
907 | if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) { | ||
904 | if let ModItem::ExternCrate(id) = item { | 908 | if let ModItem::ExternCrate(id) = item { |
905 | let import = self.item_tree[*id].clone(); | 909 | let import = self.item_tree[*id].clone(); |
906 | if import.is_macro_use { | 910 | if import.is_macro_use { |
@@ -912,8 +916,11 @@ impl ModCollector<'_, '_> { | |||
912 | 916 | ||
913 | for &item in items { | 917 | for &item in items { |
914 | let attrs = self.item_tree.attrs(item.into()); | 918 | let attrs = self.item_tree.attrs(item.into()); |
915 | if !self.is_cfg_enabled(attrs) { | 919 | if let Some(cfg) = attrs.cfg() { |
916 | continue; | 920 | if !self.is_cfg_enabled(&cfg) { |
921 | self.emit_unconfigured_diagnostic(item, &cfg); | ||
922 | continue; | ||
923 | } | ||
917 | } | 924 | } |
918 | let module = | 925 | let module = |
919 | ModuleId { krate: self.def_collector.def_map.krate, local_id: self.module_id }; | 926 | ModuleId { krate: self.def_collector.def_map.krate, local_id: self.module_id }; |
@@ -1320,8 +1327,22 @@ impl ModCollector<'_, '_> { | |||
1320 | } | 1327 | } |
1321 | } | 1328 | } |
1322 | 1329 | ||
1323 | fn is_cfg_enabled(&self, attrs: &Attrs) -> bool { | 1330 | fn is_cfg_enabled(&self, cfg: &CfgExpr) -> bool { |
1324 | attrs.is_cfg_enabled(self.def_collector.cfg_options) | 1331 | self.def_collector.cfg_options.check(cfg) != Some(false) |
1332 | } | ||
1333 | |||
1334 | fn emit_unconfigured_diagnostic(&mut self, item: ModItem, cfg: &CfgExpr) { | ||
1335 | let ast_id = item.ast_id(self.item_tree); | ||
1336 | let id_map = self.def_collector.db.ast_id_map(self.file_id); | ||
1337 | let syntax_ptr = id_map.get(ast_id).syntax_node_ptr(); | ||
1338 | |||
1339 | let ast_node = InFile::new(self.file_id, syntax_ptr); | ||
1340 | self.def_collector.def_map.diagnostics.push(DefDiagnostic::unconfigured_code( | ||
1341 | self.module_id, | ||
1342 | ast_node, | ||
1343 | cfg.clone(), | ||
1344 | self.def_collector.cfg_options.clone(), | ||
1345 | )); | ||
1325 | } | 1346 | } |
1326 | } | 1347 | } |
1327 | 1348 | ||
diff --git a/crates/hir_def/src/nameres/tests.rs b/crates/hir_def/src/nameres/tests.rs index 11d84f808..9c19bf572 100644 --- a/crates/hir_def/src/nameres/tests.rs +++ b/crates/hir_def/src/nameres/tests.rs | |||
@@ -691,3 +691,20 @@ mod tr { | |||
691 | "#]], | 691 | "#]], |
692 | ); | 692 | ); |
693 | } | 693 | } |
694 | |||
695 | #[test] | ||
696 | fn cfg_the_entire_crate() { | ||
697 | check( | ||
698 | r#" | ||
699 | //- /main.rs | ||
700 | #![cfg(never)] | ||
701 | |||
702 | pub struct S; | ||
703 | pub enum E {} | ||
704 | pub fn f() {} | ||
705 | "#, | ||
706 | expect![[r#" | ||
707 | crate | ||
708 | "#]], | ||
709 | ); | ||
710 | } | ||
diff --git a/crates/hir_def/src/nameres/tests/diagnostics.rs b/crates/hir_def/src/nameres/tests/diagnostics.rs index 576b813d2..1a7b98831 100644 --- a/crates/hir_def/src/nameres/tests/diagnostics.rs +++ b/crates/hir_def/src/nameres/tests/diagnostics.rs | |||
@@ -1,42 +1,10 @@ | |||
1 | use base_db::fixture::WithFixture; | 1 | use base_db::fixture::WithFixture; |
2 | use base_db::FileId; | ||
3 | use base_db::SourceDatabaseExt; | ||
4 | use hir_expand::db::AstDatabase; | ||
5 | use rustc_hash::FxHashMap; | ||
6 | use syntax::TextRange; | ||
7 | use syntax::TextSize; | ||
8 | 2 | ||
9 | use crate::test_db::TestDB; | 3 | use crate::test_db::TestDB; |
10 | 4 | ||
11 | fn check_diagnostics(ra_fixture: &str) { | 5 | fn check_diagnostics(ra_fixture: &str) { |
12 | let db: TestDB = TestDB::with_files(ra_fixture); | 6 | let db: TestDB = TestDB::with_files(ra_fixture); |
13 | let annotations = db.extract_annotations(); | 7 | db.check_diagnostics(); |
14 | assert!(!annotations.is_empty()); | ||
15 | |||
16 | let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default(); | ||
17 | db.diagnostics(|d| { | ||
18 | let src = d.display_source(); | ||
19 | let root = db.parse_or_expand(src.file_id).unwrap(); | ||
20 | // FIXME: macros... | ||
21 | let file_id = src.file_id.original_file(&db); | ||
22 | let range = src.value.to_node(&root).text_range(); | ||
23 | let message = d.message().to_owned(); | ||
24 | actual.entry(file_id).or_default().push((range, message)); | ||
25 | }); | ||
26 | |||
27 | for (file_id, diags) in actual.iter_mut() { | ||
28 | diags.sort_by_key(|it| it.0.start()); | ||
29 | let text = db.file_text(*file_id); | ||
30 | // For multiline spans, place them on line start | ||
31 | for (range, content) in diags { | ||
32 | if text[*range].contains('\n') { | ||
33 | *range = TextRange::new(range.start(), range.start() + TextSize::from(1)); | ||
34 | *content = format!("... {}", content); | ||
35 | } | ||
36 | } | ||
37 | } | ||
38 | |||
39 | assert_eq!(annotations, actual); | ||
40 | } | 8 | } |
41 | 9 | ||
42 | #[test] | 10 | #[test] |
@@ -129,3 +97,25 @@ fn unresolved_module() { | |||
129 | ", | 97 | ", |
130 | ); | 98 | ); |
131 | } | 99 | } |
100 | |||
101 | #[test] | ||
102 | fn inactive_item() { | ||
103 | // Additional tests in `cfg` crate. This only tests disabled cfgs. | ||
104 | |||
105 | check_diagnostics( | ||
106 | r#" | ||
107 | //- /lib.rs | ||
108 | #[cfg(no)] pub fn f() {} | ||
109 | //^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no is disabled | ||
110 | |||
111 | #[cfg(no)] #[cfg(no2)] mod m; | ||
112 | //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no and no2 are disabled | ||
113 | |||
114 | #[cfg(all(not(a), b))] enum E {} | ||
115 | //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: b is disabled | ||
116 | |||
117 | #[cfg(feature = "std")] use std; | ||
118 | //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: feature = "std" is disabled | ||
119 | "#, | ||
120 | ); | ||
121 | } | ||
diff --git a/crates/hir_def/src/test_db.rs b/crates/hir_def/src/test_db.rs index fb1d3c974..2b36c824a 100644 --- a/crates/hir_def/src/test_db.rs +++ b/crates/hir_def/src/test_db.rs | |||
@@ -12,10 +12,10 @@ use hir_expand::diagnostics::Diagnostic; | |||
12 | use hir_expand::diagnostics::DiagnosticSinkBuilder; | 12 | use hir_expand::diagnostics::DiagnosticSinkBuilder; |
13 | use rustc_hash::FxHashMap; | 13 | use rustc_hash::FxHashMap; |
14 | use rustc_hash::FxHashSet; | 14 | use rustc_hash::FxHashSet; |
15 | use syntax::TextRange; | 15 | use syntax::{TextRange, TextSize}; |
16 | use test_utils::extract_annotations; | 16 | use test_utils::extract_annotations; |
17 | 17 | ||
18 | use crate::db::DefDatabase; | 18 | use crate::{db::DefDatabase, ModuleDefId}; |
19 | 19 | ||
20 | #[salsa::database( | 20 | #[salsa::database( |
21 | base_db::SourceDatabaseExtStorage, | 21 | base_db::SourceDatabaseExtStorage, |
@@ -135,9 +135,47 @@ impl TestDB { | |||
135 | let crate_def_map = self.crate_def_map(krate); | 135 | let crate_def_map = self.crate_def_map(krate); |
136 | 136 | ||
137 | let mut sink = DiagnosticSinkBuilder::new().build(&mut cb); | 137 | let mut sink = DiagnosticSinkBuilder::new().build(&mut cb); |
138 | for (module_id, _) in crate_def_map.modules.iter() { | 138 | for (module_id, module) in crate_def_map.modules.iter() { |
139 | crate_def_map.add_diagnostics(self, module_id, &mut sink); | 139 | crate_def_map.add_diagnostics(self, module_id, &mut sink); |
140 | |||
141 | for decl in module.scope.declarations() { | ||
142 | if let ModuleDefId::FunctionId(it) = decl { | ||
143 | let source_map = self.body_with_source_map(it.into()).1; | ||
144 | source_map.add_diagnostics(self, &mut sink); | ||
145 | } | ||
146 | } | ||
140 | } | 147 | } |
141 | } | 148 | } |
142 | } | 149 | } |
150 | |||
151 | pub fn check_diagnostics(&self) { | ||
152 | let db: &TestDB = self; | ||
153 | let annotations = db.extract_annotations(); | ||
154 | assert!(!annotations.is_empty()); | ||
155 | |||
156 | let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default(); | ||
157 | db.diagnostics(|d| { | ||
158 | let src = d.display_source(); | ||
159 | let root = db.parse_or_expand(src.file_id).unwrap(); | ||
160 | // FIXME: macros... | ||
161 | let file_id = src.file_id.original_file(db); | ||
162 | let range = src.value.to_node(&root).text_range(); | ||
163 | let message = d.message().to_owned(); | ||
164 | actual.entry(file_id).or_default().push((range, message)); | ||
165 | }); | ||
166 | |||
167 | for (file_id, diags) in actual.iter_mut() { | ||
168 | diags.sort_by_key(|it| it.0.start()); | ||
169 | let text = db.file_text(*file_id); | ||
170 | // For multiline spans, place them on line start | ||
171 | for (range, content) in diags { | ||
172 | if text[*range].contains('\n') { | ||
173 | *range = TextRange::new(range.start(), range.start() + TextSize::from(1)); | ||
174 | *content = format!("... {}", content); | ||
175 | } | ||
176 | } | ||
177 | } | ||
178 | |||
179 | assert_eq!(annotations, actual); | ||
180 | } | ||
143 | } | 181 | } |
diff --git a/crates/hir_expand/src/db.rs b/crates/hir_expand/src/db.rs index b591130ca..ade57ac1b 100644 --- a/crates/hir_expand/src/db.rs +++ b/crates/hir_expand/src/db.rs | |||
@@ -389,6 +389,7 @@ fn to_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind { | |||
389 | CALL_EXPR => FragmentKind::Expr, | 389 | CALL_EXPR => FragmentKind::Expr, |
390 | INDEX_EXPR => FragmentKind::Expr, | 390 | INDEX_EXPR => FragmentKind::Expr, |
391 | METHOD_CALL_EXPR => FragmentKind::Expr, | 391 | METHOD_CALL_EXPR => FragmentKind::Expr, |
392 | FIELD_EXPR => FragmentKind::Expr, | ||
392 | AWAIT_EXPR => FragmentKind::Expr, | 393 | AWAIT_EXPR => FragmentKind::Expr, |
393 | CAST_EXPR => FragmentKind::Expr, | 394 | CAST_EXPR => FragmentKind::Expr, |
394 | REF_EXPR => FragmentKind::Expr, | 395 | REF_EXPR => FragmentKind::Expr, |
diff --git a/crates/hir_expand/src/name.rs b/crates/hir_expand/src/name.rs index 63f828707..b26ffa1ef 100644 --- a/crates/hir_expand/src/name.rs +++ b/crates/hir_expand/src/name.rs | |||
@@ -208,6 +208,42 @@ pub mod known { | |||
208 | PartialOrd, | 208 | PartialOrd, |
209 | Eq, | 209 | Eq, |
210 | PartialEq, | 210 | PartialEq, |
211 | // Safe intrinsics | ||
212 | abort, | ||
213 | size_of, | ||
214 | min_align_of, | ||
215 | needs_drop, | ||
216 | caller_location, | ||
217 | size_of_val, | ||
218 | min_align_of_val, | ||
219 | add_with_overflow, | ||
220 | sub_with_overflow, | ||
221 | mul_with_overflow, | ||
222 | wrapping_add, | ||
223 | wrapping_sub, | ||
224 | wrapping_mul, | ||
225 | saturating_add, | ||
226 | saturating_sub, | ||
227 | rotate_left, | ||
228 | rotate_right, | ||
229 | ctpop, | ||
230 | ctlz, | ||
231 | cttz, | ||
232 | bswap, | ||
233 | bitreverse, | ||
234 | discriminant_value, | ||
235 | type_id, | ||
236 | likely, | ||
237 | unlikely, | ||
238 | ptr_guaranteed_eq, | ||
239 | ptr_guaranteed_ne, | ||
240 | minnumf32, | ||
241 | minnumf64, | ||
242 | maxnumf32, | ||
243 | rustc_peek, | ||
244 | maxnumf64, | ||
245 | type_name, | ||
246 | variant_count, | ||
211 | ); | 247 | ); |
212 | 248 | ||
213 | // self/Self cannot be used as an identifier | 249 | // self/Self cannot be used as an identifier |
diff --git a/crates/hir_ty/Cargo.toml b/crates/hir_ty/Cargo.toml index e9c62c6aa..367a1b98d 100644 --- a/crates/hir_ty/Cargo.toml +++ b/crates/hir_ty/Cargo.toml | |||
@@ -17,9 +17,9 @@ ena = "0.14.0" | |||
17 | log = "0.4.8" | 17 | log = "0.4.8" |
18 | rustc-hash = "1.1.0" | 18 | rustc-hash = "1.1.0" |
19 | scoped-tls = "1" | 19 | scoped-tls = "1" |
20 | chalk-solve = "0.33" | 20 | chalk-solve = { version = "0.34", default-features = false } |
21 | chalk-ir = "0.33" | 21 | chalk-ir = "0.34" |
22 | chalk-recursive = "0.33" | 22 | chalk-recursive = "0.34" |
23 | 23 | ||
24 | stdx = { path = "../stdx", version = "0.0.0" } | 24 | stdx = { path = "../stdx", version = "0.0.0" } |
25 | hir_def = { path = "../hir_def", version = "0.0.0" } | 25 | hir_def = { path = "../hir_def", version = "0.0.0" } |
diff --git a/crates/hir_ty/src/diagnostics.rs b/crates/hir_ty/src/diagnostics.rs index dfe98571e..b58fe0ed7 100644 --- a/crates/hir_ty/src/diagnostics.rs +++ b/crates/hir_ty/src/diagnostics.rs | |||
@@ -36,6 +36,9 @@ pub fn validate_body(db: &dyn HirDatabase, owner: DefWithBodyId, sink: &mut Diag | |||
36 | validator.validate_body(db); | 36 | validator.validate_body(db); |
37 | } | 37 | } |
38 | 38 | ||
39 | // Diagnostic: no-such-field | ||
40 | // | ||
41 | // This diagnostic is triggered if created structure does not have field provided in record. | ||
39 | #[derive(Debug)] | 42 | #[derive(Debug)] |
40 | pub struct NoSuchField { | 43 | pub struct NoSuchField { |
41 | pub file: HirFileId, | 44 | pub file: HirFileId, |
@@ -60,6 +63,17 @@ impl Diagnostic for NoSuchField { | |||
60 | } | 63 | } |
61 | } | 64 | } |
62 | 65 | ||
66 | // Diagnostic: missing-structure-fields | ||
67 | // | ||
68 | // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure. | ||
69 | // | ||
70 | // Example: | ||
71 | // | ||
72 | // ```rust | ||
73 | // struct A { a: u8, b: u8 } | ||
74 | // | ||
75 | // let a = A { a: 10 }; | ||
76 | // ``` | ||
63 | #[derive(Debug)] | 77 | #[derive(Debug)] |
64 | pub struct MissingFields { | 78 | pub struct MissingFields { |
65 | pub file: HirFileId, | 79 | pub file: HirFileId, |
@@ -96,6 +110,21 @@ impl Diagnostic for MissingFields { | |||
96 | } | 110 | } |
97 | } | 111 | } |
98 | 112 | ||
113 | // Diagnostic: missing-pat-fields | ||
114 | // | ||
115 | // This diagnostic is triggered if pattern lacks some fields that exist in the corresponding structure. | ||
116 | // | ||
117 | // Example: | ||
118 | // | ||
119 | // ```rust | ||
120 | // struct A { a: u8, b: u8 } | ||
121 | // | ||
122 | // let a = A { a: 10, b: 20 }; | ||
123 | // | ||
124 | // if let A { a } = a { | ||
125 | // // ... | ||
126 | // } | ||
127 | // ``` | ||
99 | #[derive(Debug)] | 128 | #[derive(Debug)] |
100 | pub struct MissingPatFields { | 129 | pub struct MissingPatFields { |
101 | pub file: HirFileId, | 130 | pub file: HirFileId, |
@@ -130,6 +159,9 @@ impl Diagnostic for MissingPatFields { | |||
130 | } | 159 | } |
131 | } | 160 | } |
132 | 161 | ||
162 | // Diagnostic: missing-match-arm | ||
163 | // | ||
164 | // This diagnostic is triggered if `match` block is missing one or more match arms. | ||
133 | #[derive(Debug)] | 165 | #[derive(Debug)] |
134 | pub struct MissingMatchArms { | 166 | pub struct MissingMatchArms { |
135 | pub file: HirFileId, | 167 | pub file: HirFileId, |
@@ -152,6 +184,17 @@ impl Diagnostic for MissingMatchArms { | |||
152 | } | 184 | } |
153 | } | 185 | } |
154 | 186 | ||
187 | // Diagnostic: missing-ok-in-tail-expr | ||
188 | // | ||
189 | // This diagnostic is triggered if block that should return `Result` returns a value not wrapped in `Ok`. | ||
190 | // | ||
191 | // Example: | ||
192 | // | ||
193 | // ```rust | ||
194 | // fn foo() -> Result<u8, ()> { | ||
195 | // 10 | ||
196 | // } | ||
197 | // ``` | ||
155 | #[derive(Debug)] | 198 | #[derive(Debug)] |
156 | pub struct MissingOkInTailExpr { | 199 | pub struct MissingOkInTailExpr { |
157 | pub file: HirFileId, | 200 | pub file: HirFileId, |
@@ -173,6 +216,9 @@ impl Diagnostic for MissingOkInTailExpr { | |||
173 | } | 216 | } |
174 | } | 217 | } |
175 | 218 | ||
219 | // Diagnostic: break-outside-of-loop | ||
220 | // | ||
221 | // This diagnostic is triggered if `break` keyword is used outside of a loop. | ||
176 | #[derive(Debug)] | 222 | #[derive(Debug)] |
177 | pub struct BreakOutsideOfLoop { | 223 | pub struct BreakOutsideOfLoop { |
178 | pub file: HirFileId, | 224 | pub file: HirFileId, |
@@ -194,6 +240,9 @@ impl Diagnostic for BreakOutsideOfLoop { | |||
194 | } | 240 | } |
195 | } | 241 | } |
196 | 242 | ||
243 | // Diagnostic: missing-unsafe | ||
244 | // | ||
245 | // This diagnostic is triggered if operation marked as `unsafe` is used outside of `unsafe` function or block. | ||
197 | #[derive(Debug)] | 246 | #[derive(Debug)] |
198 | pub struct MissingUnsafe { | 247 | pub struct MissingUnsafe { |
199 | pub file: HirFileId, | 248 | pub file: HirFileId, |
@@ -215,6 +264,9 @@ impl Diagnostic for MissingUnsafe { | |||
215 | } | 264 | } |
216 | } | 265 | } |
217 | 266 | ||
267 | // Diagnostic: mismatched-arg-count | ||
268 | // | ||
269 | // This diagnostic is triggered if function is invoked with an incorrect amount of arguments. | ||
218 | #[derive(Debug)] | 270 | #[derive(Debug)] |
219 | pub struct MismatchedArgCount { | 271 | pub struct MismatchedArgCount { |
220 | pub file: HirFileId, | 272 | pub file: HirFileId, |
@@ -264,6 +316,9 @@ impl fmt::Display for CaseType { | |||
264 | } | 316 | } |
265 | } | 317 | } |
266 | 318 | ||
319 | // Diagnostic: incorrect-ident-case | ||
320 | // | ||
321 | // This diagnostic is triggered if item name doesn't follow https://doc.rust-lang.org/1.0.0/style/style/naming/README.html[Rust naming convention]. | ||
267 | #[derive(Debug)] | 322 | #[derive(Debug)] |
268 | pub struct IncorrectCase { | 323 | pub struct IncorrectCase { |
269 | pub file: HirFileId, | 324 | pub file: HirFileId, |
diff --git a/crates/hir_ty/src/diagnostics/decl_check.rs b/crates/hir_ty/src/diagnostics/decl_check.rs index f987636fe..f179c62b7 100644 --- a/crates/hir_ty/src/diagnostics/decl_check.rs +++ b/crates/hir_ty/src/diagnostics/decl_check.rs | |||
@@ -708,11 +708,23 @@ fn foo() { | |||
708 | } | 708 | } |
709 | 709 | ||
710 | #[test] | 710 | #[test] |
711 | fn incorrect_struct_name() { | 711 | fn incorrect_struct_names() { |
712 | check_diagnostics( | 712 | check_diagnostics( |
713 | r#" | 713 | r#" |
714 | struct non_camel_case_name {} | 714 | struct non_camel_case_name {} |
715 | // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName` | 715 | // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName` |
716 | |||
717 | struct SCREAMING_CASE {} | ||
718 | // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase` | ||
719 | "#, | ||
720 | ); | ||
721 | } | ||
722 | |||
723 | #[test] | ||
724 | fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() { | ||
725 | check_diagnostics( | ||
726 | r#" | ||
727 | struct AABB {} | ||
716 | "#, | 728 | "#, |
717 | ); | 729 | ); |
718 | } | 730 | } |
@@ -728,11 +740,23 @@ struct SomeStruct { SomeField: u8 } | |||
728 | } | 740 | } |
729 | 741 | ||
730 | #[test] | 742 | #[test] |
731 | fn incorrect_enum_name() { | 743 | fn incorrect_enum_names() { |
732 | check_diagnostics( | 744 | check_diagnostics( |
733 | r#" | 745 | r#" |
734 | enum some_enum { Val(u8) } | 746 | enum some_enum { Val(u8) } |
735 | // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum` | 747 | // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum` |
748 | |||
749 | enum SOME_ENUM | ||
750 | // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum` | ||
751 | "#, | ||
752 | ); | ||
753 | } | ||
754 | |||
755 | #[test] | ||
756 | fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() { | ||
757 | check_diagnostics( | ||
758 | r#" | ||
759 | enum AABB {} | ||
736 | "#, | 760 | "#, |
737 | ); | 761 | ); |
738 | } | 762 | } |
diff --git a/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs b/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs index 3800f2a6b..b0144a289 100644 --- a/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs +++ b/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs | |||
@@ -1,150 +1,145 @@ | |||
1 | //! Functions for string case manipulation, such as detecting the identifier case, | 1 | //! Functions for string case manipulation, such as detecting the identifier case, |
2 | //! and converting it into appropriate form. | 2 | //! and converting it into appropriate form. |
3 | 3 | ||
4 | #[derive(Debug)] | 4 | // Code that was taken from rustc was taken at commit 89fdb30, |
5 | enum DetectedCase { | 5 | // from file /compiler/rustc_lint/src/nonstandard_style.rs |
6 | LowerCamelCase, | ||
7 | UpperCamelCase, | ||
8 | LowerSnakeCase, | ||
9 | UpperSnakeCase, | ||
10 | Unknown, | ||
11 | } | ||
12 | |||
13 | fn detect_case(ident: &str) -> DetectedCase { | ||
14 | let trimmed_ident = ident.trim_matches('_'); | ||
15 | let first_lowercase = trimmed_ident.starts_with(|chr: char| chr.is_ascii_lowercase()); | ||
16 | let mut has_lowercase = first_lowercase; | ||
17 | let mut has_uppercase = false; | ||
18 | let mut has_underscore = false; | ||
19 | |||
20 | for chr in trimmed_ident.chars() { | ||
21 | if chr == '_' { | ||
22 | has_underscore = true; | ||
23 | } else if chr.is_ascii_uppercase() { | ||
24 | has_uppercase = true; | ||
25 | } else if chr.is_ascii_lowercase() { | ||
26 | has_lowercase = true; | ||
27 | } | ||
28 | } | ||
29 | |||
30 | if has_uppercase { | ||
31 | if !has_lowercase { | ||
32 | DetectedCase::UpperSnakeCase | ||
33 | } else if !has_underscore { | ||
34 | if first_lowercase { | ||
35 | DetectedCase::LowerCamelCase | ||
36 | } else { | ||
37 | DetectedCase::UpperCamelCase | ||
38 | } | ||
39 | } else { | ||
40 | // It has uppercase, it has lowercase, it has underscore. | ||
41 | // No assumptions here | ||
42 | DetectedCase::Unknown | ||
43 | } | ||
44 | } else { | ||
45 | DetectedCase::LowerSnakeCase | ||
46 | } | ||
47 | } | ||
48 | 6 | ||
49 | /// Converts an identifier to an UpperCamelCase form. | 7 | /// Converts an identifier to an UpperCamelCase form. |
50 | /// Returns `None` if the string is already is UpperCamelCase. | 8 | /// Returns `None` if the string is already is UpperCamelCase. |
51 | pub fn to_camel_case(ident: &str) -> Option<String> { | 9 | pub fn to_camel_case(ident: &str) -> Option<String> { |
52 | let detected_case = detect_case(ident); | 10 | if is_camel_case(ident) { |
53 | 11 | return None; | |
54 | match detected_case { | ||
55 | DetectedCase::UpperCamelCase => return None, | ||
56 | DetectedCase::LowerCamelCase => { | ||
57 | let mut first_capitalized = false; | ||
58 | let output = ident | ||
59 | .chars() | ||
60 | .map(|chr| { | ||
61 | if !first_capitalized && chr.is_ascii_lowercase() { | ||
62 | first_capitalized = true; | ||
63 | chr.to_ascii_uppercase() | ||
64 | } else { | ||
65 | chr | ||
66 | } | ||
67 | }) | ||
68 | .collect(); | ||
69 | return Some(output); | ||
70 | } | ||
71 | _ => {} | ||
72 | } | 12 | } |
73 | 13 | ||
74 | let mut output = String::with_capacity(ident.len()); | 14 | // Taken from rustc. |
75 | 15 | let ret = ident | |
76 | let mut capital_added = false; | 16 | .trim_matches('_') |
77 | for chr in ident.chars() { | 17 | .split('_') |
78 | if chr.is_alphabetic() { | 18 | .filter(|component| !component.is_empty()) |
79 | if !capital_added { | 19 | .map(|component| { |
80 | output.push(chr.to_ascii_uppercase()); | 20 | let mut camel_cased_component = String::new(); |
81 | capital_added = true; | 21 | |
82 | } else { | 22 | let mut new_word = true; |
83 | output.push(chr.to_ascii_lowercase()); | 23 | let mut prev_is_lower_case = true; |
24 | |||
25 | for c in component.chars() { | ||
26 | // Preserve the case if an uppercase letter follows a lowercase letter, so that | ||
27 | // `camelCase` is converted to `CamelCase`. | ||
28 | if prev_is_lower_case && c.is_uppercase() { | ||
29 | new_word = true; | ||
30 | } | ||
31 | |||
32 | if new_word { | ||
33 | camel_cased_component.push_str(&c.to_uppercase().to_string()); | ||
34 | } else { | ||
35 | camel_cased_component.push_str(&c.to_lowercase().to_string()); | ||
36 | } | ||
37 | |||
38 | prev_is_lower_case = c.is_lowercase(); | ||
39 | new_word = false; | ||
84 | } | 40 | } |
85 | } else if chr == '_' { | ||
86 | // Skip this character and make the next one capital. | ||
87 | capital_added = false; | ||
88 | } else { | ||
89 | // Put the characted as-is. | ||
90 | output.push(chr); | ||
91 | } | ||
92 | } | ||
93 | 41 | ||
94 | if output == ident { | 42 | camel_cased_component |
95 | // While we didn't detect the correct case at the beginning, there | 43 | }) |
96 | // may be special cases: e.g. `A` is both valid CamelCase and UPPER_SNAKE_CASE. | 44 | .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| { |
97 | None | 45 | // separate two components with an underscore if their boundary cannot |
98 | } else { | 46 | // be distinguished using a uppercase/lowercase case distinction |
99 | Some(output) | 47 | let join = if let Some(prev) = prev { |
100 | } | 48 | let l = prev.chars().last().unwrap(); |
49 | let f = next.chars().next().unwrap(); | ||
50 | !char_has_case(l) && !char_has_case(f) | ||
51 | } else { | ||
52 | false | ||
53 | }; | ||
54 | (acc + if join { "_" } else { "" } + &next, Some(next)) | ||
55 | }) | ||
56 | .0; | ||
57 | Some(ret) | ||
101 | } | 58 | } |
102 | 59 | ||
103 | /// Converts an identifier to a lower_snake_case form. | 60 | /// Converts an identifier to a lower_snake_case form. |
104 | /// Returns `None` if the string is already in lower_snake_case. | 61 | /// Returns `None` if the string is already in lower_snake_case. |
105 | pub fn to_lower_snake_case(ident: &str) -> Option<String> { | 62 | pub fn to_lower_snake_case(ident: &str) -> Option<String> { |
106 | // First, assume that it's UPPER_SNAKE_CASE. | 63 | if is_lower_snake_case(ident) { |
107 | match detect_case(ident) { | 64 | return None; |
108 | DetectedCase::LowerSnakeCase => return None, | 65 | } else if is_upper_snake_case(ident) { |
109 | DetectedCase::UpperSnakeCase => { | 66 | return Some(ident.to_lowercase()); |
110 | return Some(ident.chars().map(|chr| chr.to_ascii_lowercase()).collect()) | ||
111 | } | ||
112 | _ => {} | ||
113 | } | 67 | } |
114 | 68 | ||
115 | // Otherwise, assume that it's CamelCase. | 69 | Some(stdx::to_lower_snake_case(ident)) |
116 | let lower_snake_case = stdx::to_lower_snake_case(ident); | ||
117 | |||
118 | if lower_snake_case == ident { | ||
119 | // While we didn't detect the correct case at the beginning, there | ||
120 | // may be special cases: e.g. `a` is both valid camelCase and snake_case. | ||
121 | None | ||
122 | } else { | ||
123 | Some(lower_snake_case) | ||
124 | } | ||
125 | } | 70 | } |
126 | 71 | ||
127 | /// Converts an identifier to an UPPER_SNAKE_CASE form. | 72 | /// Converts an identifier to an UPPER_SNAKE_CASE form. |
128 | /// Returns `None` if the string is already is UPPER_SNAKE_CASE. | 73 | /// Returns `None` if the string is already is UPPER_SNAKE_CASE. |
129 | pub fn to_upper_snake_case(ident: &str) -> Option<String> { | 74 | pub fn to_upper_snake_case(ident: &str) -> Option<String> { |
130 | match detect_case(ident) { | 75 | if is_upper_snake_case(ident) { |
131 | DetectedCase::UpperSnakeCase => return None, | 76 | return None; |
132 | DetectedCase::LowerSnakeCase => { | 77 | } else if is_lower_snake_case(ident) { |
133 | return Some(ident.chars().map(|chr| chr.to_ascii_uppercase()).collect()) | 78 | return Some(ident.to_uppercase()); |
134 | } | ||
135 | _ => {} | ||
136 | } | 79 | } |
137 | 80 | ||
138 | // Normalize the string from whatever form it's in currently, and then just make it uppercase. | 81 | Some(stdx::to_upper_snake_case(ident)) |
139 | let upper_snake_case = stdx::to_upper_snake_case(ident); | 82 | } |
140 | 83 | ||
141 | if upper_snake_case == ident { | 84 | // Taken from rustc. |
142 | // While we didn't detect the correct case at the beginning, there | 85 | // Modified by replacing the use of unstable feature `array_windows`. |
143 | // may be special cases: e.g. `A` is both valid CamelCase and UPPER_SNAKE_CASE. | 86 | fn is_camel_case(name: &str) -> bool { |
144 | None | 87 | let name = name.trim_matches('_'); |
145 | } else { | 88 | if name.is_empty() { |
146 | Some(upper_snake_case) | 89 | return true; |
147 | } | 90 | } |
91 | |||
92 | let mut fst = None; | ||
93 | // start with a non-lowercase letter rather than non-uppercase | ||
94 | // ones (some scripts don't have a concept of upper/lowercase) | ||
95 | !name.chars().next().unwrap().is_lowercase() | ||
96 | && !name.contains("__") | ||
97 | && !name.chars().any(|snd| { | ||
98 | let ret = match (fst, snd) { | ||
99 | (None, _) => false, | ||
100 | (Some(fst), snd) => { | ||
101 | char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_' | ||
102 | } | ||
103 | }; | ||
104 | fst = Some(snd); | ||
105 | |||
106 | ret | ||
107 | }) | ||
108 | } | ||
109 | |||
110 | fn is_lower_snake_case(ident: &str) -> bool { | ||
111 | is_snake_case(ident, char::is_uppercase) | ||
112 | } | ||
113 | |||
114 | fn is_upper_snake_case(ident: &str) -> bool { | ||
115 | is_snake_case(ident, char::is_lowercase) | ||
116 | } | ||
117 | |||
118 | // Taken from rustc. | ||
119 | // Modified to allow checking for both upper and lower snake case. | ||
120 | fn is_snake_case<F: Fn(char) -> bool>(ident: &str, wrong_case: F) -> bool { | ||
121 | if ident.is_empty() { | ||
122 | return true; | ||
123 | } | ||
124 | let ident = ident.trim_matches('_'); | ||
125 | |||
126 | let mut allow_underscore = true; | ||
127 | ident.chars().all(|c| { | ||
128 | allow_underscore = match c { | ||
129 | '_' if !allow_underscore => return false, | ||
130 | '_' => false, | ||
131 | // It would be more obvious to check for the correct case, | ||
132 | // but some characters do not have a case. | ||
133 | c if !wrong_case(c) => true, | ||
134 | _ => return false, | ||
135 | }; | ||
136 | true | ||
137 | }) | ||
138 | } | ||
139 | |||
140 | // Taken from rustc. | ||
141 | fn char_has_case(c: char) -> bool { | ||
142 | c.is_lowercase() || c.is_uppercase() | ||
148 | } | 143 | } |
149 | 144 | ||
150 | #[cfg(test)] | 145 | #[cfg(test)] |
@@ -167,6 +162,7 @@ mod tests { | |||
167 | check(to_lower_snake_case, "CamelCase", expect![["camel_case"]]); | 162 | check(to_lower_snake_case, "CamelCase", expect![["camel_case"]]); |
168 | check(to_lower_snake_case, "lowerCamelCase", expect![["lower_camel_case"]]); | 163 | check(to_lower_snake_case, "lowerCamelCase", expect![["lower_camel_case"]]); |
169 | check(to_lower_snake_case, "a", expect![[""]]); | 164 | check(to_lower_snake_case, "a", expect![[""]]); |
165 | check(to_lower_snake_case, "abc", expect![[""]]); | ||
170 | } | 166 | } |
171 | 167 | ||
172 | #[test] | 168 | #[test] |
@@ -180,6 +176,12 @@ mod tests { | |||
180 | check(to_camel_case, "Weird_Case", expect![["WeirdCase"]]); | 176 | check(to_camel_case, "Weird_Case", expect![["WeirdCase"]]); |
181 | check(to_camel_case, "name", expect![["Name"]]); | 177 | check(to_camel_case, "name", expect![["Name"]]); |
182 | check(to_camel_case, "A", expect![[""]]); | 178 | check(to_camel_case, "A", expect![[""]]); |
179 | check(to_camel_case, "AABB", expect![[""]]); | ||
180 | // Taken from rustc: /compiler/rustc_lint/src/nonstandard_style/tests.rs | ||
181 | check(to_camel_case, "X86_64", expect![[""]]); | ||
182 | check(to_camel_case, "x86__64", expect![["X86_64"]]); | ||
183 | check(to_camel_case, "Abc_123", expect![["Abc123"]]); | ||
184 | check(to_camel_case, "A1_b2_c3", expect![["A1B2C3"]]); | ||
183 | } | 185 | } |
184 | 186 | ||
185 | #[test] | 187 | #[test] |
@@ -190,5 +192,7 @@ mod tests { | |||
190 | check(to_upper_snake_case, "CamelCase", expect![["CAMEL_CASE"]]); | 192 | check(to_upper_snake_case, "CamelCase", expect![["CAMEL_CASE"]]); |
191 | check(to_upper_snake_case, "lowerCamelCase", expect![["LOWER_CAMEL_CASE"]]); | 193 | check(to_upper_snake_case, "lowerCamelCase", expect![["LOWER_CAMEL_CASE"]]); |
192 | check(to_upper_snake_case, "A", expect![[""]]); | 194 | check(to_upper_snake_case, "A", expect![[""]]); |
195 | check(to_upper_snake_case, "ABC", expect![[""]]); | ||
196 | check(to_upper_snake_case, "X86_64", expect![[""]]); | ||
193 | } | 197 | } |
194 | } | 198 | } |
diff --git a/crates/hir_ty/src/diagnostics/unsafe_check.rs b/crates/hir_ty/src/diagnostics/unsafe_check.rs index 21a121aad..2da9688ca 100644 --- a/crates/hir_ty/src/diagnostics/unsafe_check.rs +++ b/crates/hir_ty/src/diagnostics/unsafe_check.rs | |||
@@ -202,4 +202,22 @@ fn main() { | |||
202 | "#, | 202 | "#, |
203 | ); | 203 | ); |
204 | } | 204 | } |
205 | |||
206 | #[test] | ||
207 | fn no_missing_unsafe_diagnostic_with_safe_intrinsic() { | ||
208 | check_diagnostics( | ||
209 | r#" | ||
210 | extern "rust-intrinsic" { | ||
211 | pub fn bitreverse(x: u32) -> u32; // Safe intrinsic | ||
212 | pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic | ||
213 | } | ||
214 | |||
215 | fn main() { | ||
216 | let _ = bitreverse(12); | ||
217 | let _ = floorf32(12.0); | ||
218 | //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block | ||
219 | } | ||
220 | "#, | ||
221 | ); | ||
222 | } | ||
205 | } | 223 | } |
diff --git a/crates/hir_ty/src/traits.rs b/crates/hir_ty/src/traits.rs index 14cd3a2b4..ce1174cbe 100644 --- a/crates/hir_ty/src/traits.rs +++ b/crates/hir_ty/src/traits.rs | |||
@@ -5,6 +5,7 @@ use base_db::CrateId; | |||
5 | use chalk_ir::cast::Cast; | 5 | use chalk_ir::cast::Cast; |
6 | use chalk_solve::{logging_db::LoggingRustIrDatabase, Solver}; | 6 | use chalk_solve::{logging_db::LoggingRustIrDatabase, Solver}; |
7 | use hir_def::{lang_item::LangItemTarget, TraitId}; | 7 | use hir_def::{lang_item::LangItemTarget, TraitId}; |
8 | use stdx::panic_context; | ||
8 | 9 | ||
9 | use crate::{db::HirDatabase, DebruijnIndex, Substs}; | 10 | use crate::{db::HirDatabase, DebruijnIndex, Substs}; |
10 | 11 | ||
@@ -168,14 +169,23 @@ fn solve( | |||
168 | }; | 169 | }; |
169 | 170 | ||
170 | let mut solve = || { | 171 | let mut solve = || { |
171 | if is_chalk_print() { | 172 | let _ctx = if is_chalk_debug() || is_chalk_print() { |
172 | let logging_db = LoggingRustIrDatabase::new(context); | 173 | Some(panic_context::enter(format!("solving {:?}", goal))) |
173 | let solution = solver.solve_limited(&logging_db, goal, &should_continue); | 174 | } else { |
174 | log::debug!("chalk program:\n{}", logging_db); | 175 | None |
176 | }; | ||
177 | let solution = if is_chalk_print() { | ||
178 | let logging_db = | ||
179 | LoggingRustIrDatabaseLoggingOnDrop(LoggingRustIrDatabase::new(context)); | ||
180 | let solution = solver.solve_limited(&logging_db.0, goal, &should_continue); | ||
175 | solution | 181 | solution |
176 | } else { | 182 | } else { |
177 | solver.solve_limited(&context, goal, &should_continue) | 183 | solver.solve_limited(&context, goal, &should_continue) |
178 | } | 184 | }; |
185 | |||
186 | log::debug!("solve({:?}) => {:?}", goal, solution); | ||
187 | |||
188 | solution | ||
179 | }; | 189 | }; |
180 | 190 | ||
181 | // don't set the TLS for Chalk unless Chalk debugging is active, to make | 191 | // don't set the TLS for Chalk unless Chalk debugging is active, to make |
@@ -183,11 +193,17 @@ fn solve( | |||
183 | let solution = | 193 | let solution = |
184 | if is_chalk_debug() { chalk::tls::set_current_program(db, solve) } else { solve() }; | 194 | if is_chalk_debug() { chalk::tls::set_current_program(db, solve) } else { solve() }; |
185 | 195 | ||
186 | log::debug!("solve({:?}) => {:?}", goal, solution); | ||
187 | |||
188 | solution | 196 | solution |
189 | } | 197 | } |
190 | 198 | ||
199 | struct LoggingRustIrDatabaseLoggingOnDrop<'a>(LoggingRustIrDatabase<Interner, ChalkContext<'a>>); | ||
200 | |||
201 | impl<'a> Drop for LoggingRustIrDatabaseLoggingOnDrop<'a> { | ||
202 | fn drop(&mut self) { | ||
203 | eprintln!("chalk program:\n{}", self.0); | ||
204 | } | ||
205 | } | ||
206 | |||
191 | fn is_chalk_debug() -> bool { | 207 | fn is_chalk_debug() -> bool { |
192 | std::env::var("CHALK_DEBUG").is_ok() | 208 | std::env::var("CHALK_DEBUG").is_ok() |
193 | } | 209 | } |
diff --git a/crates/hir_ty/src/traits/chalk/mapping.rs b/crates/hir_ty/src/traits/chalk/mapping.rs index be3301313..dd7affcec 100644 --- a/crates/hir_ty/src/traits/chalk/mapping.rs +++ b/crates/hir_ty/src/traits/chalk/mapping.rs | |||
@@ -4,8 +4,8 @@ | |||
4 | //! conversions. | 4 | //! conversions. |
5 | 5 | ||
6 | use chalk_ir::{ | 6 | use chalk_ir::{ |
7 | cast::Cast, fold::shift::Shift, interner::HasInterner, PlaceholderIndex, Scalar, TypeName, | 7 | cast::Cast, fold::shift::Shift, interner::HasInterner, LifetimeData, PlaceholderIndex, Scalar, |
8 | UniverseIndex, | 8 | TypeName, UniverseIndex, |
9 | }; | 9 | }; |
10 | use chalk_solve::rust_ir; | 10 | use chalk_solve::rust_ir; |
11 | 11 | ||
@@ -76,7 +76,7 @@ impl ToChalk for Ty { | |||
76 | ); | 76 | ); |
77 | let bounded_ty = chalk_ir::DynTy { | 77 | let bounded_ty = chalk_ir::DynTy { |
78 | bounds: make_binders(where_clauses, 1), | 78 | bounds: make_binders(where_clauses, 1), |
79 | lifetime: FAKE_PLACEHOLDER.to_lifetime(&Interner), | 79 | lifetime: LifetimeData::Static.intern(&Interner), |
80 | }; | 80 | }; |
81 | chalk_ir::TyData::Dyn(bounded_ty).intern(&Interner) | 81 | chalk_ir::TyData::Dyn(bounded_ty).intern(&Interner) |
82 | } | 82 | } |
@@ -161,9 +161,6 @@ impl ToChalk for Ty { | |||
161 | } | 161 | } |
162 | } | 162 | } |
163 | 163 | ||
164 | const FAKE_PLACEHOLDER: PlaceholderIndex = | ||
165 | PlaceholderIndex { ui: UniverseIndex::ROOT, idx: usize::MAX }; | ||
166 | |||
167 | /// We currently don't model lifetimes, but Chalk does. So, we have to insert a | 164 | /// We currently don't model lifetimes, but Chalk does. So, we have to insert a |
168 | /// fake lifetime here, because Chalks built-in logic may expect it to be there. | 165 | /// fake lifetime here, because Chalks built-in logic may expect it to be there. |
169 | fn ref_to_chalk( | 166 | fn ref_to_chalk( |
@@ -172,7 +169,7 @@ fn ref_to_chalk( | |||
172 | subst: Substs, | 169 | subst: Substs, |
173 | ) -> chalk_ir::Ty<Interner> { | 170 | ) -> chalk_ir::Ty<Interner> { |
174 | let arg = subst[0].clone().to_chalk(db); | 171 | let arg = subst[0].clone().to_chalk(db); |
175 | let lifetime = FAKE_PLACEHOLDER.to_lifetime(&Interner); | 172 | let lifetime = LifetimeData::Static.intern(&Interner); |
176 | chalk_ir::ApplicationTy { | 173 | chalk_ir::ApplicationTy { |
177 | name: TypeName::Ref(mutability.to_chalk(db)), | 174 | name: TypeName::Ref(mutability.to_chalk(db)), |
178 | substitution: chalk_ir::Substitution::from_iter( | 175 | substitution: chalk_ir::Substitution::from_iter( |
@@ -205,7 +202,11 @@ fn array_to_chalk(db: &dyn HirDatabase, subst: Substs) -> chalk_ir::Ty<Interner> | |||
205 | substitution: chalk_ir::Substitution::empty(&Interner), | 202 | substitution: chalk_ir::Substitution::empty(&Interner), |
206 | } | 203 | } |
207 | .intern(&Interner); | 204 | .intern(&Interner); |
208 | let const_ = FAKE_PLACEHOLDER.to_const(&Interner, usize_ty); | 205 | let const_ = chalk_ir::ConstData { |
206 | ty: usize_ty, | ||
207 | value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }), | ||
208 | } | ||
209 | .intern(&Interner); | ||
209 | chalk_ir::ApplicationTy { | 210 | chalk_ir::ApplicationTy { |
210 | name: TypeName::Array, | 211 | name: TypeName::Array, |
211 | substitution: chalk_ir::Substitution::from_iter( | 212 | substitution: chalk_ir::Substitution::from_iter( |
diff --git a/crates/ide/Cargo.toml b/crates/ide/Cargo.toml index 29dc9a6a8..4d483580d 100644 --- a/crates/ide/Cargo.toml +++ b/crates/ide/Cargo.toml | |||
@@ -11,7 +11,7 @@ doctest = false | |||
11 | 11 | ||
12 | [dependencies] | 12 | [dependencies] |
13 | either = "1.5.3" | 13 | either = "1.5.3" |
14 | indexmap = "1.3.2" | 14 | indexmap = "1.4.0" |
15 | itertools = "0.9.0" | 15 | itertools = "0.9.0" |
16 | log = "0.4.8" | 16 | log = "0.4.8" |
17 | rustc-hash = "1.1.0" | 17 | rustc-hash = "1.1.0" |
@@ -23,13 +23,13 @@ url = "2.1.1" | |||
23 | stdx = { path = "../stdx", version = "0.0.0" } | 23 | stdx = { path = "../stdx", version = "0.0.0" } |
24 | syntax = { path = "../syntax", version = "0.0.0" } | 24 | syntax = { path = "../syntax", version = "0.0.0" } |
25 | text_edit = { path = "../text_edit", version = "0.0.0" } | 25 | text_edit = { path = "../text_edit", version = "0.0.0" } |
26 | base_db = { path = "../base_db", version = "0.0.0" } | ||
27 | ide_db = { path = "../ide_db", version = "0.0.0" } | 26 | ide_db = { path = "../ide_db", version = "0.0.0" } |
28 | cfg = { path = "../cfg", version = "0.0.0" } | 27 | cfg = { path = "../cfg", version = "0.0.0" } |
29 | profile = { path = "../profile", version = "0.0.0" } | 28 | profile = { path = "../profile", version = "0.0.0" } |
30 | test_utils = { path = "../test_utils", version = "0.0.0" } | 29 | test_utils = { path = "../test_utils", version = "0.0.0" } |
31 | assists = { path = "../assists", version = "0.0.0" } | 30 | assists = { path = "../assists", version = "0.0.0" } |
32 | ssr = { path = "../ssr", version = "0.0.0" } | 31 | ssr = { path = "../ssr", version = "0.0.0" } |
32 | completion = { path = "../completion", version = "0.0.0" } | ||
33 | 33 | ||
34 | # ide should depend only on the top-level `hir` package. if you need | 34 | # ide should depend only on the top-level `hir` package. if you need |
35 | # something from some `hir_xxx` subpackage, reexport the API via `hir`. | 35 | # something from some `hir_xxx` subpackage, reexport the API via `hir`. |
diff --git a/crates/ide/src/call_hierarchy.rs b/crates/ide/src/call_hierarchy.rs index d2cf2cc7d..8ad50a2ee 100644 --- a/crates/ide/src/call_hierarchy.rs +++ b/crates/ide/src/call_hierarchy.rs | |||
@@ -3,12 +3,12 @@ | |||
3 | use indexmap::IndexMap; | 3 | use indexmap::IndexMap; |
4 | 4 | ||
5 | use hir::Semantics; | 5 | use hir::Semantics; |
6 | use ide_db::call_info::FnCallNode; | ||
6 | use ide_db::RootDatabase; | 7 | use ide_db::RootDatabase; |
7 | use syntax::{ast, match_ast, AstNode, TextRange}; | 8 | use syntax::{ast, match_ast, AstNode, TextRange}; |
8 | 9 | ||
9 | use crate::{ | 10 | use crate::{ |
10 | call_info::FnCallNode, display::ToNav, goto_definition, references, FilePosition, | 11 | display::ToNav, goto_definition, references, FilePosition, NavigationTarget, RangeInfo, |
11 | NavigationTarget, RangeInfo, | ||
12 | }; | 12 | }; |
13 | 13 | ||
14 | #[derive(Debug, Clone)] | 14 | #[derive(Debug, Clone)] |
@@ -137,7 +137,7 @@ impl CallLocations { | |||
137 | 137 | ||
138 | #[cfg(test)] | 138 | #[cfg(test)] |
139 | mod tests { | 139 | mod tests { |
140 | use base_db::FilePosition; | 140 | use ide_db::base_db::FilePosition; |
141 | 141 | ||
142 | use crate::fixture; | 142 | use crate::fixture; |
143 | 143 | ||
diff --git a/crates/ide/src/completion/generated_features.rs b/crates/ide/src/completion/generated_features.rs deleted file mode 100644 index 24754a8cf..000000000 --- a/crates/ide/src/completion/generated_features.rs +++ /dev/null | |||
@@ -1,4 +0,0 @@ | |||
1 | //! Generated file, do not edit by hand, see `xtask/src/codegen` | ||
2 | |||
3 | use crate::completion::complete_attribute::LintCompletion; | ||
4 | pub ( super ) const FEATURES : & [ LintCompletion ] = & [ LintCompletion { label : "doc_cfg" , description : "# `doc_cfg`\n\nThe tracking issue for this feature is: [#43781]\n\n------\n\nThe `doc_cfg` feature allows an API be documented as only available in some specific platforms.\nThis attribute has two effects:\n\n1. In the annotated item's documentation, there will be a message saying \"This is supported on\n (platform) only\".\n\n2. The item's doc-tests will only run on the specific platform.\n\nIn addition to allowing the use of the `#[doc(cfg)]` attribute, this feature enables the use of a\nspecial conditional compilation flag, `#[cfg(doc)]`, set whenever building documentation on your\ncrate.\n\nThis feature was introduced as part of PR [#43348] to allow the platform-specific parts of the\nstandard library be documented.\n\n```rust\n#![feature(doc_cfg)]\n\n#[cfg(any(windows, doc))]\n#[doc(cfg(windows))]\n/// The application's icon in the notification area (a.k.a. system tray).\n///\n/// # Examples\n///\n/// ```no_run\n/// extern crate my_awesome_ui_library;\n/// use my_awesome_ui_library::current_app;\n/// use my_awesome_ui_library::windows::notification;\n///\n/// let icon = current_app().get::<notification::Icon>();\n/// icon.show();\n/// icon.show_message(\"Hello\");\n/// ```\npub struct Icon {\n // ...\n}\n```\n\n[#43781]: https://github.com/rust-lang/rust/issues/43781\n[#43348]: https://github.com/rust-lang/rust/issues/43348\n" } , LintCompletion { label : "impl_trait_in_bindings" , description : "# `impl_trait_in_bindings`\n\nThe tracking issue for this feature is: [#63065]\n\n[#63065]: https://github.com/rust-lang/rust/issues/63065\n\n------------------------\n\nThe `impl_trait_in_bindings` feature gate lets you use `impl Trait` syntax in\n`let`, `static`, and `const` bindings.\n\nA simple example is:\n\n```rust\n#![feature(impl_trait_in_bindings)]\n\nuse std::fmt::Debug;\n\nfn main() {\n let a: impl Debug + Clone = 42;\n let b = a.clone();\n println!(\"{:?}\", b); // prints `42`\n}\n```\n\nNote however that because the types of `a` and `b` are opaque in the above\nexample, calling inherent methods or methods outside of the specified traits\n(e.g., `a.abs()` or `b.abs()`) is not allowed, and yields an error.\n" } , LintCompletion { label : "plugin" , description : "# `plugin`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin_registrar`] and `rustc_private` features.\n\n[`plugin_registrar`]: plugin-registrar.md\n\n------------------------\n\n`rustc` can load compiler plugins, which are user-provided libraries that\nextend the compiler's behavior with new lint checks, etc.\n\nA plugin is a dynamic library crate with a designated *registrar* function that\nregisters extensions with `rustc`. Other crates can load these extensions using\nthe crate attribute `#![plugin(...)]`. See the\n`rustc_driver::plugin` documentation for more about the\nmechanics of defining and loading a plugin.\n\nIn the vast majority of cases, a plugin should *only* be used through\n`#![plugin]` and not through an `extern crate` item. Linking a plugin would\npull in all of librustc_ast and librustc as dependencies of your crate. This is\ngenerally unwanted unless you are building another plugin.\n\nThe usual practice is to put compiler plugins in their own crate, separate from\nany `macro_rules!` macros or ordinary Rust code meant to be used by consumers\nof a library.\n\n# Lint plugins\n\nPlugins can extend [Rust's lint\ninfrastructure](../../reference/attributes/diagnostics.md#lint-check-attributes) with\nadditional checks for code style, safety, etc. Now let's write a plugin\n[`lint-plugin-test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs)\nthat warns about any item named `lintme`.\n\n```rust,ignore\n#![feature(plugin_registrar)]\n#![feature(box_syntax, rustc_private)]\n\nextern crate rustc_ast;\n\n// Load rustc as a plugin to get macros\nextern crate rustc_driver;\n#[macro_use]\nextern crate rustc_lint;\n#[macro_use]\nextern crate rustc_session;\n\nuse rustc_driver::plugin::Registry;\nuse rustc_lint::{EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};\nuse rustc_ast::ast;\ndeclare_lint!(TEST_LINT, Warn, \"Warn about items named 'lintme'\");\n\ndeclare_lint_pass!(Pass => [TEST_LINT]);\n\nimpl EarlyLintPass for Pass {\n fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {\n if it.ident.name.as_str() == \"lintme\" {\n cx.lint(TEST_LINT, |lint| {\n lint.build(\"item is named 'lintme'\").set_span(it.span).emit()\n });\n }\n }\n}\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n reg.lint_store.register_lints(&[&TEST_LINT]);\n reg.lint_store.register_early_pass(|| box Pass);\n}\n```\n\nThen code like\n\n```rust,ignore\n#![feature(plugin)]\n#![plugin(lint_plugin_test)]\n\nfn lintme() { }\n```\n\nwill produce a compiler warning:\n\n```txt\nfoo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default\nfoo.rs:4 fn lintme() { }\n ^~~~~~~~~~~~~~~\n```\n\nThe components of a lint plugin are:\n\n* one or more `declare_lint!` invocations, which define static `Lint` structs;\n\n* a struct holding any state needed by the lint pass (here, none);\n\n* a `LintPass`\n implementation defining how to check each syntax element. A single\n `LintPass` may call `span_lint` for several different `Lint`s, but should\n register them all through the `get_lints` method.\n\nLint passes are syntax traversals, but they run at a late stage of compilation\nwhere type information is available. `rustc`'s [built-in\nlints](https://github.com/rust-lang/rust/blob/master/src/librustc_session/lint/builtin.rs)\nmostly use the same infrastructure as lint plugins, and provide examples of how\nto access type information.\n\nLints defined by plugins are controlled by the usual [attributes and compiler\nflags](../../reference/attributes/diagnostics.md#lint-check-attributes), e.g.\n`#[allow(test_lint)]` or `-A test-lint`. These identifiers are derived from the\nfirst argument to `declare_lint!`, with appropriate case and punctuation\nconversion.\n\nYou can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,\nincluding those provided by plugins loaded by `foo.rs`.\n" } , LintCompletion { label : "infer_static_outlives_requirements" , description : "# `infer_static_outlives_requirements`\n\nThe tracking issue for this feature is: [#54185]\n\n[#54185]: https://github.com/rust-lang/rust/issues/54185\n\n------------------------\nThe `infer_static_outlives_requirements` feature indicates that certain\n`'static` outlives requirements can be inferred by the compiler rather than\nstating them explicitly.\n\nNote: It is an accompanying feature to `infer_outlives_requirements`,\nwhich must be enabled to infer outlives requirements.\n\nFor example, currently generic struct definitions that contain\nreferences, require where-clauses of the form T: 'static. By using\nthis feature the outlives predicates will be inferred, although\nthey may still be written explicitly.\n\n```rust,ignore (pseudo-Rust)\nstruct Foo<U> where U: 'static { // <-- currently required\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n\n## Examples:\n\n```rust,ignore (pseudo-Rust)\n#![feature(infer_outlives_requirements)]\n#![feature(infer_static_outlives_requirements)]\n\n#[rustc_outlives]\n// Implicitly infer U: 'static\nstruct Foo<U> {\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n" } , LintCompletion { label : "doc_alias" , description : "# `doc_alias`\n\nThe tracking issue for this feature is: [#50146]\n\n[#50146]: https://github.com/rust-lang/rust/issues/50146\n\n------------------------\n\nYou can add alias(es) to an item when using the `rustdoc` search through the\n`doc(alias)` attribute. Example:\n\n```rust,no_run\n#![feature(doc_alias)]\n\n#[doc(alias = \"x\")]\n#[doc(alias = \"big\")]\npub struct BigX;\n```\n\nThen, when looking for it through the `rustdoc` search, if you enter \"x\" or\n\"big\", search will show the `BigX` struct first.\n\nNote that this feature is currently hidden behind the `feature(doc_alias)` gate.\n" } , LintCompletion { label : "optin_builtin_traits" , description : "# `optin_builtin_traits`\n\nThe tracking issue for this feature is [#13231] \n\n[#13231]: https://github.com/rust-lang/rust/issues/13231\n\n----\n\nThe `optin_builtin_traits` feature gate allows you to define auto traits.\n\nAuto traits, like [`Send`] or [`Sync`] in the standard library, are marker traits\nthat are automatically implemented for every type, unless the type, or a type it contains, \nhas explicitly opted out via a negative impl. (Negative impls are separately controlled\nby the `negative_impls` feature.)\n\n[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html\n[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html\n\n```rust,ignore\nimpl !Trait for Type\n```\n\nExample:\n\n```rust\n#![feature(negative_impls)]\n#![feature(optin_builtin_traits)]\n\nauto trait Valid {}\n\nstruct True;\nstruct False;\n\nimpl !Valid for False {}\n\nstruct MaybeValid<T>(T);\n\nfn must_be_valid<T: Valid>(_t: T) { }\n\nfn main() {\n // works\n must_be_valid( MaybeValid(True) );\n \n // compiler error - trait bound not satisfied\n // must_be_valid( MaybeValid(False) );\n}\n```\n\n## Automatic trait implementations\n\nWhen a type is declared as an `auto trait`, we will automatically\ncreate impls for every struct/enum/union, unless an explicit impl is\nprovided. These automatic impls contain a where clause for each field\nof the form `T: AutoTrait`, where `T` is the type of the field and\n`AutoTrait` is the auto trait in question. As an example, consider the\nstruct `List` and the auto trait `Send`:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n```\n\nPresuming that there is no explicit impl of `Send` for `List`, the\ncompiler will supply an automatic impl of the form:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n\nunsafe impl<T> Send for List<T>\nwhere\n T: Send, // from the field `data`\n Option<Box<List<T>>>: Send, // from the field `next`\n{ }\n```\n\nExplicit impls may be either positive or negative. They take the form:\n\n```rust,ignore\nimpl<...> AutoTrait for StructName<..> { }\nimpl<...> !AutoTrait for StructName<..> { }\n```\n\n## Coinduction: Auto traits permit cyclic matching\n\nUnlike ordinary trait matching, auto traits are **coinductive**. This\nmeans, in short, that cycles which occur in trait matching are\nconsidered ok. As an example, consider the recursive struct `List`\nintroduced in the previous section. In attempting to determine whether\n`List: Send`, we would wind up in a cycle: to apply the impl, we must\nshow that `Option<Box<List>>: Send`, which will in turn require\n`Box<List>: Send` and then finally `List: Send` again. Under ordinary\ntrait matching, this cycle would be an error, but for an auto trait it\nis considered a successful match.\n\n## Items\n\nAuto traits cannot have any trait items, such as methods or associated types. This ensures that we can generate default implementations.\n\n## Supertraits\n\nAuto traits cannot have supertraits. This is for soundness reasons, as the interaction of coinduction with implied bounds is difficult to reconcile.\n\n" } , LintCompletion { label : "const_in_array_repeat_expressions" , description : "# `const_in_array_repeat_expressions`\n\nThe tracking issue for this feature is: [#49147]\n\n[#49147]: https://github.com/rust-lang/rust/issues/49147\n\n------------------------\n\nRelaxes the rules for repeat expressions, `[x; N]` such that `x` may also be `const` (strictly\nspeaking rvalue promotable), in addition to `typeof(x): Copy`. The result of `[x; N]` where `x` is\n`const` is itself also `const`.\n" } , LintCompletion { label : "generators" , description : "# `generators`\n\nThe tracking issue for this feature is: [#43122]\n\n[#43122]: https://github.com/rust-lang/rust/issues/43122\n\n------------------------\n\nThe `generators` feature gate in Rust allows you to define generator or\ncoroutine literals. A generator is a \"resumable function\" that syntactically\nresembles a closure but compiles to much different semantics in the compiler\nitself. The primary feature of a generator is that it can be suspended during\nexecution to be resumed at a later date. Generators use the `yield` keyword to\n\"return\", and then the caller can `resume` a generator to resume execution just\nafter the `yield` keyword.\n\nGenerators are an extra-unstable feature in the compiler right now. Added in\n[RFC 2033] they're mostly intended right now as a information/constraint\ngathering phase. The intent is that experimentation can happen on the nightly\ncompiler before actual stabilization. A further RFC will be required to\nstabilize generators/coroutines and will likely contain at least a few small\ntweaks to the overall design.\n\n[RFC 2033]: https://github.com/rust-lang/rfcs/pull/2033\n\nA syntactical example of a generator is:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n yield 1;\n return \"foo\"\n };\n\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Yielded(1) => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Complete(\"foo\") => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n}\n```\n\nGenerators are closure-like literals which can contain a `yield` statement. The\n`yield` statement takes an optional expression of a value to yield out of the\ngenerator. All generator literals implement the `Generator` trait in the\n`std::ops` module. The `Generator` trait has one main method, `resume`, which\nresumes execution of the generator at the previous suspension point.\n\nAn example of the control flow of generators is that the following example\nprints all numbers in order:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n println!(\"2\");\n yield;\n println!(\"4\");\n };\n\n println!(\"1\");\n Pin::new(&mut generator).resume(());\n println!(\"3\");\n Pin::new(&mut generator).resume(());\n println!(\"5\");\n}\n```\n\nAt this time the main intended use case of generators is an implementation\nprimitive for async/await syntax, but generators will likely be extended to\nergonomic implementations of iterators and other primitives in the future.\nFeedback on the design and usage is always appreciated!\n\n### The `Generator` trait\n\nThe `Generator` trait in `std::ops` currently looks like:\n\n```rust\n# #![feature(arbitrary_self_types, generator_trait)]\n# use std::ops::GeneratorState;\n# use std::pin::Pin;\n\npub trait Generator<R = ()> {\n type Yield;\n type Return;\n fn resume(self: Pin<&mut Self>, resume: R) -> GeneratorState<Self::Yield, Self::Return>;\n}\n```\n\nThe `Generator::Yield` type is the type of values that can be yielded with the\n`yield` statement. The `Generator::Return` type is the returned type of the\ngenerator. This is typically the last expression in a generator's definition or\nany value passed to `return` in a generator. The `resume` function is the entry\npoint for executing the `Generator` itself.\n\nThe return value of `resume`, `GeneratorState`, looks like:\n\n```rust\npub enum GeneratorState<Y, R> {\n Yielded(Y),\n Complete(R),\n}\n```\n\nThe `Yielded` variant indicates that the generator can later be resumed. This\ncorresponds to a `yield` point in a generator. The `Complete` variant indicates\nthat the generator is complete and cannot be resumed again. Calling `resume`\nafter a generator has returned `Complete` will likely result in a panic of the\nprogram.\n\n### Closure-like semantics\n\nThe closure-like syntax for generators alludes to the fact that they also have\nclosure-like semantics. Namely:\n\n* When created, a generator executes no code. A closure literal does not\n actually execute any of the closure's code on construction, and similarly a\n generator literal does not execute any code inside the generator when\n constructed.\n\n* Generators can capture outer variables by reference or by move, and this can\n be tweaked with the `move` keyword at the beginning of the closure. Like\n closures all generators will have an implicit environment which is inferred by\n the compiler. Outer variables can be moved into a generator for use as the\n generator progresses.\n\n* Generator literals produce a value with a unique type which implements the\n `std::ops::Generator` trait. This allows actual execution of the generator\n through the `Generator::resume` method as well as also naming it in return\n types and such.\n\n* Traits like `Send` and `Sync` are automatically implemented for a `Generator`\n depending on the captured variables of the environment. Unlike closures,\n generators also depend on variables live across suspension points. This means\n that although the ambient environment may be `Send` or `Sync`, the generator\n itself may not be due to internal variables live across `yield` points being\n not-`Send` or not-`Sync`. Note that generators do\n not implement traits like `Copy` or `Clone` automatically.\n\n* Whenever a generator is dropped it will drop all captured environment\n variables.\n\n### Generators as state machines\n\nIn the compiler, generators are currently compiled as state machines. Each\n`yield` expression will correspond to a different state that stores all live\nvariables over that suspension point. Resumption of a generator will dispatch on\nthe current state and then execute internally until a `yield` is reached, at\nwhich point all state is saved off in the generator and a value is returned.\n\nLet's take a look at an example to see what's going on here:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = move || {\n yield 1;\n return ret\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nThis generator literal will compile down to something similar to:\n\n```rust\n#![feature(arbitrary_self_types, generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = {\n enum __Generator {\n Start(&'static str),\n Yield1(&'static str),\n Done,\n }\n\n impl Generator for __Generator {\n type Yield = i32;\n type Return = &'static str;\n\n fn resume(mut self: Pin<&mut Self>, resume: ()) -> GeneratorState<i32, &'static str> {\n use std::mem;\n match mem::replace(&mut *self, __Generator::Done) {\n __Generator::Start(s) => {\n *self = __Generator::Yield1(s);\n GeneratorState::Yielded(1)\n }\n\n __Generator::Yield1(s) => {\n *self = __Generator::Done;\n GeneratorState::Complete(s)\n }\n\n __Generator::Done => {\n panic!(\"generator resumed after completion\")\n }\n }\n }\n }\n\n __Generator::Start(ret)\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nNotably here we can see that the compiler is generating a fresh type,\n`__Generator` in this case. This type has a number of states (represented here\nas an `enum`) corresponding to each of the conceptual states of the generator.\nAt the beginning we're closing over our outer variable `foo` and then that\nvariable is also live over the `yield` point, so it's stored in both states.\n\nWhen the generator starts it'll immediately yield 1, but it saves off its state\njust before it does so indicating that it has reached the yield point. Upon\nresuming again we'll execute the `return ret` which returns the `Complete`\nstate.\n\nHere we can also note that the `Done` state, if resumed, panics immediately as\nit's invalid to resume a completed generator. It's also worth noting that this\nis just a rough desugaring, not a normative specification for what the compiler\ndoes.\n" } , LintCompletion { label : "unsized_tuple_coercion" , description : "# `unsized_tuple_coercion`\n\nThe tracking issue for this feature is: [#42877]\n\n[#42877]: https://github.com/rust-lang/rust/issues/42877\n\n------------------------\n\nThis is a part of [RFC0401]. According to the RFC, there should be an implementation like this:\n\n```rust,ignore\nimpl<..., T, U: ?Sized> Unsized<(..., U)> for (..., T) where T: Unsized<U> {}\n```\n\nThis implementation is currently gated behind `#[feature(unsized_tuple_coercion)]` to avoid insta-stability. Therefore you can use it like this:\n\n```rust\n#![feature(unsized_tuple_coercion)]\n\nfn main() {\n let x : ([i32; 3], [i32; 3]) = ([1, 2, 3], [4, 5, 6]);\n let y : &([i32; 3], [i32]) = &x;\n assert_eq!(y.1[0], 4);\n}\n```\n\n[RFC0401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md\n" } , LintCompletion { label : "cfg_version" , description : "# `cfg_version`\n\nThe tracking issue for this feature is: [#64796]\n\n[#64796]: https://github.com/rust-lang/rust/issues/64796\n\n------------------------\n\nThe `cfg_version` feature makes it possible to execute different code\ndepending on the compiler version.\n\n## Examples\n\n```rust\n#![feature(cfg_version)]\n\n#[cfg(version(\"1.42\"))]\nfn a() {\n // ...\n}\n\n#[cfg(not(version(\"1.42\")))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(version(\"1.42\")) {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "ffi_const" , description : "# `ffi_const`\n\nThe `#[ffi_const]` attribute applies clang's `const` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_const]` functions shall have no effects except for its return\nvalue, which can only depend on the values of the function parameters, and is\nnot affected by changes to the observable state of the program.\n\nApplying the `#[ffi_const]` attribute to a function that violates these\nrequirements is undefined behaviour.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination, and it can avoid emitting some calls in repeated invocations of the\nfunction with the same argument values regardless of other operations being\nperformed in between these functions calls (as opposed to `#[ffi_pure]`\nfunctions).\n\n## Pitfalls\n\nA `#[ffi_const]` function can only read global memory that would not affect\nits return value for the whole execution of the program (e.g. immutable global\nmemory). `#[ffi_const]` functions are referentially-transparent and therefore\nmore strict than `#[ffi_pure]` functions.\n\nA common pitfall involves applying the `#[ffi_const]` attribute to a\nfunction that reads memory through pointer arguments which do not necessarily\npoint to immutable global memory.\n\nA `#[ffi_const]` function that returns unit has no effect on the abstract\nmachine's state, and a `#[ffi_const]` function cannot be `#[ffi_pure]`.\n\nA `#[ffi_const]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `const` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`const` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_const]`.\n\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacgigch.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_const.htm\n" } , LintCompletion { label : "const_fn" , description : "# `const_fn`\n\nThe tracking issue for this feature is: [#57563]\n\n[#57563]: https://github.com/rust-lang/rust/issues/57563\n\n------------------------\n\nThe `const_fn` feature allows marking free functions and inherent methods as\n`const`, enabling them to be called in constants contexts, with constant\narguments.\n\n## Examples\n\n```rust\n#![feature(const_fn)]\n\nconst fn double(x: i32) -> i32 {\n x * 2\n}\n\nconst FIVE: i32 = 5;\nconst TEN: i32 = double(FIVE);\n\nfn main() {\n assert_eq!(5, FIVE);\n assert_eq!(10, TEN);\n}\n```\n" } , LintCompletion { label : "unsized_locals" , description : "# `unsized_locals`\n\nThe tracking issue for this feature is: [#48055]\n\n[#48055]: https://github.com/rust-lang/rust/issues/48055\n\n------------------------\n\nThis implements [RFC1909]. When turned on, you can have unsized arguments and locals:\n\n[RFC1909]: https://github.com/rust-lang/rfcs/blob/master/text/1909-unsized-rvalues.md\n\n```rust\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nfn main() {\n let x: Box<dyn Any> = Box::new(42);\n let x: dyn Any = *x;\n // ^ unsized local variable\n // ^^ unsized temporary\n foo(x);\n}\n\nfn foo(_: dyn Any) {}\n// ^^^^^^ unsized argument\n```\n\nThe RFC still forbids the following unsized expressions:\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nstruct MyStruct<T: ?Sized> {\n content: T,\n}\n\nstruct MyTupleStruct<T: ?Sized>(T);\n\nfn answer() -> Box<dyn Any> {\n Box::new(42)\n}\n\nfn main() {\n // You CANNOT have unsized statics.\n static X: dyn Any = *answer(); // ERROR\n const Y: dyn Any = *answer(); // ERROR\n\n // You CANNOT have struct initialized unsized.\n MyStruct { content: *answer() }; // ERROR\n MyTupleStruct(*answer()); // ERROR\n (42, *answer()); // ERROR\n\n // You CANNOT have unsized return types.\n fn my_function() -> dyn Any { *answer() } // ERROR\n\n // You CAN have unsized local variables...\n let mut x: dyn Any = *answer(); // OK\n // ...but you CANNOT reassign to them.\n x = *answer(); // ERROR\n\n // You CANNOT even initialize them separately.\n let y: dyn Any; // OK\n y = *answer(); // ERROR\n\n // Not mentioned in the RFC, but by-move captured variables are also Sized.\n let x: dyn Any = *answer();\n (move || { // ERROR\n let y = x;\n })();\n\n // You CAN create a closure with unsized arguments,\n // but you CANNOT call it.\n // This is an implementation detail and may be changed in the future.\n let f = |x: dyn Any| {};\n f(*answer()); // ERROR\n}\n```\n\n## By-value trait objects\n\nWith this feature, you can have by-value `self` arguments without `Self: Sized` bounds.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main() {\n let slice: Box<[i32]> = Box::new([1, 2, 3]);\n <[i32] as Foo>::foo(*slice);\n}\n```\n\nAnd `Foo` will also be object-safe.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main () {\n let slice: Box<dyn Foo> = Box::new([1, 2, 3]);\n // doesn't compile yet\n <dyn Foo as Foo>::foo(*slice);\n}\n```\n\nOne of the objectives of this feature is to allow `Box<dyn FnOnce>`.\n\n## Variable length arrays\n\nThe RFC also describes an extension to the array literal syntax: `[e; dyn n]`. In the syntax, `n` isn't necessarily a constant expression. The array is dynamically allocated on the stack and has the type of `[T]`, instead of `[T; n]`.\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nfn mergesort<T: Ord>(a: &mut [T]) {\n let mut tmp = [T; dyn a.len()];\n // ...\n}\n\nfn main() {\n let mut a = [3, 1, 5, 6];\n mergesort(&mut a);\n assert_eq!(a, [1, 3, 5, 6]);\n}\n```\n\nVLAs are not implemented yet. The syntax isn't final, either. We may need an alternative syntax for Rust 2015 because, in Rust 2015, expressions like `[e; dyn(1)]` would be ambiguous. One possible alternative proposed in the RFC is `[e; n]`: if `n` captures one or more local variables, then it is considered as `[e; dyn n]`.\n\n## Advisory on stack usage\n\nIt's advised not to casually use the `#![feature(unsized_locals)]` feature. Typical use-cases are:\n\n- When you need a by-value trait objects.\n- When you really need a fast allocation of small temporary arrays.\n\nAnother pitfall is repetitive allocation and temporaries. Currently the compiler simply extends the stack frame every time it encounters an unsized assignment. So for example, the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = {{{{{{{{{{*x}}}}}}}}}};\n}\n```\n\nand the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n for _ in 0..10 {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = *x;\n }\n}\n```\n\nwill unnecessarily extend the stack frame.\n" } , LintCompletion { label : "or_patterns" , description : "# `or_patterns`\n\nThe tracking issue for this feature is: [#54883]\n\n[#54883]: https://github.com/rust-lang/rust/issues/54883\n\n------------------------\n\nThe `or_pattern` language feature allows `|` to be arbitrarily nested within\na pattern, for example, `Some(A(0) | B(1 | 2))` becomes a valid pattern.\n\n## Examples\n\n```rust,ignore\n#![feature(or_patterns)]\n\npub enum Foo {\n Bar,\n Baz,\n Quux,\n}\n\npub fn example(maybe_foo: Option<Foo>) {\n match maybe_foo {\n Some(Foo::Bar | Foo::Baz) => {\n println!(\"The value contained `Bar` or `Baz`\");\n }\n Some(_) => {\n println!(\"The value did not contain `Bar` or `Baz`\");\n }\n None => {\n println!(\"The value was `None`\");\n }\n }\n}\n```\n" } , LintCompletion { label : "no_sanitize" , description : "# `no_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `no_sanitize` attribute can be used to selectively disable sanitizer\ninstrumentation in an annotated function. This might be useful to: avoid\ninstrumentation overhead in a performance critical function, or avoid\ninstrumenting code that contains constructs unsupported by given sanitizer.\n\nThe precise effect of this annotation depends on particular sanitizer in use.\nFor example, with `no_sanitize(thread)`, the thread sanitizer will no longer\ninstrument non-atomic store / load operations, but it will instrument atomic\noperations to avoid reporting false positives and provide meaning full stack\ntraces.\n\n## Examples\n\n``` rust\n#![feature(no_sanitize)]\n\n#[no_sanitize(address)]\nfn foo() {\n // ...\n}\n```\n" } , LintCompletion { label : "doc_spotlight" , description : "# `doc_spotlight`\n\nThe tracking issue for this feature is: [#45040]\n\nThe `doc_spotlight` feature allows the use of the `spotlight` parameter to the `#[doc]` attribute,\nto \"spotlight\" a specific trait on the return values of functions. Adding a `#[doc(spotlight)]`\nattribute to a trait definition will make rustdoc print extra information for functions which return\na type that implements that trait. This attribute is applied to the `Iterator`, `io::Read`, and\n`io::Write` traits in the standard library.\n\nYou can do this on your own traits, like this:\n\n```\n#![feature(doc_spotlight)]\n\n#[doc(spotlight)]\npub trait MyTrait {}\n\npub struct MyStruct;\nimpl MyTrait for MyStruct {}\n\n/// The docs for this function will have an extra line about `MyStruct` implementing `MyTrait`,\n/// without having to write that yourself!\npub fn my_fn() -> MyStruct { MyStruct }\n```\n\nThis feature was originally implemented in PR [#45039].\n\n[#45040]: https://github.com/rust-lang/rust/issues/45040\n[#45039]: https://github.com/rust-lang/rust/pull/45039\n" } , LintCompletion { label : "cfg_sanitize" , description : "# `cfg_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `cfg_sanitize` feature makes it possible to execute different code\ndepending on whether a particular sanitizer is enabled or not.\n\n## Examples\n\n```rust\n#![feature(cfg_sanitize)]\n\n#[cfg(sanitize = \"thread\")]\nfn a() {\n // ...\n}\n\n#[cfg(not(sanitize = \"thread\"))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(sanitize = \"leak\") {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "doc_masked" , description : "# `doc_masked`\n\nThe tracking issue for this feature is: [#44027]\n\n-----\n\nThe `doc_masked` feature allows a crate to exclude types from a given crate from appearing in lists\nof trait implementations. The specifics of the feature are as follows:\n\n1. When rustdoc encounters an `extern crate` statement annotated with a `#[doc(masked)]` attribute,\n it marks the crate as being masked.\n\n2. When listing traits a given type implements, rustdoc ensures that traits from masked crates are\n not emitted into the documentation.\n\n3. When listing types that implement a given trait, rustdoc ensures that types from masked crates\n are not emitted into the documentation.\n\nThis feature was introduced in PR [#44026] to ensure that compiler-internal and\nimplementation-specific types and traits were not included in the standard library's documentation.\nSuch types would introduce broken links into the documentation.\n\n[#44026]: https://github.com/rust-lang/rust/pull/44026\n[#44027]: https://github.com/rust-lang/rust/pull/44027\n" } , LintCompletion { label : "abi_thiscall" , description : "# `abi_thiscall`\n\nThe tracking issue for this feature is: [#42202]\n\n[#42202]: https://github.com/rust-lang/rust/issues/42202\n\n------------------------\n\nThe MSVC ABI on x86 Windows uses the `thiscall` calling convention for C++\ninstance methods by default; it is identical to the usual (C) calling\nconvention on x86 Windows except that the first parameter of the method,\nthe `this` pointer, is passed in the ECX register.\n" } , LintCompletion { label : "lang_items" , description : "# `lang_items`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe `rustc` compiler has certain pluggable operations, that is,\nfunctionality that isn't hard-coded into the language, but is\nimplemented in libraries, with a special marker to tell the compiler\nit exists. The marker is the attribute `#[lang = \"...\"]` and there are\nvarious different values of `...`, i.e. various different 'lang\nitems'.\n\nFor example, `Box` pointers require two lang items, one for allocation\nand one for deallocation. A freestanding program that uses the `Box`\nsugar for dynamic allocations via `malloc` and `free`:\n\n```rust,ignore\n#![feature(lang_items, box_syntax, start, libc, core_intrinsics)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\nextern crate libc;\n\n#[lang = \"owned_box\"]\npub struct Box<T>(*mut T);\n\n#[lang = \"exchange_malloc\"]\nunsafe fn allocate(size: usize, _align: usize) -> *mut u8 {\n let p = libc::malloc(size as libc::size_t) as *mut u8;\n\n // Check if `malloc` failed:\n if p as usize == 0 {\n intrinsics::abort();\n }\n\n p\n}\n\n#[lang = \"box_free\"]\nunsafe fn box_free<T: ?Sized>(ptr: *mut T) {\n libc::free(ptr as *mut libc::c_void)\n}\n\n#[start]\nfn main(_argc: isize, _argv: *const *const u8) -> isize {\n let _x = box 1;\n\n 0\n}\n\n#[lang = \"eh_personality\"] extern fn rust_eh_personality() {}\n#[lang = \"panic_impl\"] extern fn rust_begin_panic(info: &PanicInfo) -> ! { unsafe { intrinsics::abort() } }\n#[no_mangle] pub extern fn rust_eh_register_frames () {}\n#[no_mangle] pub extern fn rust_eh_unregister_frames () {}\n```\n\nNote the use of `abort`: the `exchange_malloc` lang item is assumed to\nreturn a valid pointer, and so needs to do the check internally.\n\nOther features provided by lang items include:\n\n- overloadable operators via traits: the traits corresponding to the\n `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all\n marked with lang items; those specific four are `eq`, `ord`,\n `deref`, and `add` respectively.\n- stack unwinding and general failure; the `eh_personality`,\n `panic` and `panic_bounds_checks` lang items.\n- the traits in `std::marker` used to indicate types of\n various kinds; lang items `send`, `sync` and `copy`.\n- the marker types and variance indicators found in\n `std::marker`; lang items `covariant_type`,\n `contravariant_lifetime`, etc.\n\nLang items are loaded lazily by the compiler; e.g. if one never uses\n`Box` then there is no need to define functions for `exchange_malloc`\nand `box_free`. `rustc` will emit an error when an item is needed\nbut not found in the current crate or any that it depends on.\n\nMost lang items are defined by `libcore`, but if you're trying to build\nan executable without the standard library, you'll run into the need\nfor lang items. The rest of this page focuses on this use-case, even though\nlang items are a bit broader than that.\n\n### Using libc\n\nIn order to build a `#[no_std]` executable we will need libc as a dependency.\nWe can specify this using our `Cargo.toml` file:\n\n```toml\n[dependencies]\nlibc = { version = \"0.2.14\", default-features = false }\n```\n\nNote that the default features have been disabled. This is a critical step -\n**the default features of libc include the standard library and so must be\ndisabled.**\n\n### Writing an executable without stdlib\n\nControlling the entry point is possible in two ways: the `#[start]` attribute,\nor overriding the default shim for the C `main` function with your own.\n\nThe function marked `#[start]` is passed the command line parameters\nin the same format as C:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[start]\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nTo override the compiler-inserted `main` shim, one has to disable it\nwith `#![no_main]` and then create the appropriate symbol with the\ncorrect ABI and the correct name, which requires overriding the\ncompiler's name mangling too:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\n#![no_main]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[no_mangle] // ensure that this symbol is called `main` in the output\npub extern fn main(_argc: i32, _argv: *const *const u8) -> i32 {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nIn many cases, you may need to manually link to the `compiler_builtins` crate\nwhen building a `no_std` binary. You may observe this via linker error messages\nsuch as \"```undefined reference to `__rust_probestack'```\".\n\n## More about the language items\n\nThe compiler currently makes a few assumptions about symbols which are\navailable in the executable to call. Normally these functions are provided by\nthe standard library, but without it you must define your own. These symbols\nare called \"language items\", and they each have an internal name, and then a\nsignature that an implementation must conform to.\n\nThe first of these functions, `rust_eh_personality`, is used by the failure\nmechanisms of the compiler. This is often mapped to GCC's personality function\n(see the [libstd implementation][unwind] for more information), but crates\nwhich do not trigger a panic can be assured that this function is never\ncalled. The language item's name is `eh_personality`.\n\n[unwind]: https://github.com/rust-lang/rust/blob/master/src/libpanic_unwind/gcc.rs\n\nThe second function, `rust_begin_panic`, is also used by the failure mechanisms of the\ncompiler. When a panic happens, this controls the message that's displayed on\nthe screen. While the language item's name is `panic_impl`, the symbol name is\n`rust_begin_panic`.\n\nFinally, a `eh_catch_typeinfo` static is needed for certain targets which\nimplement Rust panics on top of C++ exceptions.\n\n## List of all language items\n\nThis is a list of all language items in Rust along with where they are located in\nthe source code.\n\n- Primitives\n - `i8`: `libcore/num/mod.rs`\n - `i16`: `libcore/num/mod.rs`\n - `i32`: `libcore/num/mod.rs`\n - `i64`: `libcore/num/mod.rs`\n - `i128`: `libcore/num/mod.rs`\n - `isize`: `libcore/num/mod.rs`\n - `u8`: `libcore/num/mod.rs`\n - `u16`: `libcore/num/mod.rs`\n - `u32`: `libcore/num/mod.rs`\n - `u64`: `libcore/num/mod.rs`\n - `u128`: `libcore/num/mod.rs`\n - `usize`: `libcore/num/mod.rs`\n - `f32`: `libstd/f32.rs`\n - `f64`: `libstd/f64.rs`\n - `char`: `libcore/char.rs`\n - `slice`: `liballoc/slice.rs`\n - `str`: `liballoc/str.rs`\n - `const_ptr`: `libcore/ptr.rs`\n - `mut_ptr`: `libcore/ptr.rs`\n - `unsafe_cell`: `libcore/cell.rs`\n- Runtime\n - `start`: `libstd/rt.rs`\n - `eh_personality`: `libpanic_unwind/emcc.rs` (EMCC)\n - `eh_personality`: `libpanic_unwind/gcc.rs` (GNU)\n - `eh_personality`: `libpanic_unwind/seh.rs` (SEH)\n - `eh_catch_typeinfo`: `libpanic_unwind/emcc.rs` (EMCC)\n - `panic`: `libcore/panicking.rs`\n - `panic_bounds_check`: `libcore/panicking.rs`\n - `panic_impl`: `libcore/panicking.rs`\n - `panic_impl`: `libstd/panicking.rs`\n- Allocations\n - `owned_box`: `liballoc/boxed.rs`\n - `exchange_malloc`: `liballoc/heap.rs`\n - `box_free`: `liballoc/heap.rs`\n- Operands\n - `not`: `libcore/ops/bit.rs`\n - `bitand`: `libcore/ops/bit.rs`\n - `bitor`: `libcore/ops/bit.rs`\n - `bitxor`: `libcore/ops/bit.rs`\n - `shl`: `libcore/ops/bit.rs`\n - `shr`: `libcore/ops/bit.rs`\n - `bitand_assign`: `libcore/ops/bit.rs`\n - `bitor_assign`: `libcore/ops/bit.rs`\n - `bitxor_assign`: `libcore/ops/bit.rs`\n - `shl_assign`: `libcore/ops/bit.rs`\n - `shr_assign`: `libcore/ops/bit.rs`\n - `deref`: `libcore/ops/deref.rs`\n - `deref_mut`: `libcore/ops/deref.rs`\n - `index`: `libcore/ops/index.rs`\n - `index_mut`: `libcore/ops/index.rs`\n - `add`: `libcore/ops/arith.rs`\n - `sub`: `libcore/ops/arith.rs`\n - `mul`: `libcore/ops/arith.rs`\n - `div`: `libcore/ops/arith.rs`\n - `rem`: `libcore/ops/arith.rs`\n - `neg`: `libcore/ops/arith.rs`\n - `add_assign`: `libcore/ops/arith.rs`\n - `sub_assign`: `libcore/ops/arith.rs`\n - `mul_assign`: `libcore/ops/arith.rs`\n - `div_assign`: `libcore/ops/arith.rs`\n - `rem_assign`: `libcore/ops/arith.rs`\n - `eq`: `libcore/cmp.rs`\n - `ord`: `libcore/cmp.rs`\n- Functions\n - `fn`: `libcore/ops/function.rs`\n - `fn_mut`: `libcore/ops/function.rs`\n - `fn_once`: `libcore/ops/function.rs`\n - `generator_state`: `libcore/ops/generator.rs`\n - `generator`: `libcore/ops/generator.rs`\n- Other\n - `coerce_unsized`: `libcore/ops/unsize.rs`\n - `drop`: `libcore/ops/drop.rs`\n - `drop_in_place`: `libcore/ptr.rs`\n - `clone`: `libcore/clone.rs`\n - `copy`: `libcore/marker.rs`\n - `send`: `libcore/marker.rs`\n - `sized`: `libcore/marker.rs`\n - `unsize`: `libcore/marker.rs`\n - `sync`: `libcore/marker.rs`\n - `phantom_data`: `libcore/marker.rs`\n - `discriminant_kind`: `libcore/marker.rs`\n - `freeze`: `libcore/marker.rs`\n - `debug_trait`: `libcore/fmt/mod.rs`\n - `non_zero`: `libcore/nonzero.rs`\n - `arc`: `liballoc/sync.rs`\n - `rc`: `liballoc/rc.rs`\n" } , LintCompletion { label : "abi_msp430_interrupt" , description : "# `abi_msp430_interrupt`\n\nThe tracking issue for this feature is: [#38487]\n\n[#38487]: https://github.com/rust-lang/rust/issues/38487\n\n------------------------\n\nIn the MSP430 architecture, interrupt handlers have a special calling\nconvention. You can use the `\"msp430-interrupt\"` ABI to make the compiler apply\nthe right calling convention to the interrupt handlers you define.\n\n<!-- NOTE(ignore) this example is specific to the msp430 target -->\n\n``` rust,ignore\n#![feature(abi_msp430_interrupt)]\n#![no_std]\n\n// Place the interrupt handler at the appropriate memory address\n// (Alternatively, you can use `#[used]` and remove `pub` and `#[no_mangle]`)\n#[link_section = \"__interrupt_vector_10\"]\n#[no_mangle]\npub static TIM0_VECTOR: extern \"msp430-interrupt\" fn() = tim0;\n\n// The interrupt handler\nextern \"msp430-interrupt\" fn tim0() {\n // ..\n}\n```\n\n``` text\n$ msp430-elf-objdump -CD ./target/msp430/release/app\nDisassembly of section __interrupt_vector_10:\n\n0000fff2 <TIM0_VECTOR>:\n fff2: 00 c0 interrupt service routine at 0xc000\n\nDisassembly of section .text:\n\n0000c000 <int::tim0>:\n c000: 00 13 reti\n```\n" } , LintCompletion { label : "link_args" , description : "# `link_args`\n\nThe tracking issue for this feature is: [#29596]\n\n[#29596]: https://github.com/rust-lang/rust/issues/29596\n\n------------------------\n\nYou can tell `rustc` how to customize linking, and that is via the `link_args`\nattribute. This attribute is applied to `extern` blocks and specifies raw flags\nwhich need to get passed to the linker when producing an artifact. An example\nusage would be:\n\n```rust,no_run\n#![feature(link_args)]\n\n#[link_args = \"-foo -bar -baz\"]\nextern {}\n# fn main() {}\n```\n\nNote that this feature is currently hidden behind the `feature(link_args)` gate\nbecause this is not a sanctioned way of performing linking. Right now `rustc`\nshells out to the system linker (`gcc` on most systems, `link.exe` on MSVC), so\nit makes sense to provide extra command line arguments, but this will not\nalways be the case. In the future `rustc` may use LLVM directly to link native\nlibraries, in which case `link_args` will have no meaning. You can achieve the\nsame effect as the `link_args` attribute with the `-C link-args` argument to\n`rustc`.\n\nIt is highly recommended to *not* use this attribute, and rather use the more\nformal `#[link(...)]` attribute on `extern` blocks instead.\n" } , LintCompletion { label : "const_eval_limit" , description : "# `const_eval_limit`\n\nThe tracking issue for this feature is: [#67217]\n\n[#67217]: https://github.com/rust-lang/rust/issues/67217\n\nThe `const_eval_limit` allows someone to limit the evaluation steps the CTFE undertakes to evaluate a `const fn`.\n" } , LintCompletion { label : "negative_impls" , description : "# `negative_impls`\n\nThe tracking issue for this feature is [#68318].\n\n[#68318]: https://github.com/rust-lang/rust/issues/68318\n\n----\n\nWith the feature gate `negative_impls`, you can write negative impls as well as positive ones:\n\n```rust\n#![feature(negative_impls)]\ntrait DerefMut { }\nimpl<T: ?Sized> !DerefMut for &T { }\n```\n\nNegative impls indicate a semver guarantee that the given trait will not be implemented for the given types. Negative impls play an additional purpose for auto traits, described below.\n\nNegative impls have the following characteristics:\n\n* They do not have any items.\n* They must obey the orphan rules as if they were a positive impl.\n* They cannot \"overlap\" with any positive impls.\n\n## Semver interaction\n\nIt is a breaking change to remove a negative impl. Negative impls are a commitment not to implement the given trait for the named types.\n\n## Orphan and overlap rules\n\nNegative impls must obey the same orphan rules as a positive impl. This implies you cannot add a negative impl for types defined in upstream crates and so forth.\n\nSimilarly, negative impls cannot overlap with positive impls, again using the same \"overlap\" check that we ordinarily use to determine if two impls overlap. (Note that positive impls typically cannot overlap with one another either, except as permitted by specialization.)\n\n## Interaction with auto traits\n\nDeclaring a negative impl `impl !SomeAutoTrait for SomeType` for an\nauto-trait serves two purposes:\n\n* as with any trait, it declares that `SomeType` will never implement `SomeAutoTrait`;\n* it disables the automatic `SomeType: SomeAutoTrait` impl that would otherwise have been generated.\n\nNote that, at present, there is no way to indicate that a given type\ndoes not implement an auto trait *but that it may do so in the\nfuture*. For ordinary types, this is done by simply not declaring any\nimpl at all, but that is not an option for auto traits. A workaround\nis that one could embed a marker type as one of the fields, where the\nmarker type is `!AutoTrait`.\n\n## Immediate uses\n\nNegative impls are used to declare that `&T: !DerefMut` and `&mut T: !Clone`, as required to fix the soundness of `Pin` described in [#66544](https://github.com/rust-lang/rust/issues/66544).\n\nThis serves two purposes:\n\n* For proving the correctness of unsafe code, we can use that impl as evidence that no `DerefMut` or `Clone` impl exists.\n* It prevents downstream crates from creating such impls.\n" } , LintCompletion { label : "non_ascii_idents" , description : "# `non_ascii_idents`\n\nThe tracking issue for this feature is: [#55467]\n\n[#55467]: https://github.com/rust-lang/rust/issues/55467\n\n------------------------\n\nThe `non_ascii_idents` feature adds support for non-ASCII identifiers.\n\n## Examples\n\n```rust\n#![feature(non_ascii_idents)]\n\nconst ε: f64 = 0.00001f64;\nconst Π: f64 = 3.14f64;\n```\n\n## Changes to the language reference\n\n> **<sup>Lexer:<sup>** \n> IDENTIFIER : \n> XID_start XID_continue<sup>\\*</sup> \n> | `_` XID_continue<sup>+</sup> \n\nAn identifier is any nonempty Unicode string of the following form:\n\nEither\n\n * The first character has property [`XID_start`]\n * The remaining characters have property [`XID_continue`]\n\nOr\n\n * The first character is `_`\n * The identifier is more than one character, `_` alone is not an identifier\n * The remaining characters have property [`XID_continue`]\n\nthat does _not_ occur in the set of [strict keywords].\n\n> **Note**: [`XID_start`] and [`XID_continue`] as character properties cover the\n> character ranges used to form the more familiar C and Java language-family\n> identifiers.\n\n[`XID_start`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=\n[`XID_continue`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=\n[strict keywords]: ../../reference/keywords.md#strict-keywords\n" } , LintCompletion { label : "transparent_unions" , description : "# `transparent_unions`\n\nThe tracking issue for this feature is [#60405]\n\n[#60405]: https://github.com/rust-lang/rust/issues/60405\n\n----\n\nThe `transparent_unions` feature allows you mark `union`s as\n`#[repr(transparent)]`. A `union` may be `#[repr(transparent)]` in exactly the\nsame conditions in which a `struct` may be `#[repr(transparent)]` (generally,\nthis means the `union` must have exactly one non-zero-sized field). Some\nconcrete illustrations follow.\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `f32`.\n#[repr(transparent)]\nunion SingleFieldUnion {\n field: f32,\n}\n\n// This union has the same representation as `usize`.\n#[repr(transparent)]\nunion MultiFieldUnion {\n field: usize,\n nothing: (),\n}\n```\n\nFor consistency with transparent `struct`s, `union`s must have exactly one\nnon-zero-sized field. If all fields are zero-sized, the `union` must not be\n`#[repr(transparent)]`:\n\n```rust\n#![feature(transparent_unions)]\n\n// This (non-transparent) union is already valid in stable Rust:\npub union GoodUnion {\n pub nothing: (),\n}\n\n// Error: transparent union needs exactly one non-zero-sized field, but has 0\n// #[repr(transparent)]\n// pub union BadUnion {\n// pub nothing: (),\n// }\n```\n\nThe one exception is if the `union` is generic over `T` and has a field of type\n`T`, it may be `#[repr(transparent)]` even if `T` is a zero-sized type:\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `T`.\n#[repr(transparent)]\npub union GenericUnion<T: Copy> { // Unions with non-`Copy` fields are unstable.\n pub field: T,\n pub nothing: (),\n}\n\n// This is okay even though `()` is a zero-sized type.\npub const THIS_IS_OKAY: GenericUnion<()> = GenericUnion { field: () };\n```\n\nLike transarent `struct`s, a transparent `union` of type `U` has the same\nlayout, size, and ABI as its single non-ZST field. If it is generic over a type\n`T`, and all its fields are ZSTs except for exactly one field of type `T`, then\nit has the same layout and ABI as `T` (even if `T` is a ZST when monomorphized).\n\nLike transparent `struct`s, transparent `union`s are FFI-safe if and only if\ntheir underlying representation type is also FFI-safe.\n\nA `union` may not be eligible for the same nonnull-style optimizations that a\n`struct` or `enum` (with the same fields) are eligible for. Adding\n`#[repr(transparent)]` to `union` does not change this. To give a more concrete\nexample, it is unspecified whether `size_of::<T>()` is equal to\n`size_of::<Option<T>>()`, where `T` is a `union` (regardless of whether or not\nit is transparent). The Rust compiler is free to perform this optimization if\npossible, but is not required to, and different compiler versions may differ in\ntheir application of these optimizations.\n" } , LintCompletion { label : "box_syntax" , description : "# `box_syntax`\n\nThe tracking issue for this feature is: [#49733]\n\n[#49733]: https://github.com/rust-lang/rust/issues/49733\n\nSee also [`box_patterns`](box-patterns.md)\n\n------------------------\n\nCurrently the only stable way to create a `Box` is via the `Box::new` method.\nAlso it is not possible in stable Rust to destructure a `Box` in a match\npattern. The unstable `box` keyword can be used to create a `Box`. An example\nusage would be:\n\n```rust\n#![feature(box_syntax)]\n\nfn main() {\n let b = box 5;\n}\n```\n" } , LintCompletion { label : "repr128" , description : "# `repr128`\n\nThe tracking issue for this feature is: [#56071]\n\n[#56071]: https://github.com/rust-lang/rust/issues/56071\n\n------------------------\n\nThe `repr128` feature adds support for `#[repr(u128)]` on `enum`s.\n\n```rust\n#![feature(repr128)]\n\n#[repr(u128)]\nenum Foo {\n Bar(u64),\n}\n```\n" } , LintCompletion { label : "member_constraints" , description : "# `member_constraints`\n\nThe tracking issue for this feature is: [#61997]\n\n[#61997]: https://github.com/rust-lang/rust/issues/61997\n\n------------------------\n\nThe `member_constraints` feature gate lets you use `impl Trait` syntax with\nmultiple unrelated lifetime parameters.\n\nA simple example is:\n\n```rust\n#![feature(member_constraints)]\n\ntrait Trait<'a, 'b> { }\nimpl<T> Trait<'_, '_> for T {}\n\nfn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> impl Trait<'a, 'b> {\n (x, y)\n}\n\nfn main() { }\n```\n\nWithout the `member_constraints` feature gate, the above example is an\nerror because both `'a` and `'b` appear in the impl Trait bounds, but\nneither outlives the other.\n" } , LintCompletion { label : "link_cfg" , description : "# `link_cfg`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` language feature enables C-variadic functions to be\ndefined in Rust. The may be called both from within Rust and via FFI.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\npub unsafe extern \"C\" fn add(n: usize, mut args: ...) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "abi_ptx" , description : "# `abi_ptx`\n\nThe tracking issue for this feature is: [#38788]\n\n[#38788]: https://github.com/rust-lang/rust/issues/38788\n\n------------------------\n\nWhen emitting PTX code, all vanilla Rust functions (`fn`) get translated to\n\"device\" functions. These functions are *not* callable from the host via the\nCUDA API so a crate with only device functions is not too useful!\n\nOTOH, \"global\" functions *can* be called by the host; you can think of them\nas the real public API of your crate. To produce a global function use the\n`\"ptx-kernel\"` ABI.\n\n<!-- NOTE(ignore) this example is specific to the nvptx targets -->\n\n``` rust,ignore\n#![feature(abi_ptx)]\n#![no_std]\n\npub unsafe extern \"ptx-kernel\" fn global_function() {\n device_function();\n}\n\npub fn device_function() {\n // ..\n}\n```\n\n``` text\n$ xargo rustc --target nvptx64-nvidia-cuda --release -- --emit=asm\n\n$ cat $(find -name '*.s')\n//\n// Generated by LLVM NVPTX Back-End\n//\n\n.version 3.2\n.target sm_20\n.address_size 64\n\n // .globl _ZN6kernel15global_function17h46111ebe6516b382E\n\n.visible .entry _ZN6kernel15global_function17h46111ebe6516b382E()\n{\n\n\n ret;\n}\n\n // .globl _ZN6kernel15device_function17hd6a0e4993bbf3f78E\n.visible .func _ZN6kernel15device_function17hd6a0e4993bbf3f78E()\n{\n\n\n ret;\n}\n```\n" } , LintCompletion { label : "ffi_pure" , description : "# `ffi_pure`\n\nThe `#[ffi_pure]` attribute applies clang's `pure` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_pure]` functions shall have no effects except for its return\nvalue, which shall not change across two consecutive function calls with\nthe same parameters.\n\nApplying the `#[ffi_pure]` attribute to a function that violates these\nrequirements is undefined behavior.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination and loop optimizations. Some common examples of pure functions are\n`strlen` or `memcmp`.\n\nThese optimizations are only applicable when the compiler can prove that no\nprogram state observable by the `#[ffi_pure]` function has changed between calls\nof the function, which could alter the result. See also the `#[ffi_const]`\nattribute, which provides stronger guarantees regarding the allowable behavior\nof a function, enabling further optimization.\n\n## Pitfalls\n\nA `#[ffi_pure]` function can read global memory through the function\nparameters (e.g. pointers), globals, etc. `#[ffi_pure]` functions are not\nreferentially-transparent, and are therefore more relaxed than `#[ffi_const]`\nfunctions.\n\nHowever, accesing global memory through volatile or atomic reads can violate the\nrequirement that two consecutive function calls shall return the same value.\n\nA `pure` function that returns unit has no effect on the abstract machine's\nstate.\n\nA `#[ffi_pure]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `pure` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`pure` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_pure]`.\n\n\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacigdac.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_pure.htm\n" } , LintCompletion { label : "compiler_builtins" , description : "# `compiler_builtins`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "unboxed_closures" , description : "# `unboxed_closures`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`fn_traits`](../library-features/fn-traits.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `unboxed_closures` feature allows you to write functions using the `\"rust-call\"` ABI,\nrequired for implementing the [`Fn*`] family of traits. `\"rust-call\"` functions must have \nexactly one (non self) argument, a tuple representing the argument list.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n\nextern \"rust-call\" fn add_args(args: (u32, u32)) -> u32 {\n args.0 + args.1\n}\n\nfn main() {}\n```\n" } , LintCompletion { label : "arbitrary_enum_discriminant" , description : "# `arbitrary_enum_discriminant`\n\nThe tracking issue for this feature is: [#60553]\n\n[#60553]: https://github.com/rust-lang/rust/issues/60553\n\n------------------------\n\nThe `arbitrary_enum_discriminant` feature permits tuple-like and\nstruct-like enum variants with `#[repr(<int-type>)]` to have explicit discriminants.\n\n## Examples\n\n```rust\n#![feature(arbitrary_enum_discriminant)]\n\n#[allow(dead_code)]\n#[repr(u8)]\nenum Enum {\n Unit = 3,\n Tuple(u16) = 2,\n Struct {\n a: u8,\n b: u16,\n } = 1,\n}\n\nimpl Enum {\n fn tag(&self) -> u8 {\n unsafe { *(self as *const Self as *const u8) }\n }\n}\n\nassert_eq!(3, Enum::Unit.tag());\nassert_eq!(2, Enum::Tuple(5).tag());\nassert_eq!(1, Enum::Struct{a: 7, b: 11}.tag());\n```\n" } , LintCompletion { label : "marker_trait_attr" , description : "# `marker_trait_attr`\n\nThe tracking issue for this feature is: [#29864]\n\n[#29864]: https://github.com/rust-lang/rust/issues/29864\n\n------------------------\n\nNormally, Rust keeps you from adding trait implementations that could\noverlap with each other, as it would be ambiguous which to use. This\nfeature, however, carves out an exception to that rule: a trait can\nopt-in to having overlapping implementations, at the cost that those\nimplementations are not allowed to override anything (and thus the\ntrait itself cannot have any associated items, as they're pointless\nwhen they'd need to do the same thing for every type anyway).\n\n```rust\n#![feature(marker_trait_attr)]\n\n#[marker] trait CheapToClone: Clone {}\n\nimpl<T: Copy> CheapToClone for T {}\n\n// These could potentially overlap with the blanket implementation above,\n// so are only allowed because CheapToClone is a marker trait.\nimpl<T: CheapToClone, U: CheapToClone> CheapToClone for (T, U) {}\nimpl<T: CheapToClone> CheapToClone for std::ops::Range<T> {}\n\nfn cheap_clone<T: CheapToClone>(t: T) -> T {\n t.clone()\n}\n```\n\nThis is expected to replace the unstable `overlapping_marker_traits`\nfeature, which applied to all empty traits (without needing an opt-in).\n" } , LintCompletion { label : "plugin_registrar" , description : "# `plugin_registrar`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin`] and `rustc_private` features as well. For more details, see\ntheir docs.\n\n[`plugin`]: plugin.md\n\n------------------------\n" } , LintCompletion { label : "profiler_runtime" , description : "# `profiler_runtime`\n\nThe tracking issue for this feature is: [#42524](https://github.com/rust-lang/rust/issues/42524).\n\n------------------------\n" } , LintCompletion { label : "trait_alias" , description : "# `trait_alias`\n\nThe tracking issue for this feature is: [#41517]\n\n[#41517]: https://github.com/rust-lang/rust/issues/41517\n\n------------------------\n\nThe `trait_alias` feature adds support for trait aliases. These allow aliases\nto be created for one or more traits (currently just a single regular trait plus\nany number of auto-traits), and used wherever traits would normally be used as\neither bounds or trait objects.\n\n```rust\n#![feature(trait_alias)]\n\ntrait Foo = std::fmt::Debug + Send;\ntrait Bar = Foo + Sync;\n\n// Use trait alias as bound on type parameter.\nfn foo<T: Foo>(v: &T) {\n println!(\"{:?}\", v);\n}\n\npub fn main() {\n foo(&1);\n\n // Use trait alias for trait objects.\n let a: &Bar = &123;\n println!(\"{:?}\", a);\n let b = Box::new(456) as Box<dyn Foo>;\n println!(\"{:?}\", b);\n}\n```\n" } , LintCompletion { label : "try_blocks" , description : "# `try_blocks`\n\nThe tracking issue for this feature is: [#31436]\n\n[#31436]: https://github.com/rust-lang/rust/issues/31436\n\n------------------------\n\nThe `try_blocks` feature adds support for `try` blocks. A `try`\nblock creates a new scope one can use the `?` operator in.\n\n```rust,edition2018\n#![feature(try_blocks)]\n\nuse std::num::ParseIntError;\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"2\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert_eq!(result, Ok(6));\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"foo\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert!(result.is_err());\n```\n" } , LintCompletion { label : "box_patterns" , description : "# `box_patterns`\n\nThe tracking issue for this feature is: [#29641]\n\n[#29641]: https://github.com/rust-lang/rust/issues/29641\n\nSee also [`box_syntax`](box-syntax.md)\n\n------------------------\n\nBox patterns let you match on `Box<T>`s:\n\n\n```rust\n#![feature(box_patterns)]\n\nfn main() {\n let b = Some(Box::new(5));\n match b {\n Some(box n) if n < 0 => {\n println!(\"Box contains negative number {}\", n);\n },\n Some(box n) if n >= 0 => {\n println!(\"Box contains non-negative number {}\", n);\n },\n None => {\n println!(\"No box\");\n },\n _ => unreachable!()\n }\n}\n```\n" } , LintCompletion { label : "crate_visibility_modifier" , description : "# `crate_visibility_modifier`\n\nThe tracking issue for this feature is: [#53120]\n\n[#53120]: https://github.com/rust-lang/rust/issues/53120\n\n-----\n\nThe `crate_visibility_modifier` feature allows the `crate` keyword to be used\nas a visibility modifier synonymous to `pub(crate)`, indicating that a type\n(function, _&c._) is to be visible to the entire enclosing crate, but not to\nother crates.\n\n```rust\n#![feature(crate_visibility_modifier)]\n\ncrate struct Foo {\n bar: usize,\n}\n```\n" } , LintCompletion { label : "allocator_internals" , description : "# `allocator_internals`\n\nThis feature does not have a tracking issue, it is an unstable implementation\ndetail of the `global_allocator` feature not intended for use outside the\ncompiler.\n\n------------------------\n" } , LintCompletion { label : "intrinsics" , description : "# `intrinsics`\n\nThe tracking issue for this feature is: None.\n\nIntrinsics are never intended to be stable directly, but intrinsics are often\nexported in some sort of stable manner. Prefer using the stable interfaces to\nthe intrinsic directly when you can.\n\n------------------------\n\n\nThese are imported as if they were FFI functions, with the special\n`rust-intrinsic` ABI. For example, if one was in a freestanding\ncontext, but wished to be able to `transmute` between types, and\nperform efficient pointer arithmetic, one would import those functions\nvia a declaration like\n\n```rust\n#![feature(intrinsics)]\n# fn main() {}\n\nextern \"rust-intrinsic\" {\n fn transmute<T, U>(x: T) -> U;\n\n fn offset<T>(dst: *const T, offset: isize) -> *const T;\n}\n```\n\nAs with any other FFI functions, these are always `unsafe` to call.\n\n" } , LintCompletion { label : "custom_test_frameworks" , description : "# `custom_test_frameworks`\n\nThe tracking issue for this feature is: [#50297]\n\n[#50297]: https://github.com/rust-lang/rust/issues/50297\n\n------------------------\n\nThe `custom_test_frameworks` feature allows the use of `#[test_case]` and `#![test_runner]`.\nAny function, const, or static can be annotated with `#[test_case]` causing it to be aggregated (like `#[test]`)\nand be passed to the test runner determined by the `#![test_runner]` crate attribute.\n\n```rust\n#![feature(custom_test_frameworks)]\n#![test_runner(my_runner)]\n\nfn my_runner(tests: &[&i32]) {\n for t in tests {\n if **t == 0 {\n println!(\"PASSED\");\n } else {\n println!(\"FAILED\");\n }\n }\n}\n\n#[test_case]\nconst WILL_PASS: i32 = 0;\n\n#[test_case]\nconst WILL_FAIL: i32 = 4;\n```\n\n" } , LintCompletion { label : "external_doc" , description : "# `external_doc`\n\nThe tracking issue for this feature is: [#44732]\n\nThe `external_doc` feature allows the use of the `include` parameter to the `#[doc]` attribute, to\ninclude external files in documentation. Use the attribute in place of, or in addition to, regular\ndoc comments and `#[doc]` attributes, and `rustdoc` will load the given file when it renders\ndocumentation for your crate.\n\nWith the following files in the same directory:\n\n`external-doc.md`:\n\n```markdown\n# My Awesome Type\n\nThis is the documentation for this spectacular type.\n```\n\n`lib.rs`:\n\n```no_run (needs-external-files)\n#![feature(external_doc)]\n\n#[doc(include = \"external-doc.md\")]\npub struct MyAwesomeType;\n```\n\n`rustdoc` will load the file `external-doc.md` and use it as the documentation for the `MyAwesomeType`\nstruct.\n\nWhen locating files, `rustdoc` will base paths in the `src/` directory, as if they were alongside the\n`lib.rs` for your crate. So if you want a `docs/` folder to live alongside the `src/` directory,\nstart your paths with `../docs/` for `rustdoc` to properly find the file.\n\nThis feature was proposed in [RFC #1990] and initially implemented in PR [#44781].\n\n[#44732]: https://github.com/rust-lang/rust/issues/44732\n[RFC #1990]: https://github.com/rust-lang/rfcs/pull/1990\n[#44781]: https://github.com/rust-lang/rust/pull/44781\n" } , LintCompletion { label : "rustc_attrs" , description : "# `rustc_attrs`\n\nThis feature has no tracking issue, and is therefore internal to\nthe compiler, not being intended for general use.\n\nNote: `rustc_attrs` enables many rustc-internal attributes and this page\nonly discuss a few of them.\n\n------------------------\n\nThe `rustc_attrs` feature allows debugging rustc type layouts by using\n`#[rustc_layout(...)]` to debug layout at compile time (it even works\nwith `cargo check`) as an alternative to `rustc -Z print-type-sizes`\nthat is way more verbose.\n\nOptions provided by `#[rustc_layout(...)]` are `debug`, `size`, `abi`.\nNote that it only work best with sized type without generics.\n\n## Examples\n\n```rust,ignore\n#![feature(rustc_attrs)]\n\n#[rustc_layout(abi, size)]\npub enum X {\n Y(u8, u8, u8),\n Z(isize),\n}\n```\n\nWhen that is compiled, the compiler will error with something like\n\n```text\nerror: abi: Aggregate { sized: true }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: size: Size { raw: 16 }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: aborting due to 2 previous errors\n```\n" } , LintCompletion { label : "profiler_runtime_lib" , description : "# `profiler_runtime_lib`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fmt_internals" , description : "# `fmt_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_io_internals" , description : "# `libstd_io_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "dec2flt" , description : "# `dec2flt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "try_trait" , description : "# `try_trait`\n\nThe tracking issue for this feature is: [#42327]\n\n[#42327]: https://github.com/rust-lang/rust/issues/42327\n\n------------------------\n\nThis introduces a new trait `Try` for extending the `?` operator to types\nother than `Result` (a part of [RFC 1859]). The trait provides the canonical\nway to _view_ a type in terms of a success/failure dichotomy. This will\nallow `?` to supplant the `try_opt!` macro on `Option` and the `try_ready!`\nmacro on `Poll`, among other things.\n\n[RFC 1859]: https://github.com/rust-lang/rfcs/pull/1859\n\nHere's an example implementation of the trait:\n\n```rust,ignore\n/// A distinct type to represent the `None` value of an `Option`.\n///\n/// This enables using the `?` operator on `Option`; it's rarely useful alone.\n#[derive(Debug)]\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\npub struct None { _priv: () }\n\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\nimpl<T> ops::Try for Option<T> {\n type Ok = T;\n type Error = None;\n\n fn into_result(self) -> Result<T, None> {\n self.ok_or(None { _priv: () })\n }\n\n fn from_ok(v: T) -> Self {\n Some(v)\n }\n\n fn from_error(_: None) -> Self {\n None\n }\n}\n```\n\nNote the `Error` associated type here is a new marker. The `?` operator\nallows interconversion between different `Try` implementers only when\nthe error type can be converted `Into` the error type of the enclosing\nfunction (or catch block). Having a distinct error type (as opposed to\njust `()`, or similar) restricts this to where it's semantically meaningful.\n" } , LintCompletion { label : "windows_handle" , description : "# `windows_handle`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_stdio" , description : "# `windows_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "int_error_internals" , description : "# `int_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_panic" , description : "# `core_panic`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_bignum" , description : "# `core_private_bignum`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "derive_eq" , description : "# `derive_eq`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "thread_local_internals" , description : "# `thread_local_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "print_internals" , description : "# `print_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "c_void_variant" , description : "# `c_void_variant`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fn_traits" , description : "# `fn_traits`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`unboxed_closures`](../language-features/unboxed-closures.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `fn_traits` feature allows for implementation of the [`Fn*`] traits\nfor creating custom closure-like types.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n#![feature(fn_traits)]\n\nstruct Adder {\n a: u32\n}\n\nimpl FnOnce<(u32, )> for Adder {\n type Output = u32;\n extern \"rust-call\" fn call_once(self, b: (u32, )) -> Self::Output {\n self.a + b.0\n }\n}\n\nfn main() {\n let adder = Adder { a: 3 };\n assert_eq!(adder(2), 5);\n}\n```\n" } , LintCompletion { label : "rt" , description : "# `rt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "default_free_fn" , description : "# `default_free_fn`\n\nThe tracking issue for this feature is: [#73014]\n\n[#73014]: https://github.com/rust-lang/rust/issues/73014\n\n------------------------\n\nAdds a free `default()` function to the `std::default` module. This function\njust forwards to [`Default::default()`], but may remove repetition of the word\n\"default\" from the call site.\n\nHere is an example:\n\n```rust\n#![feature(default_free_fn)]\nuse std::default::default;\n\n#[derive(Default)]\nstruct AppConfig {\n foo: FooConfig,\n bar: BarConfig,\n}\n\n#[derive(Default)]\nstruct FooConfig {\n foo: i32,\n}\n\n#[derive(Default)]\nstruct BarConfig {\n bar: f32,\n baz: u8,\n}\n\nfn main() {\n let options = AppConfig {\n foo: default(),\n bar: BarConfig {\n bar: 10.1,\n ..default()\n },\n };\n}\n```\n" } , LintCompletion { label : "update_panic_count" , description : "# `update_panic_count`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "str_internals" , description : "# `str_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fd" , description : "# `fd`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "char_error_internals" , description : "# `char_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_intrinsics" , description : "# `core_intrinsics`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_c" , description : "# `windows_c`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_sys_internals" , description : "# `libstd_sys_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fd_read" , description : "# `fd_read`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` library feature exposes the `VaList` structure,\nRust's analogue of C's `va_list` type.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\nuse std::ffi::VaList;\n\npub unsafe extern \"C\" fn vadd(n: usize, mut args: VaList) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "allocator_api" , description : "# `allocator_api`\n\nThe tracking issue for this feature is [#32838]\n\n[#32838]: https://github.com/rust-lang/rust/issues/32838\n\n------------------------\n\nSometimes you want the memory for one collection to use a different\nallocator than the memory for another collection. In this case,\nreplacing the global allocator is not a workable option. Instead,\nyou need to pass in an instance of an `AllocRef` to each collection\nfor which you want a custom allocator.\n\nTBD\n" } , LintCompletion { label : "flt2dec" , description : "# `flt2dec`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "global_asm" , description : "# `global_asm`\n\nThe tracking issue for this feature is: [#35119]\n\n[#35119]: https://github.com/rust-lang/rust/issues/35119\n\n------------------------\n\nThe `global_asm!` macro allows the programmer to write arbitrary\nassembly outside the scope of a function body, passing it through\n`rustc` and `llvm` to the assembler. The macro is a no-frills\ninterface to LLVM's concept of [module-level inline assembly]. That is,\nall caveats applicable to LLVM's module-level inline assembly apply\nto `global_asm!`.\n\n[module-level inline assembly]: http://llvm.org/docs/LangRef.html#module-level-inline-assembly\n\n`global_asm!` fills a role not currently satisfied by either `asm!`\nor `#[naked]` functions. The programmer has _all_ features of the\nassembler at their disposal. The linker will expect to resolve any\nsymbols defined in the inline assembly, modulo any symbols marked as\nexternal. It also means syntax for directives and assembly follow the\nconventions of the assembler in your toolchain.\n\nA simple usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# you also need relevant target_arch cfgs\nglobal_asm!(include_str!(\"something_neato.s\"));\n```\n\nAnd a more complicated usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# #![cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n\npub mod sally {\n global_asm!(r#\"\n .global foo\n foo:\n jmp baz\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn baz() {}\n}\n\n// the symbols `foo` and `bar` are global, no matter where\n// `global_asm!` was used.\nextern \"C\" {\n fn foo();\n fn bar();\n}\n\npub mod harry {\n global_asm!(r#\"\n .global bar\n bar:\n jmp quux\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn quux() {}\n}\n```\n\nYou may use `global_asm!` multiple times, anywhere in your crate, in\nwhatever way suits you. The effect is as if you concatenated all\nusages and placed the larger, single usage in the crate root.\n\n------------------------\n\nIf you don't need quite as much power and flexibility as\n`global_asm!` provides, and you don't mind restricting your inline\nassembly to `fn` bodies only, you might try the\n[asm](asm.md) feature instead.\n" } , LintCompletion { label : "asm" , description : "# `asm`\n\nThe tracking issue for this feature is: [#72016]\n\n[#72016]: https://github.com/rust-lang/rust/issues/72016\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `asm!` macro.\n\n# Guide-level explanation\n[guide-level-explanation]: #guide-level-explanation\n\nRust provides support for inline assembly via the `asm!` macro.\nIt can be used to embed handwritten assembly in the assembly output generated by the compiler.\nGenerally this should not be necessary, but might be where the required performance or timing\ncannot be otherwise achieved. Accessing low level hardware primitives, e.g. in kernel code, may also demand this functionality.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but other architectures are also supported.\n\nInline assembly is currently supported on the following architectures:\n- x86 and x86-64\n- ARM\n- AArch64\n- RISC-V\n- NVPTX\n- Hexagon\n\n## Basic usage\n\nLet us start with the simplest possible example:\n\n```rust,allow_fail\n# #![feature(asm)]\nunsafe {\n asm!(\"nop\");\n}\n```\n\nThis will insert a NOP (no operation) instruction into the assembly generated by the compiler.\nNote that all `asm!` invocations have to be inside an `unsafe` block, as they could insert\narbitrary instructions and break various invariants. The instructions to be inserted are listed\nin the first argument of the `asm!` macro as a string literal.\n\n## Inputs and outputs\n\nNow inserting an instruction that does nothing is rather boring. Let us do something that\nactually acts on data:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64;\nunsafe {\n asm!(\"mov {}, 5\", out(reg) x);\n}\nassert_eq!(x, 5);\n```\n\nThis will write the value `5` into the `u64` variable `x`.\nYou can see that the string literal we use to specify instructions is actually a template string.\nIt is governed by the same rules as Rust [format strings][format-syntax].\nThe arguments that are inserted into the template however look a bit different then you may\nbe familiar with. First we need to specify if the variable is an input or an output of the\ninline assembly. In this case it is an output. We declared this by writing `out`.\nWe also need to specify in what kind of register the assembly expects the variable.\nIn this case we put it in an arbitrary general purpose register by specifying `reg`.\nThe compiler will choose an appropriate register to insert into\nthe template and will read the variable from there after the inline assembly finishes executing.\n\nLet us see another example that also uses an input:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet i: u64 = 3;\nlet o: u64;\nunsafe {\n asm!(\n \"mov {0}, {1}\",\n \"add {0}, {number}\",\n out(reg) o,\n in(reg) i,\n number = const 5,\n );\n}\nassert_eq!(o, 8);\n```\n\nThis will add `5` to the input in variable `i` and write the result to variable `o`.\nThe particular way this assembly does this is first copying the value from `i` to the output,\nand then adding `5` to it.\n\nThe example shows a few things:\n\nFirst, we can see that `asm!` allows multiple template string arguments; each\none is treated as a separate line of assembly code, as if they were all joined\ntogether with newlines between them. This makes it easy to format assembly\ncode.\n\nSecond, we can see that inputs are declared by writing `in` instead of `out`.\n\nThird, one of our operands has a type we haven't seen yet, `const`.\nThis tells the compiler to expand this argument to value directly inside the assembly template.\nThis is only possible for constants and literals.\n\nFourth, we can see that we can specify an argument number, or name as in any format string.\nFor inline assembly templates this is particularly useful as arguments are often used more than once.\nFor more complex inline assembly using this facility is generally recommended, as it improves\nreadability, and allows reordering instructions without changing the argument order.\n\nWe can further refine the above example to avoid the `mov` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u64 = 3;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x, number = const 5);\n}\nassert_eq!(x, 8);\n```\n\nWe can see that `inout` is used to specify an argument that is both input and output.\nThis is different from specifying an input and output separately in that it is guaranteed to assign both to the same register.\n\nIt is also possible to specify different variables for the input and output parts of an `inout` operand:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64 = 3;\nlet y: u64;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x => y, number = const 5);\n}\nassert_eq!(y, 8);\n```\n\n## Late output operands\n\nThe Rust compiler is conservative with its allocation of operands. It is assumed that an `out`\ncan be written at any time, and can therefore not share its location with any other argument.\nHowever, to guarantee optimal performance it is important to use as few registers as possible,\nso they won't have to be saved and reloaded around the inline assembly block.\nTo achieve this Rust provides a `lateout` specifier. This can be used on any output that is\nwritten only after all inputs have been consumed.\nThere is also a `inlateout` variant of this specifier.\n\nHere is an example where `inlateout` *cannot* be used:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nlet c: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n \"add {0}, {2}\",\n inout(reg) a,\n in(reg) b,\n in(reg) c,\n );\n}\nassert_eq!(a, 12);\n```\n\nHere the compiler is free to allocate the same register for inputs `b` and `c` since it knows they have the same value. However it must allocate a separate register for `a` since it uses `inout` and not `inlateout`. If `inlateout` was used, then `a` and `c` could be allocated to the same register, in which case the first instruction to overwrite the value of `c` and cause the assembly code to produce the wrong result.\n\nHowever the following example can use `inlateout` since the output is only modified after all input registers have been read:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\"add {0}, {1}\", inlateout(reg) a, in(reg) b);\n}\nassert_eq!(a, 8);\n```\n\nAs you can see, this assembly fragment will still work correctly if `a` and `b` are assigned to the same register.\n\n## Explicit register operands\n\nSome instructions require that the operands be in a specific register.\nTherefore, Rust inline assembly provides some more specific constraint specifiers.\nWhile `reg` is generally available on any architecture, these are highly architecture specific. E.g. for x86 the general purpose registers `eax`, `ebx`, `ecx`, `edx`, `ebp`, `esi`, and `edi`\namong others can be addressed by their name.\n\n```rust,allow_fail,no_run\n# #![feature(asm)]\nlet cmd = 0xd1;\nunsafe {\n asm!(\"out 0x64, eax\", in(\"eax\") cmd);\n}\n```\n\nIn this example we call the `out` instruction to output the content of the `cmd` variable\nto port `0x64`. Since the `out` instruction only accepts `eax` (and its sub registers) as operand\nwe had to use the `eax` constraint specifier.\n\nNote that unlike other operand types, explicit register operands cannot be used in the template string: you can't use `{}` and should write the register name directly instead. Also, they must appear at the end of the operand list after all other operand types.\n\nConsider this example which uses the x86 `mul` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nfn mul(a: u64, b: u64) -> u128 {\n let lo: u64;\n let hi: u64;\n\n unsafe {\n asm!(\n // The x86 mul instruction takes rax as an implicit input and writes\n // the 128-bit result of the multiplication to rax:rdx.\n \"mul {}\",\n in(reg) a,\n inlateout(\"rax\") b => lo,\n lateout(\"rdx\") hi\n );\n }\n\n ((hi as u128) << 64) + lo as u128\n}\n```\n\nThis uses the `mul` instruction to multiply two 64-bit inputs with a 128-bit result.\nThe only explicit operand is a register, that we fill from the variable `a`.\nThe second operand is implicit, and must be the `rax` register, which we fill from the variable `b`.\nThe lower 64 bits of the result are stored in `rax` from which we fill the variable `lo`.\nThe higher 64 bits are stored in `rdx` from which we fill the variable `hi`.\n\n## Clobbered registers\n\nIn many cases inline assembly will modify state that is not needed as an output.\nUsually this is either because we have to use a scratch register in the assembly,\nor instructions modify state that we don't need to further examine.\nThis state is generally referred to as being \"clobbered\".\nWe need to tell the compiler about this since it may need to save and restore this state\naround the inline assembly block.\n\n```rust,allow_fail\n# #![feature(asm)]\nlet ebx: u32;\nlet ecx: u32;\n\nunsafe {\n asm!(\n \"cpuid\",\n // EAX 4 selects the \"Deterministic Cache Parameters\" CPUID leaf\n inout(\"eax\") 4 => _,\n // ECX 0 selects the L0 cache information.\n inout(\"ecx\") 0 => ecx,\n lateout(\"ebx\") ebx,\n lateout(\"edx\") _,\n );\n}\n\nprintln!(\n \"L1 Cache: {}\",\n ((ebx >> 22) + 1) * (((ebx >> 12) & 0x3ff) + 1) * ((ebx & 0xfff) + 1) * (ecx + 1)\n);\n```\n\nIn the example above we use the `cpuid` instruction to get the L1 cache size.\nThis instruction writes to `eax`, `ebx`, `ecx`, and `edx`, but for the cache size we only care about the contents of `ebx` and `ecx`.\n\nHowever we still need to tell the compiler that `eax` and `edx` have been modified so that it can save any values that were in these registers before the asm. This is done by declaring these as outputs but with `_` instead of a variable name, which indicates that the output value is to be discarded.\n\nThis can also be used with a general register class (e.g. `reg`) to obtain a scratch register for use inside the asm code:\n\n```rust,allow_fail\n# #![feature(asm)]\n// Multiply x by 6 using shifts and adds\nlet mut x: u64 = 4;\nunsafe {\n asm!(\n \"mov {tmp}, {x}\",\n \"shl {tmp}, 1\",\n \"shl {x}, 2\",\n \"add {x}, {tmp}\",\n x = inout(reg) x,\n tmp = out(reg) _,\n );\n}\nassert_eq!(x, 4 * 6);\n```\n\n## Symbol operands\n\nA special operand type, `sym`, allows you to use the symbol name of a `fn` or `static` in inline assembly code.\nThis allows you to call a function or access a global variable without needing to keep its address in a register.\n\n```rust,allow_fail\n# #![feature(asm)]\nextern \"C\" fn foo(arg: i32) {\n println!(\"arg = {}\", arg);\n}\n\nfn call_foo(arg: i32) {\n unsafe {\n asm!(\n \"call {}\",\n sym foo,\n // 1st argument in rdi, which is caller-saved\n inout(\"rdi\") arg => _,\n // All caller-saved registers must be marked as clobberred\n out(\"rax\") _, out(\"rcx\") _, out(\"rdx\") _, out(\"rsi\") _,\n out(\"r8\") _, out(\"r9\") _, out(\"r10\") _, out(\"r11\") _,\n out(\"xmm0\") _, out(\"xmm1\") _, out(\"xmm2\") _, out(\"xmm3\") _,\n out(\"xmm4\") _, out(\"xmm5\") _, out(\"xmm6\") _, out(\"xmm7\") _,\n out(\"xmm8\") _, out(\"xmm9\") _, out(\"xmm10\") _, out(\"xmm11\") _,\n out(\"xmm12\") _, out(\"xmm13\") _, out(\"xmm14\") _, out(\"xmm15\") _,\n )\n }\n}\n```\n\nNote that the `fn` or `static` item does not need to be public or `#[no_mangle]`:\nthe compiler will automatically insert the appropriate mangled symbol name into the assembly code.\n\n## Register template modifiers\n\nIn some cases, fine control is needed over the way a register name is formatted when inserted into the template string. This is needed when an architecture's assembly language has several names for the same register, each typically being a \"view\" over a subset of the register (e.g. the low 32 bits of a 64-bit register).\n\nBy default the compiler will always choose the name that refers to the full register size (e.g. `rax` on x86-64, `eax` on x86, etc).\n\nThis default can be overriden by using modifiers on the template string operands, just like you would with format strings:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u16 = 0xab;\n\nunsafe {\n asm!(\"mov {0:h}, {0:l}\", inout(reg_abcd) x);\n}\n\nassert_eq!(x, 0xabab);\n```\n\nIn this example, we use the `reg_abcd` register class to restrict the register allocator to the 4 legacy x86 register (`ax`, `bx`, `cx`, `dx`) of which the first two bytes can be addressed independently.\n\nLet us assume that the register allocator has chosen to allocate `x` in the `ax` register.\nThe `h` modifier will emit the register name for the high byte of that register and the `l` modifier will emit the register name for the low byte. The asm code will therefore be expanded as `mov ah, al` which copies the low byte of the value into the high byte.\n\nIf you use a smaller data type (e.g. `u16`) with an operand and forget the use template modifiers, the compiler will emit a warning and suggest the correct modifier to use.\n\n## Options\n\nBy default, an inline assembly block is treated the same way as an external FFI function call with a custom calling convention: it may read/write memory, have observable side effects, etc. However in many cases, it is desirable to give the compiler more information about what the assembly code is actually doing so that it can optimize better.\n\nLet's take our previous example of an `add` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n inlateout(reg) a, in(reg) b,\n options(pure, nomem, nostack),\n );\n}\nassert_eq!(a, 8);\n```\n\nOptions can be provided as an optional final argument to the `asm!` macro. We specified three options here:\n- `pure` means that the asm code has no observable side effects and that its output depends only on its inputs. This allows the compiler optimizer to call the inline asm fewer times or even eliminate it entirely.\n- `nomem` means that the asm code does not read or write to memory. By default the compiler will assume that inline assembly can read or write any memory address that is accessible to it (e.g. through a pointer passed as an operand, or a global).\n- `nostack` means that the asm code does not push any data onto the stack. This allows the compiler to use optimizations such as the stack red zone on x86-64 to avoid stack pointer adjustments.\n\nThese allow the compiler to better optimize code using `asm!`, for example by eliminating pure `asm!` blocks whose outputs are not needed.\n\nSee the reference for the full list of available options and their effects.\n\n# Reference-level explanation\n[reference-level-explanation]: #reference-level-explanation\n\nInline assembler is implemented as an unsafe macro `asm!()`.\nThe first argument to this macro is a template string literal used to build the final assembly.\nThe following arguments specify input and output operands.\nWhen required, options are specified as the final argument.\n\nThe following ABNF specifies the general syntax:\n\n```ignore\ndir_spec := \"in\" / \"out\" / \"lateout\" / \"inout\" / \"inlateout\"\nreg_spec := <register class> / \"<explicit register>\"\noperand_expr := expr / \"_\" / expr \"=>\" expr / expr \"=>\" \"_\"\nreg_operand := dir_spec \"(\" reg_spec \")\" operand_expr\noperand := reg_operand / \"const\" const_expr / \"sym\" path\noption := \"pure\" / \"nomem\" / \"readonly\" / \"preserves_flags\" / \"noreturn\" / \"att_syntax\"\noptions := \"options(\" option *[\",\" option] [\",\"] \")\"\nasm := \"asm!(\" format_string *(\",\" format_string) *(\",\" [ident \"=\"] operand) [\",\" options] [\",\"] \")\"\n```\n\nThe macro will initially be supported only on ARM, AArch64, Hexagon, x86, x86-64 and RISC-V targets. Support for more targets may be added in the future. The compiler will emit an error if `asm!` is used on an unsupported target.\n\n[format-syntax]: https://doc.rust-lang.org/std/fmt/#syntax\n\n## Template string arguments\n\nThe assembler template uses the same syntax as [format strings][format-syntax] (i.e. placeholders are specified by curly braces). The corresponding arguments are accessed in order, by index, or by name. However, implicit named arguments (introduced by [RFC #2795][rfc-2795]) are not supported.\n\nAn `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code. All template string arguments must appear before any other arguments.\n\nAs with format strings, named arguments must appear after positional arguments. Explicit register operands must appear at the end of the operand list, after named arguments if any.\n\nExplicit register operands cannot be used by placeholders in the template string. All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.\n\nThe exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler.\n\nThe 5 targets specified in this RFC (x86, ARM, AArch64, RISC-V, Hexagon) all use the assembly code syntax of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior.\n\n[rfc-2795]: https://github.com/rust-lang/rfcs/pull/2795\n\n## Operand type\n\nSeveral types of operands are supported:\n\n* `in(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - The allocated register must contain the same value at the end of the asm code (except if a `lateout` is allocated to the same register).\n* `out(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain an undefined value at the start of the asm code.\n - `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n* `lateout(<reg>) <expr>`\n - Identical to `out` except that the register allocator can reuse a register allocated to an `in`.\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `inout(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register is written to at the end of the asm code.\n* `inout(<reg>) <in expr> => <out expr>`\n - Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`.\n - `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n - `<in expr>` and `<out expr>` may have different types.\n* `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>`\n - Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`).\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `const <expr>`\n - `<expr>` must be an integer or floating-point constant expression.\n - The value of the expression is formatted as a string and substituted directly into the asm template string.\n* `sym <path>`\n - `<path>` must refer to a `fn` or `static`.\n - A mangled symbol name referring to the item is substituted into the asm template string.\n - The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).\n - `<path>` is allowed to point to a `#[thread_local]` static, in which case the asm code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.\n\nOperand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output.\n\n## Register operands\n\nInput and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `\"eax\"`) while register classes are specified as identifiers (e.g. `reg`). Using string literals for register names enables support for architectures that use special characters in register names, such as MIPS (`$0`, `$1`, etc).\n\nNote that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register. It is a compile-time error to use the same explicit register for two input operands or two output operands. Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.\n\nOnly the following types are allowed as operands for inline assembly:\n- Integers (signed and unsigned)\n- Floating-point numbers\n- Pointers (thin only)\n- Function pointers\n- SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM).\n\nHere is the list of currently supported register classes:\n\n| Architecture | Register class | Registers | LLVM constraint code |\n| ------------ | -------------- | --------- | -------------------- |\n| x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `r[8-15]` (x86-64 only) | `r` |\n| x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` |\n| x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` |\n| x86-64 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `r[8-15]b`, `ah`\\*, `bh`\\*, `ch`\\*, `dh`\\* | `q` |\n| x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` |\n| x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` |\n| x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` |\n| x86 | `kreg` | `k[1-7]` | `Yk` |\n| AArch64 | `reg` | `x[0-28]`, `x30` | `r` |\n| AArch64 | `vreg` | `v[0-31]` | `w` |\n| AArch64 | `vreg_low16` | `v[0-15]` | `x` |\n| ARM | `reg` | `r[0-5]` `r7`\\*, `r[8-10]`, `r11`\\*, `r12`, `r14` | `r` |\n| ARM (Thumb) | `reg_thumb` | `r[0-r7]` | `l` |\n| ARM (ARM) | `reg_thumb` | `r[0-r10]`, `r12`, `r14` | `l` |\n| ARM | `sreg` | `s[0-31]` | `t` |\n| ARM | `sreg_low16` | `s[0-15]` | `x` |\n| ARM | `dreg` | `d[0-31]` | `w` |\n| ARM | `dreg_low16` | `d[0-15]` | `t` |\n| ARM | `dreg_low8` | `d[0-8]` | `x` |\n| ARM | `qreg` | `q[0-15]` | `w` |\n| ARM | `qreg_low8` | `q[0-7]` | `t` |\n| ARM | `qreg_low4` | `q[0-3]` | `x` |\n| NVPTX | `reg16` | None\\* | `h` |\n| NVPTX | `reg32` | None\\* | `r` |\n| NVPTX | `reg64` | None\\* | `l` |\n| RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` |\n| RISC-V | `freg` | `f[0-31]` | `f` |\n| Hexagon | `reg` | `r[0-28]` | `r` |\n\n> **Note**: On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.\n>\n> Note #2: On x86-64 the high byte registers (e.g. `ah`) are only available when used as an explicit register. Specifying the `reg_byte` register class for an operand will always allocate a low byte register.\n>\n> Note #3: NVPTX doesn't have a fixed register set, so named registers are not supported.\n>\n> Note #4: On ARM the frame pointer is either `r7` or `r11` depending on the platform.\n\nAdditional register classes may be added in the future based on demand (e.g. MMX, x87, etc).\n\nEach register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled.\n\n| Architecture | Register class | Target feature | Allowed types |\n| ------------ | -------------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `i16`, `i32`, `f32` |\n| x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` |\n| x86 | `reg_byte` | None | `i8` |\n| x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` |\n| x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` <br> `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8` |\n| x86 | `kreg` | `axv512f` | `i8`, `i16` |\n| x86 | `kreg` | `axv512bw` | `i32`, `i64` |\n| AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| AArch64 | `vreg` | `fp` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, <br> `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| ARM | `sreg` | `vfp2` | `i32`, `f32` |\n| ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` |\n| ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` |\n| NVPTX | `reg16` | None | `i8`, `i16` |\n| NVPTX | `reg32` | None | `i8`, `i16`, `i32`, `f32` |\n| NVPTX | `reg64` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V | `freg` | `f` | `f32` |\n| RISC-V | `freg` | `d` | `f64` |\n| Hexagon | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n\n> **Note**: For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target).\n\nIf a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture.\n\nWhen separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types.\n\n## Register names\n\nSome registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases:\n\n| Architecture | Base register | Aliases |\n| ------------ | ------------- | ------- |\n| x86 | `ax` | `eax`, `rax` |\n| x86 | `bx` | `ebx`, `rbx` |\n| x86 | `cx` | `ecx`, `rcx` |\n| x86 | `dx` | `edx`, `rdx` |\n| x86 | `si` | `esi`, `rsi` |\n| x86 | `di` | `edi`, `rdi` |\n| x86 | `bp` | `bpl`, `ebp`, `rbp` |\n| x86 | `sp` | `spl`, `esp`, `rsp` |\n| x86 | `ip` | `eip`, `rip` |\n| x86 | `st(0)` | `st` |\n| x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` |\n| x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` |\n| AArch64 | `x[0-30]` | `w[0-30]` |\n| AArch64 | `x29` | `fp` |\n| AArch64 | `x30` | `lr` |\n| AArch64 | `sp` | `wsp` |\n| AArch64 | `xzr` | `wzr` |\n| AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` |\n| ARM | `r[0-3]` | `a[1-4]` |\n| ARM | `r[4-9]` | `v[1-6]` |\n| ARM | `r9` | `rfp` |\n| ARM | `r10` | `sl` |\n| ARM | `r11` | `fp` |\n| ARM | `r12` | `ip` |\n| ARM | `r13` | `sp` |\n| ARM | `r14` | `lr` |\n| ARM | `r15` | `pc` |\n| RISC-V | `x0` | `zero` |\n| RISC-V | `x1` | `ra` |\n| RISC-V | `x2` | `sp` |\n| RISC-V | `x3` | `gp` |\n| RISC-V | `x4` | `tp` |\n| RISC-V | `x[5-7]` | `t[0-2]` |\n| RISC-V | `x8` | `fp`, `s0` |\n| RISC-V | `x9` | `s1` |\n| RISC-V | `x[10-17]` | `a[0-7]` |\n| RISC-V | `x[18-27]` | `s[2-11]` |\n| RISC-V | `x[28-31]` | `t[3-6]` |\n| RISC-V | `f[0-7]` | `ft[0-7]` |\n| RISC-V | `f[8-9]` | `fs[0-1]` |\n| RISC-V | `f[10-17]` | `fa[0-7]` |\n| RISC-V | `f[18-27]` | `fs[2-11]` |\n| RISC-V | `f[28-31]` | `ft[8-11]` |\n| Hexagon | `r29` | `sp` |\n| Hexagon | `r30` | `fr` |\n| Hexagon | `r31` | `lr` |\n\nSome registers cannot be used for input or output operands:\n\n| Architecture | Unsupported register | Reason |\n| ------------ | -------------------- | ------ |\n| All | `sp` | The stack pointer must be restored to its original value at the end of an asm code block. |\n| All | `bp` (x86), `x29` (AArch64), `x8` (RISC-V), `fr` (Hexagon) | The frame pointer cannot be used as an input or output. |\n| ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output. |\n| ARM | `r6` | `r6` is used internally by LLVM as a base pointer and therefore cannot be used as an input or output. |\n| x86 | `k0` | This is a constant zero register which can't be modified. |\n| x86 | `ip` | This is the program counter, not a real register. |\n| x86 | `mm[0-7]` | MMX registers are not currently supported (but may be in the future). |\n| x86 | `st([0-7])` | x87 registers are not currently supported (but may be in the future). |\n| AArch64 | `xzr` | This is a constant zero register which can't be modified. |\n| ARM | `pc` | This is the program counter, not a real register. |\n| RISC-V | `x0` | This is a constant zero register which can't be modified. |\n| RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. |\n| Hexagon | `lr` | This is the link register which cannot be used as an input or output. |\n\nIn some cases LLVM will allocate a \"reserved register\" for `reg` operands even though this register cannot be explicitly specified. Assembly code making use of reserved registers should be careful since `reg` operands may alias with those registers. Reserved registers are:\n- The frame pointer on all architectures.\n- `r6` on ARM.\n\n## Template modifiers\n\nThe placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string. Only one modifier is allowed per template placeholder.\n\nThe supported modifiers are a subset of LLVM's (and GCC's) [asm template argument modifiers][llvm-argmod], but do not use the same letter codes.\n\n| Architecture | Register class | Modifier | Example output | LLVM modifier |\n| ------------ | -------------- | -------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `eax` | `k` |\n| x86-64 | `reg` | None | `rax` | `q` |\n| x86-32 | `reg_abcd` | `l` | `al` | `b` |\n| x86-64 | `reg` | `l` | `al` | `b` |\n| x86 | `reg_abcd` | `h` | `ah` | `h` |\n| x86 | `reg` | `x` | `ax` | `w` |\n| x86 | `reg` | `e` | `eax` | `k` |\n| x86-64 | `reg` | `r` | `rax` | `q` |\n| x86 | `reg_byte` | None | `al` / `ah` | None |\n| x86 | `xmm_reg` | None | `xmm0` | `x` |\n| x86 | `ymm_reg` | None | `ymm0` | `t` |\n| x86 | `zmm_reg` | None | `zmm0` | `g` |\n| x86 | `*mm_reg` | `x` | `xmm0` | `x` |\n| x86 | `*mm_reg` | `y` | `ymm0` | `t` |\n| x86 | `*mm_reg` | `z` | `zmm0` | `g` |\n| x86 | `kreg` | None | `k1` | None |\n| AArch64 | `reg` | None | `x0` | `x` |\n| AArch64 | `reg` | `w` | `w0` | `w` |\n| AArch64 | `reg` | `x` | `x0` | `x` |\n| AArch64 | `vreg` | None | `v0` | None |\n| AArch64 | `vreg` | `v` | `v0` | None |\n| AArch64 | `vreg` | `b` | `b0` | `b` |\n| AArch64 | `vreg` | `h` | `h0` | `h` |\n| AArch64 | `vreg` | `s` | `s0` | `s` |\n| AArch64 | `vreg` | `d` | `d0` | `d` |\n| AArch64 | `vreg` | `q` | `q0` | `q` |\n| ARM | `reg` | None | `r0` | None |\n| ARM | `sreg` | None | `s0` | None |\n| ARM | `dreg` | None | `d0` | `P` |\n| ARM | `qreg` | None | `q0` | `q` |\n| ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` |\n| NVPTX | `reg16` | None | `rs0` | None |\n| NVPTX | `reg32` | None | `r0` | None |\n| NVPTX | `reg64` | None | `rd0` | None |\n| RISC-V | `reg` | None | `x1` | None |\n| RISC-V | `freg` | None | `f0` | None |\n| Hexagon | `reg` | None | `r0` | None |\n\n> Notes:\n> - on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.\n> - on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size.\n> - on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change.\n\nAs stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the asm code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand.\n\n[llvm-argmod]: http://llvm.org/docs/LangRef.html#asm-template-argument-modifiers\n\n## Options\n\nFlags are used to further influence the behavior of the inline assembly block.\nCurrently the following options are defined:\n- `pure`: The `asm` block has no side effects, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the `asm` block fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used.\n- `nomem`: The `asm` blocks does not read or write to any memory. This allows the compiler to cache the values of modified global variables in registers across the `asm` block since it knows that they are not read or written to by the `asm`.\n- `readonly`: The `asm` block does not write to any memory. This allows the compiler to cache the values of unmodified global variables in registers across the `asm` block since it knows that they are not written to by the `asm`.\n- `preserves_flags`: The `asm` block does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after the `asm` block.\n- `noreturn`: The `asm` block never returns, and its return type is defined as `!` (never). Behavior is undefined if execution falls through past the end of the asm code. A `noreturn` asm block behaves just like a function which doesn't return; notably, local variables in scope are not dropped before it is invoked.\n- `nostack`: The `asm` block does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is *not* used then the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n- `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`.\n\nThe compiler performs some additional checks on options:\n- The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.\n- The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.\n- It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).\n- It is a compile-time error to specify `noreturn` on an asm block with outputs.\n\n## Rules for inline assembly\n\n- Any registers not specified as inputs will contain an undefined value on entry to the asm block.\n - An \"undefined value\" in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).\n- Any registers not specified as outputs must have the same value upon exiting the asm block as they had on entry, otherwise behavior is undefined.\n - This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.\n - Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation.\n- Behavior is undefined if execution unwinds out of an asm block.\n - This also applies if the assembly code calls a function which then unwinds.\n- The set of memory locations that assembly code is allowed the read and write are the same as those allowed for an FFI function.\n - Refer to the unsafe code guidelines for the exact rules.\n - If the `readonly` option is set, then only memory reads are allowed.\n - If the `nomem` option is set then no reads or writes to memory are allowed.\n - These rules do not apply to memory which is private to the asm code, such as stack space allocated within the asm block.\n- The compiler cannot assume that the instructions in the asm are the ones that will actually end up executed.\n - This effectively means that the compiler must treat the `asm!` as a black box and only take the interface specification into account, not the instructions themselves.\n - Runtime code patching is allowed, via target-specific mechanisms (outside the scope of this RFC).\n- Unless the `nostack` option is set, asm code is allowed to use stack space below the stack pointer.\n - On entry to the asm block the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n - You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page).\n - You should adjust the stack pointer when allocating stack memory as required by the target ABI.\n - The stack pointer must be restored to its original value before leaving the asm block.\n- If the `noreturn` option is set then behavior is undefined if execution falls through to the end of the asm block.\n- If the `pure` option is set then behavior is undefined if the `asm` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm` code with the same inputs result in different outputs.\n - When used with the `nomem` option, \"inputs\" are just the direct inputs of the `asm!`.\n - When used with the `readonly` option, \"inputs\" comprise the direct inputs of the `asm!` and any memory that the `asm!` block is allowed to read.\n- These flags registers must be restored upon exiting the asm block if the `preserves_flags` option is set:\n - x86\n - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).\n - Floating-point status word (all).\n - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).\n - ARM\n - Condition flags in `CPSR` (N, Z, C, V)\n - Saturation flag in `CPSR` (Q)\n - Greater than or equal flags in `CPSR` (GE).\n - Condition flags in `FPSCR` (N, Z, C, V)\n - Saturation flag in `FPSCR` (QC)\n - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).\n - AArch64\n - Condition flags (`NZCV` register).\n - Floating-point status (`FPSR` register).\n - RISC-V\n - Floating-point exception flags in `fcsr` (`fflags`).\n- On x86, the direction flag (DF in `EFLAGS`) is clear on entry to an asm block and must be clear on exit.\n - Behavior is undefined if the direction flag is set on exiting an asm block.\n- The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting an `asm!` block.\n - This means that `asm!` blocks that never return (even if not marked `noreturn`) don't need to preserve these registers.\n - When returning to a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are *exiting*.\n - You cannot exit an `asm!` block that has not been entered. Neither can you exit an `asm!` block that has already been exited.\n - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).\n - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.\n- You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places.\n - As a consequence, you should only use [local labels] inside inline assembly code. Defining symbols in assembly code may lead to assembler and/or linker errors due to duplicate symbol definitions.\n\n> **Note**: As a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call.\n\n[local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels\n" } , LintCompletion { label : "core_private_diy_float" , description : "# `core_private_diy_float`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "trace_macros" , description : "# `trace_macros`\n\nThe tracking issue for this feature is [#29598].\n\n[#29598]: https://github.com/rust-lang/rust/issues/29598\n\n------------------------\n\nWith `trace_macros` you can trace the expansion of macros in your code.\n\n## Examples\n\n```rust\n#![feature(trace_macros)]\n\nfn main() {\n trace_macros!(true);\n println!(\"Hello, Rust!\");\n trace_macros!(false);\n}\n```\n\nThe `cargo build` output:\n\n```txt\nnote: trace_macro\n --> src/main.rs:5:5\n |\n5 | println!(\"Hello, Rust!\");\n | ^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: expanding `println! { \"Hello, Rust!\" }`\n = note: to `print ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )`\n = note: expanding `print! { concat ! ( \"Hello, Rust!\" , \"\\n\" ) }`\n = note: to `$crate :: io :: _print ( format_args ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )\n )`\n\n Finished dev [unoptimized + debuginfo] target(s) in 0.60 secs\n```\n" } , LintCompletion { label : "concat_idents" , description : "# `concat_idents`\n\nThe tracking issue for this feature is: [#29599]\n\n[#29599]: https://github.com/rust-lang/rust/issues/29599\n\n------------------------\n\nThe `concat_idents` feature adds a macro for concatenating multiple identifiers\ninto one identifier.\n\n## Examples\n\n```rust\n#![feature(concat_idents)]\n\nfn main() {\n fn foobar() -> u32 { 23 }\n let f = concat_idents!(foo, bar);\n assert_eq!(f(), 23);\n}\n```" } , LintCompletion { label : "windows_net" , description : "# `windows_net`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "derive_clone_copy" , description : "# `derive_clone_copy`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_thread_internals" , description : "# `libstd_thread_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "test" , description : "# `test`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe internals of the `test` crate are unstable, behind the `test` flag. The\nmost widely used part of the `test` crate are benchmark tests, which can test\nthe performance of your code. Let's make our `src/lib.rs` look like this\n(comments elided):\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\n\npub fn add_two(a: i32) -> i32 {\n a + 2\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn it_works() {\n assert_eq!(4, add_two(2));\n }\n\n #[bench]\n fn bench_add_two(b: &mut Bencher) {\n b.iter(|| add_two(2));\n }\n}\n```\n\nNote the `test` feature gate, which enables this unstable feature.\n\nWe've imported the `test` crate, which contains our benchmarking support.\nWe have a new function as well, with the `bench` attribute. Unlike regular\ntests, which take no arguments, benchmark tests take a `&mut Bencher`. This\n`Bencher` provides an `iter` method, which takes a closure. This closure\ncontains the code we'd like to benchmark.\n\nWe can run benchmark tests with `cargo bench`:\n\n```bash\n$ cargo bench\n Compiling adder v0.0.1 (file:///home/steve/tmp/adder)\n Running target/release/adder-91b3e234d4ed382a\n\nrunning 2 tests\ntest tests::it_works ... ignored\ntest tests::bench_add_two ... bench: 1 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 1 ignored; 1 measured\n```\n\nOur non-benchmark test was ignored. You may have noticed that `cargo bench`\ntakes a bit longer than `cargo test`. This is because Rust runs our benchmark\na number of times, and then takes the average. Because we're doing so little\nwork in this example, we have a `1 ns/iter (+/- 0)`, but this would show\nthe variance if there was one.\n\nAdvice on writing benchmarks:\n\n\n* Move setup code outside the `iter` loop; only put the part you want to measure inside\n* Make the code do \"the same thing\" on each iteration; do not accumulate or change state\n* Make the outer function idempotent too; the benchmark runner is likely to run\n it many times\n* Make the inner `iter` loop short and fast so benchmark runs are fast and the\n calibrator can adjust the run-length at fine resolution\n* Make the code in the `iter` loop do something simple, to assist in pinpointing\n performance improvements (or regressions)\n\n## Gotcha: optimizations\n\nThere's another tricky part to writing benchmarks: benchmarks compiled with\noptimizations activated can be dramatically changed by the optimizer so that\nthe benchmark is no longer benchmarking what one expects. For example, the\ncompiler might recognize that some calculation has no external effects and\nremove it entirely.\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\nuse test::Bencher;\n\n#[bench]\nfn bench_xor_1000_ints(b: &mut Bencher) {\n b.iter(|| {\n (0..1000).fold(0, |old, new| old ^ new);\n });\n}\n```\n\ngives the following results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 0 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nThe benchmarking runner offers two ways to avoid this. Either, the closure that\nthe `iter` method receives can return an arbitrary value which forces the\noptimizer to consider the result used and ensures it cannot remove the\ncomputation entirely. This could be done for the example above by adjusting the\n`b.iter` call to\n\n```rust\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n // Note lack of `;` (could also use an explicit `return`).\n (0..1000).fold(0, |old, new| old ^ new)\n});\n```\n\nOr, the other option is to call the generic `test::black_box` function, which\nis an opaque \"black box\" to the optimizer and so forces it to consider any\nargument as used.\n\n```rust\n#![feature(test)]\n\nextern crate test;\n\n# fn main() {\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n let n = test::black_box(1000);\n\n (0..n).fold(0, |a, b| a ^ b)\n})\n# }\n```\n\nNeither of these read or modify the value, and are very cheap for small values.\nLarger values can be passed indirectly to reduce overhead (e.g.\n`black_box(&huge_struct)`).\n\nPerforming either of the above changes gives the following benchmarking results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nHowever, the optimizer can still modify a testcase in an undesirable manner\neven when using either of the above.\n" } , LintCompletion { label : "sort_internals" , description : "# `sort_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "is_sorted" , description : "# `is_sorted`\n\nThe tracking issue for this feature is: [#53485]\n\n[#53485]: https://github.com/rust-lang/rust/issues/53485\n\n------------------------\n\nAdd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to `[T]`;\nadd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to\n`Iterator`.\n" } , LintCompletion { label : "llvm_asm" , description : "# `llvm_asm`\n\nThe tracking issue for this feature is: [#70173]\n\n[#70173]: https://github.com/rust-lang/rust/issues/70173\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `llvm_asm!` macro.\n\n```rust,ignore\nllvm_asm!(assembly template\n : output operands\n : input operands\n : clobbers\n : options\n );\n```\n\nAny use of `llvm_asm` is feature gated (requires `#![feature(llvm_asm)]` on the\ncrate to allow) and of course requires an `unsafe` block.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but\n> all platforms are supported.\n\n## Assembly template\n\nThe `assembly template` is the only required parameter and must be a\nliteral string (i.e. `\"\"`)\n\n```rust\n#![feature(llvm_asm)]\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn foo() {\n unsafe {\n llvm_asm!(\"NOP\");\n }\n}\n\n// Other platforms:\n#[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\nfn foo() { /* ... */ }\n\nfn main() {\n // ...\n foo();\n // ...\n}\n```\n\n(The `feature(llvm_asm)` and `#[cfg]`s are omitted from now on.)\n\nOutput operands, input operands, clobbers and options are all optional\nbut you must add the right number of `:` if you skip them:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\"\n :\n :\n : \"eax\"\n );\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nWhitespace also doesn't matter:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\" ::: \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## Operands\n\nInput and output operands follow the same format: `:\n\"constraints1\"(expr1), \"constraints2\"(expr2), ...\"`. Output operand\nexpressions must be mutable place, or not yet assigned:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn add(a: i32, b: i32) -> i32 {\n let c: i32;\n unsafe {\n llvm_asm!(\"add $2, $0\"\n : \"=r\"(c)\n : \"0\"(a), \"r\"(b)\n );\n }\n c\n}\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn add(a: i32, b: i32) -> i32 { a + b }\n\nfn main() {\n assert_eq!(add(3, 14159), 14162)\n}\n```\n\nIf you would like to use real operands in this position, however,\nyou are required to put curly braces `{}` around the register that\nyou want, and you are required to put the specific size of the\noperand. This is useful for very low level programming, where\nwhich register you use is important:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# unsafe fn read_byte_in(port: u16) -> u8 {\nlet result: u8;\nllvm_asm!(\"in %dx, %al\" : \"={al}\"(result) : \"{dx}\"(port));\nresult\n# }\n```\n\n## Clobbers\n\nSome instructions modify registers which might otherwise have held\ndifferent values so we use the clobbers list to indicate to the\ncompiler not to assume any values loaded into those registers will\nstay valid.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\n// Put the value 0x200 in eax:\nllvm_asm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nInput and output registers need not be listed since that information\nis already communicated by the given constraints. Otherwise, any other\nregisters used either implicitly or explicitly should be listed.\n\nIf the assembly changes the condition code register `cc` should be\nspecified as one of the clobbers. Similarly, if the assembly modifies\nmemory, `memory` should also be specified.\n\n## Options\n\nThe last section, `options` is specific to Rust. The format is comma\nseparated literal strings (i.e. `:\"foo\", \"bar\", \"baz\"`). It's used to\nspecify some extra info about the inline assembly:\n\nCurrent valid options are:\n\n1. *volatile* - specifying this is analogous to\n `__asm__ __volatile__ (...)` in gcc/clang.\n2. *alignstack* - certain instructions expect the stack to be\n aligned a certain way (i.e. SSE) and specifying this indicates to\n the compiler to insert its usual stack alignment code\n3. *intel* - use intel syntax instead of the default AT&T.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() {\nlet result: i32;\nunsafe {\n llvm_asm!(\"mov eax, 2\" : \"={eax}\"(result) : : : \"intel\")\n}\nprintln!(\"eax is currently {}\", result);\n# }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## More Information\n\nThe current implementation of the `llvm_asm!` macro is a direct binding to [LLVM's\ninline assembler expressions][llvm-docs], so be sure to check out [their\ndocumentation as well][llvm-docs] for more information about clobbers,\nconstraints, etc.\n\n[llvm-docs]: http://llvm.org/docs/LangRef.html#inline-assembler-expressions\n\nIf you need more power and don't mind losing some of the niceties of\n`llvm_asm!`, check out [global_asm](global-asm.md).\n" } , LintCompletion { label : "format_args_capture" , description : "# `format_args_capture`\n\nThe tracking issue for this feature is: [#67984]\n\n[#67984]: https://github.com/rust-lang/rust/issues/67984\n\n------------------------\n\nEnables `format_args!` (and macros which use `format_args!` in their implementation, such\nas `format!`, `print!` and `panic!`) to capture variables from the surrounding scope.\nThis avoids the need to pass named parameters when the binding in question\nalready exists in scope.\n\n```rust\n#![feature(format_args_capture)]\n\nlet (person, species, name) = (\"Charlie Brown\", \"dog\", \"Snoopy\");\n\n// captures named argument `person`\nprint!(\"Hello {person}\");\n\n// captures named arguments `species` and `name`\nformat!(\"The {species}'s name is {name}.\");\n```\n\nThis also works for formatting parameters such as width and precision:\n\n```rust\n#![feature(format_args_capture)]\n\nlet precision = 2;\nlet s = format!(\"{:.precision$}\", 1.324223);\n\nassert_eq!(&s, \"1.32\");\n```\n\nA non-exhaustive list of macros which benefit from this functionality include:\n- `format!`\n- `print!` and `println!`\n- `eprint!` and `eprintln!`\n- `write!` and `writeln!`\n- `panic!`\n- `unreachable!`\n- `unimplemented!`\n- `todo!`\n- `assert!` and similar\n- macros in many thirdparty crates, such as `log`\n" } , LintCompletion { label : "set_stdio" , description : "# `set_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } ] ; | ||
diff --git a/crates/ide/src/diagnostics.rs b/crates/ide/src/diagnostics.rs index 1e5ea4617..d0ee58858 100644 --- a/crates/ide/src/diagnostics.rs +++ b/crates/ide/src/diagnostics.rs | |||
@@ -9,8 +9,11 @@ mod field_shorthand; | |||
9 | 9 | ||
10 | use std::cell::RefCell; | 10 | use std::cell::RefCell; |
11 | 11 | ||
12 | use base_db::SourceDatabase; | 12 | use hir::{ |
13 | use hir::{diagnostics::DiagnosticSinkBuilder, Semantics}; | 13 | diagnostics::{Diagnostic as _, DiagnosticSinkBuilder}, |
14 | Semantics, | ||
15 | }; | ||
16 | use ide_db::base_db::SourceDatabase; | ||
14 | use ide_db::RootDatabase; | 17 | use ide_db::RootDatabase; |
15 | use itertools::Itertools; | 18 | use itertools::Itertools; |
16 | use rustc_hash::FxHashSet; | 19 | use rustc_hash::FxHashSet; |
@@ -31,6 +34,25 @@ pub struct Diagnostic { | |||
31 | pub range: TextRange, | 34 | pub range: TextRange, |
32 | pub severity: Severity, | 35 | pub severity: Severity, |
33 | pub fix: Option<Fix>, | 36 | pub fix: Option<Fix>, |
37 | pub unused: bool, | ||
38 | } | ||
39 | |||
40 | impl Diagnostic { | ||
41 | fn error(range: TextRange, message: String) -> Self { | ||
42 | Self { message, range, severity: Severity::Error, fix: None, unused: false } | ||
43 | } | ||
44 | |||
45 | fn hint(range: TextRange, message: String) -> Self { | ||
46 | Self { message, range, severity: Severity::WeakWarning, fix: None, unused: false } | ||
47 | } | ||
48 | |||
49 | fn with_fix(self, fix: Option<Fix>) -> Self { | ||
50 | Self { fix, ..self } | ||
51 | } | ||
52 | |||
53 | fn with_unused(self, unused: bool) -> Self { | ||
54 | Self { unused, ..self } | ||
55 | } | ||
34 | } | 56 | } |
35 | 57 | ||
36 | #[derive(Debug)] | 58 | #[derive(Debug)] |
@@ -71,13 +93,13 @@ pub(crate) fn diagnostics( | |||
71 | let mut res = Vec::new(); | 93 | let mut res = Vec::new(); |
72 | 94 | ||
73 | // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily. | 95 | // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily. |
74 | res.extend(parse.errors().iter().take(128).map(|err| Diagnostic { | 96 | res.extend( |
75 | // name: None, | 97 | parse |
76 | range: err.range(), | 98 | .errors() |
77 | message: format!("Syntax Error: {}", err), | 99 | .iter() |
78 | severity: Severity::Error, | 100 | .take(128) |
79 | fix: None, | 101 | .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))), |
80 | })); | 102 | ); |
81 | 103 | ||
82 | for node in parse.tree().syntax().descendants() { | 104 | for node in parse.tree().syntax().descendants() { |
83 | check_unnecessary_braces_in_use_statement(&mut res, file_id, &node); | 105 | check_unnecessary_braces_in_use_statement(&mut res, file_id, &node); |
@@ -100,6 +122,13 @@ pub(crate) fn diagnostics( | |||
100 | .on::<hir::diagnostics::IncorrectCase, _>(|d| { | 122 | .on::<hir::diagnostics::IncorrectCase, _>(|d| { |
101 | res.borrow_mut().push(warning_with_fix(d, &sema)); | 123 | res.borrow_mut().push(warning_with_fix(d, &sema)); |
102 | }) | 124 | }) |
125 | .on::<hir::diagnostics::InactiveCode, _>(|d| { | ||
126 | // Override severity and mark as unused. | ||
127 | res.borrow_mut().push( | ||
128 | Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message()) | ||
129 | .with_unused(true), | ||
130 | ); | ||
131 | }) | ||
103 | // Only collect experimental diagnostics when they're enabled. | 132 | // Only collect experimental diagnostics when they're enabled. |
104 | .filter(|diag| !(diag.is_experimental() && config.disable_experimental)) | 133 | .filter(|diag| !(diag.is_experimental() && config.disable_experimental)) |
105 | .filter(|diag| !config.disabled.contains(diag.code().as_str())); | 134 | .filter(|diag| !config.disabled.contains(diag.code().as_str())); |
@@ -108,13 +137,8 @@ pub(crate) fn diagnostics( | |||
108 | let mut sink = sink_builder | 137 | let mut sink = sink_builder |
109 | // Diagnostics not handled above get no fix and default treatment. | 138 | // Diagnostics not handled above get no fix and default treatment. |
110 | .build(|d| { | 139 | .build(|d| { |
111 | res.borrow_mut().push(Diagnostic { | 140 | res.borrow_mut() |
112 | // name: Some(d.name().into()), | 141 | .push(Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())); |
113 | message: d.message(), | ||
114 | range: sema.diagnostics_display_range(d).range, | ||
115 | severity: Severity::Error, | ||
116 | fix: None, | ||
117 | }) | ||
118 | }); | 142 | }); |
119 | 143 | ||
120 | if let Some(m) = sema.to_module_def(file_id) { | 144 | if let Some(m) = sema.to_module_def(file_id) { |
@@ -125,22 +149,11 @@ pub(crate) fn diagnostics( | |||
125 | } | 149 | } |
126 | 150 | ||
127 | fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { | 151 | fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { |
128 | Diagnostic { | 152 | Diagnostic::error(sema.diagnostics_display_range(d).range, d.message()).with_fix(d.fix(&sema)) |
129 | // name: Some(d.name().into()), | ||
130 | range: sema.diagnostics_display_range(d).range, | ||
131 | message: d.message(), | ||
132 | severity: Severity::Error, | ||
133 | fix: d.fix(&sema), | ||
134 | } | ||
135 | } | 153 | } |
136 | 154 | ||
137 | fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { | 155 | fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { |
138 | Diagnostic { | 156 | Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message()).with_fix(d.fix(&sema)) |
139 | range: sema.diagnostics_display_range(d).range, | ||
140 | message: d.message(), | ||
141 | severity: Severity::WeakWarning, | ||
142 | fix: d.fix(&sema), | ||
143 | } | ||
144 | } | 157 | } |
145 | 158 | ||
146 | fn check_unnecessary_braces_in_use_statement( | 159 | fn check_unnecessary_braces_in_use_statement( |
@@ -161,17 +174,14 @@ fn check_unnecessary_braces_in_use_statement( | |||
161 | edit_builder.finish() | 174 | edit_builder.finish() |
162 | }); | 175 | }); |
163 | 176 | ||
164 | acc.push(Diagnostic { | 177 | acc.push( |
165 | // name: None, | 178 | Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string()) |
166 | range: use_range, | 179 | .with_fix(Some(Fix::new( |
167 | message: "Unnecessary braces in use statement".to_string(), | 180 | "Remove unnecessary braces", |
168 | severity: Severity::WeakWarning, | 181 | SourceFileEdit { file_id, edit }.into(), |
169 | fix: Some(Fix::new( | 182 | use_range, |
170 | "Remove unnecessary braces", | 183 | ))), |
171 | SourceFileEdit { file_id, edit }.into(), | 184 | ); |
172 | use_range, | ||
173 | )), | ||
174 | }); | ||
175 | } | 185 | } |
176 | 186 | ||
177 | Some(()) | 187 | Some(()) |
@@ -578,6 +588,7 @@ fn test_fn() { | |||
578 | fix_trigger_range: 0..8, | 588 | fix_trigger_range: 0..8, |
579 | }, | 589 | }, |
580 | ), | 590 | ), |
591 | unused: false, | ||
581 | }, | 592 | }, |
582 | ] | 593 | ] |
583 | "#]], | 594 | "#]], |
@@ -602,7 +613,7 @@ fn main() { | |||
602 | pub struct Foo { pub a: i32, pub b: i32 } | 613 | pub struct Foo { pub a: i32, pub b: i32 } |
603 | "#, | 614 | "#, |
604 | r#" | 615 | r#" |
605 | fn {a:42, b: ()} {} | 616 | fn some(, b: ()} {} |
606 | fn items() {} | 617 | fn items() {} |
607 | fn here() {} | 618 | fn here() {} |
608 | 619 | ||
diff --git a/crates/ide/src/diagnostics/field_shorthand.rs b/crates/ide/src/diagnostics/field_shorthand.rs index 2c4acd783..f41bcd619 100644 --- a/crates/ide/src/diagnostics/field_shorthand.rs +++ b/crates/ide/src/diagnostics/field_shorthand.rs | |||
@@ -1,12 +1,12 @@ | |||
1 | //! Suggests shortening `Foo { field: field }` to `Foo { field }` in both | 1 | //! Suggests shortening `Foo { field: field }` to `Foo { field }` in both |
2 | //! expressions and patterns. | 2 | //! expressions and patterns. |
3 | 3 | ||
4 | use base_db::FileId; | 4 | use ide_db::base_db::FileId; |
5 | use ide_db::source_change::SourceFileEdit; | 5 | use ide_db::source_change::SourceFileEdit; |
6 | use syntax::{ast, match_ast, AstNode, SyntaxNode}; | 6 | use syntax::{ast, match_ast, AstNode, SyntaxNode}; |
7 | use text_edit::TextEdit; | 7 | use text_edit::TextEdit; |
8 | 8 | ||
9 | use crate::{Diagnostic, Fix, Severity}; | 9 | use crate::{Diagnostic, Fix}; |
10 | 10 | ||
11 | pub(super) fn check(acc: &mut Vec<Diagnostic>, file_id: FileId, node: &SyntaxNode) { | 11 | pub(super) fn check(acc: &mut Vec<Diagnostic>, file_id: FileId, node: &SyntaxNode) { |
12 | match_ast! { | 12 | match_ast! { |
@@ -46,17 +46,15 @@ fn check_expr_field_shorthand( | |||
46 | let edit = edit_builder.finish(); | 46 | let edit = edit_builder.finish(); |
47 | 47 | ||
48 | let field_range = record_field.syntax().text_range(); | 48 | let field_range = record_field.syntax().text_range(); |
49 | acc.push(Diagnostic { | 49 | acc.push( |
50 | // name: None, | 50 | Diagnostic::hint(field_range, "Shorthand struct initialization".to_string()).with_fix( |
51 | range: field_range, | 51 | Some(Fix::new( |
52 | message: "Shorthand struct initialization".to_string(), | 52 | "Use struct shorthand initialization", |
53 | severity: Severity::WeakWarning, | 53 | SourceFileEdit { file_id, edit }.into(), |
54 | fix: Some(Fix::new( | 54 | field_range, |
55 | "Use struct shorthand initialization", | 55 | )), |
56 | SourceFileEdit { file_id, edit }.into(), | 56 | ), |
57 | field_range, | 57 | ); |
58 | )), | ||
59 | }); | ||
60 | } | 58 | } |
61 | } | 59 | } |
62 | 60 | ||
@@ -88,17 +86,13 @@ fn check_pat_field_shorthand( | |||
88 | let edit = edit_builder.finish(); | 86 | let edit = edit_builder.finish(); |
89 | 87 | ||
90 | let field_range = record_pat_field.syntax().text_range(); | 88 | let field_range = record_pat_field.syntax().text_range(); |
91 | acc.push(Diagnostic { | 89 | acc.push(Diagnostic::hint(field_range, "Shorthand struct pattern".to_string()).with_fix( |
92 | // name: None, | 90 | Some(Fix::new( |
93 | range: field_range, | ||
94 | message: "Shorthand struct pattern".to_string(), | ||
95 | severity: Severity::WeakWarning, | ||
96 | fix: Some(Fix::new( | ||
97 | "Use struct field shorthand", | 91 | "Use struct field shorthand", |
98 | SourceFileEdit { file_id, edit }.into(), | 92 | SourceFileEdit { file_id, edit }.into(), |
99 | field_range, | 93 | field_range, |
100 | )), | 94 | )), |
101 | }); | 95 | )); |
102 | } | 96 | } |
103 | } | 97 | } |
104 | 98 | ||
diff --git a/crates/ide/src/diagnostics/fixes.rs b/crates/ide/src/diagnostics/fixes.rs index 0c75e50b0..0c950003e 100644 --- a/crates/ide/src/diagnostics/fixes.rs +++ b/crates/ide/src/diagnostics/fixes.rs | |||
@@ -1,6 +1,5 @@ | |||
1 | //! Provides a way to attach fixes to the diagnostics. | 1 | //! Provides a way to attach fixes to the diagnostics. |
2 | //! The same module also has all curret custom fixes for the diagnostics implemented. | 2 | //! The same module also has all curret custom fixes for the diagnostics implemented. |
3 | use base_db::FileId; | ||
4 | use hir::{ | 3 | use hir::{ |
5 | db::AstDatabase, | 4 | db::AstDatabase, |
6 | diagnostics::{ | 5 | diagnostics::{ |
@@ -9,6 +8,7 @@ use hir::{ | |||
9 | }, | 8 | }, |
10 | HasSource, HirDisplay, Semantics, VariantDef, | 9 | HasSource, HirDisplay, Semantics, VariantDef, |
11 | }; | 10 | }; |
11 | use ide_db::base_db::FileId; | ||
12 | use ide_db::{ | 12 | use ide_db::{ |
13 | source_change::{FileSystemEdit, SourceFileEdit}, | 13 | source_change::{FileSystemEdit, SourceFileEdit}, |
14 | RootDatabase, | 14 | RootDatabase, |
diff --git a/crates/ide/src/display.rs b/crates/ide/src/display.rs index 2484dbbf1..0650915c5 100644 --- a/crates/ide/src/display.rs +++ b/crates/ide/src/display.rs | |||
@@ -4,87 +4,8 @@ | |||
4 | mod navigation_target; | 4 | mod navigation_target; |
5 | mod short_label; | 5 | mod short_label; |
6 | 6 | ||
7 | use syntax::{ | ||
8 | ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner}, | ||
9 | SyntaxKind::{ATTR, COMMENT}, | ||
10 | }; | ||
11 | |||
12 | use ast::VisibilityOwner; | ||
13 | use stdx::format_to; | ||
14 | |||
15 | pub use navigation_target::NavigationTarget; | 7 | pub use navigation_target::NavigationTarget; |
16 | pub(crate) use navigation_target::{ToNav, TryToNav}; | 8 | pub(crate) use navigation_target::{ToNav, TryToNav}; |
17 | pub(crate) use short_label::ShortLabel; | 9 | pub(crate) use short_label::ShortLabel; |
18 | 10 | ||
19 | pub(crate) fn function_declaration(node: &ast::Fn) -> String { | 11 | pub(crate) use syntax::display::{function_declaration, macro_label}; |
20 | let mut buf = String::new(); | ||
21 | if let Some(vis) = node.visibility() { | ||
22 | format_to!(buf, "{} ", vis); | ||
23 | } | ||
24 | if node.async_token().is_some() { | ||
25 | format_to!(buf, "async "); | ||
26 | } | ||
27 | if node.const_token().is_some() { | ||
28 | format_to!(buf, "const "); | ||
29 | } | ||
30 | if node.unsafe_token().is_some() { | ||
31 | format_to!(buf, "unsafe "); | ||
32 | } | ||
33 | if let Some(abi) = node.abi() { | ||
34 | // Keyword `extern` is included in the string. | ||
35 | format_to!(buf, "{} ", abi); | ||
36 | } | ||
37 | if let Some(name) = node.name() { | ||
38 | format_to!(buf, "fn {}", name) | ||
39 | } | ||
40 | if let Some(type_params) = node.generic_param_list() { | ||
41 | format_to!(buf, "{}", type_params); | ||
42 | } | ||
43 | if let Some(param_list) = node.param_list() { | ||
44 | let params: Vec<String> = param_list | ||
45 | .self_param() | ||
46 | .into_iter() | ||
47 | .map(|self_param| self_param.to_string()) | ||
48 | .chain(param_list.params().map(|param| param.to_string())) | ||
49 | .collect(); | ||
50 | // Useful to inline parameters | ||
51 | format_to!(buf, "({})", params.join(", ")); | ||
52 | } | ||
53 | if let Some(ret_type) = node.ret_type() { | ||
54 | if ret_type.ty().is_some() { | ||
55 | format_to!(buf, " {}", ret_type); | ||
56 | } | ||
57 | } | ||
58 | if let Some(where_clause) = node.where_clause() { | ||
59 | format_to!(buf, "\n{}", where_clause); | ||
60 | } | ||
61 | buf | ||
62 | } | ||
63 | |||
64 | pub(crate) fn const_label(node: &ast::Const) -> String { | ||
65 | let label: String = node | ||
66 | .syntax() | ||
67 | .children_with_tokens() | ||
68 | .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR)) | ||
69 | .map(|node| node.to_string()) | ||
70 | .collect(); | ||
71 | |||
72 | label.trim().to_owned() | ||
73 | } | ||
74 | |||
75 | pub(crate) fn type_label(node: &ast::TypeAlias) -> String { | ||
76 | let label: String = node | ||
77 | .syntax() | ||
78 | .children_with_tokens() | ||
79 | .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR)) | ||
80 | .map(|node| node.to_string()) | ||
81 | .collect(); | ||
82 | |||
83 | label.trim().to_owned() | ||
84 | } | ||
85 | |||
86 | pub(crate) fn macro_label(node: &ast::MacroCall) -> String { | ||
87 | let name = node.name().map(|name| name.syntax().text().to_string()).unwrap_or_default(); | ||
88 | let vis = if node.has_atom_attr("macro_export") { "#[macro_export]\n" } else { "" }; | ||
89 | format!("{}macro_rules! {}", vis, name) | ||
90 | } | ||
diff --git a/crates/ide/src/display/navigation_target.rs b/crates/ide/src/display/navigation_target.rs index cf9d617dc..0c429a262 100644 --- a/crates/ide/src/display/navigation_target.rs +++ b/crates/ide/src/display/navigation_target.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use base_db::{FileId, SourceDatabase}; | ||
4 | use either::Either; | 3 | use either::Either; |
5 | use hir::{original_range, AssocItem, FieldSource, HasSource, InFile, ModuleSource}; | 4 | use hir::{original_range, AssocItem, FieldSource, HasSource, InFile, ModuleSource}; |
5 | use ide_db::base_db::{FileId, SourceDatabase}; | ||
6 | use ide_db::{defs::Definition, RootDatabase}; | 6 | use ide_db::{defs::Definition, RootDatabase}; |
7 | use syntax::{ | 7 | use syntax::{ |
8 | ast::{self, DocCommentsOwner, NameOwner}, | 8 | ast::{self, DocCommentsOwner, NameOwner}, |
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index d9dc63b33..250f10f9f 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs | |||
@@ -130,9 +130,10 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option<String> { | |||
130 | let module = definition.module(db)?; | 130 | let module = definition.module(db)?; |
131 | let krate = module.krate(); | 131 | let krate = module.krate(); |
132 | let import_map = db.import_map(krate.into()); | 132 | let import_map = db.import_map(krate.into()); |
133 | let base = once(krate.declaration_name(db)?.to_string()) | 133 | let base = once(krate.display_name(db)?.to_string()) |
134 | .chain(import_map.path_of(ns)?.segments.iter().map(|name| name.to_string())) | 134 | .chain(import_map.path_of(ns)?.segments.iter().map(|name| name.to_string())) |
135 | .join("/"); | 135 | .join("/") |
136 | + "/"; | ||
136 | 137 | ||
137 | let filename = get_symbol_filename(db, &target_def); | 138 | let filename = get_symbol_filename(db, &target_def); |
138 | let fragment = match definition { | 139 | let fragment = match definition { |
@@ -152,9 +153,16 @@ fn get_doc_link(db: &RootDatabase, definition: Definition) -> Option<String> { | |||
152 | _ => None, | 153 | _ => None, |
153 | }; | 154 | }; |
154 | 155 | ||
155 | get_doc_url(db, &krate) | 156 | get_doc_url(db, &krate)? |
156 | .and_then(|url| url.join(&base).ok()) | 157 | .join(&base) |
157 | .and_then(|url| filename.as_deref().and_then(|f| url.join(f).ok())) | 158 | .ok() |
159 | .and_then(|mut url| { | ||
160 | if !matches!(definition, Definition::ModuleDef(ModuleDef::Module(..))) { | ||
161 | url.path_segments_mut().ok()?.pop(); | ||
162 | }; | ||
163 | Some(url) | ||
164 | }) | ||
165 | .and_then(|url| url.join(filename.as_deref()?).ok()) | ||
158 | .and_then( | 166 | .and_then( |
159 | |url| if let Some(fragment) = fragment { url.join(&fragment).ok() } else { Some(url) }, | 167 | |url| if let Some(fragment) = fragment { url.join(&fragment).ok() } else { Some(url) }, |
160 | ) | 168 | ) |
@@ -188,7 +196,7 @@ fn rewrite_intra_doc_link( | |||
188 | let krate = resolved.module(db)?.krate(); | 196 | let krate = resolved.module(db)?.krate(); |
189 | let canonical_path = resolved.canonical_path(db)?; | 197 | let canonical_path = resolved.canonical_path(db)?; |
190 | let new_target = get_doc_url(db, &krate)? | 198 | let new_target = get_doc_url(db, &krate)? |
191 | .join(&format!("{}/", krate.declaration_name(db)?)) | 199 | .join(&format!("{}/", krate.display_name(db)?)) |
192 | .ok()? | 200 | .ok()? |
193 | .join(&canonical_path.replace("::", "/")) | 201 | .join(&canonical_path.replace("::", "/")) |
194 | .ok()? | 202 | .ok()? |
@@ -208,7 +216,7 @@ fn rewrite_url_link(db: &RootDatabase, def: ModuleDef, target: &str) -> Option<S | |||
208 | let module = def.module(db)?; | 216 | let module = def.module(db)?; |
209 | let krate = module.krate(); | 217 | let krate = module.krate(); |
210 | let canonical_path = def.canonical_path(db)?; | 218 | let canonical_path = def.canonical_path(db)?; |
211 | let base = format!("{}/{}", krate.declaration_name(db)?, canonical_path.replace("::", "/")); | 219 | let base = format!("{}/{}", krate.display_name(db)?, canonical_path.replace("::", "/")); |
212 | 220 | ||
213 | get_doc_url(db, &krate) | 221 | get_doc_url(db, &krate) |
214 | .and_then(|url| url.join(&base).ok()) | 222 | .and_then(|url| url.join(&base).ok()) |
@@ -357,7 +365,7 @@ fn get_doc_url(db: &RootDatabase, krate: &Crate) -> Option<Url> { | |||
357 | // | 365 | // |
358 | // FIXME: clicking on the link should just open the file in the editor, | 366 | // FIXME: clicking on the link should just open the file in the editor, |
359 | // instead of falling back to external urls. | 367 | // instead of falling back to external urls. |
360 | Some(format!("https://docs.rs/{}/*/", krate.declaration_name(db)?)) | 368 | Some(format!("https://docs.rs/{}/*/", krate.display_name(db)?)) |
361 | }) | 369 | }) |
362 | .and_then(|s| Url::parse(&s).ok()) | 370 | .and_then(|s| Url::parse(&s).ok()) |
363 | } | 371 | } |
@@ -522,6 +530,18 @@ pub struct Foo { | |||
522 | ); | 530 | ); |
523 | } | 531 | } |
524 | 532 | ||
533 | #[test] | ||
534 | fn test_module() { | ||
535 | check( | ||
536 | r#" | ||
537 | pub mod foo { | ||
538 | pub mod ba<|>r {} | ||
539 | } | ||
540 | "#, | ||
541 | expect![[r#"https://docs.rs/test/*/test/foo/bar/index.html"#]], | ||
542 | ) | ||
543 | } | ||
544 | |||
525 | // FIXME: ImportMap will return re-export paths instead of public module | 545 | // FIXME: ImportMap will return re-export paths instead of public module |
526 | // paths. The correct path to documentation will never be a re-export. | 546 | // paths. The correct path to documentation will never be a re-export. |
527 | // This problem stops us from resolving stdlib items included in the prelude | 547 | // This problem stops us from resolving stdlib items included in the prelude |
diff --git a/crates/ide/src/fixture.rs b/crates/ide/src/fixture.rs index ed06689f0..eb57f9224 100644 --- a/crates/ide/src/fixture.rs +++ b/crates/ide/src/fixture.rs | |||
@@ -1,5 +1,5 @@ | |||
1 | //! Utilities for creating `Analysis` instances for tests. | 1 | //! Utilities for creating `Analysis` instances for tests. |
2 | use base_db::fixture::ChangeFixture; | 2 | use ide_db::base_db::fixture::ChangeFixture; |
3 | use test_utils::{extract_annotations, RangeOrOffset}; | 3 | use test_utils::{extract_annotations, RangeOrOffset}; |
4 | 4 | ||
5 | use crate::{Analysis, AnalysisHost, FileId, FilePosition, FileRange}; | 5 | use crate::{Analysis, AnalysisHost, FileId, FilePosition, FileRange}; |
diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index a87e31019..15792f947 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs | |||
@@ -100,7 +100,7 @@ pub(crate) fn reference_definition( | |||
100 | 100 | ||
101 | #[cfg(test)] | 101 | #[cfg(test)] |
102 | mod tests { | 102 | mod tests { |
103 | use base_db::FileRange; | 103 | use ide_db::base_db::FileRange; |
104 | use syntax::{TextRange, TextSize}; | 104 | use syntax::{TextRange, TextSize}; |
105 | 105 | ||
106 | use crate::fixture; | 106 | use crate::fixture; |
diff --git a/crates/ide/src/goto_implementation.rs b/crates/ide/src/goto_implementation.rs index 6c586bbd1..529004878 100644 --- a/crates/ide/src/goto_implementation.rs +++ b/crates/ide/src/goto_implementation.rs | |||
@@ -74,7 +74,7 @@ fn impls_for_trait( | |||
74 | 74 | ||
75 | #[cfg(test)] | 75 | #[cfg(test)] |
76 | mod tests { | 76 | mod tests { |
77 | use base_db::FileRange; | 77 | use ide_db::base_db::FileRange; |
78 | 78 | ||
79 | use crate::fixture; | 79 | use crate::fixture; |
80 | 80 | ||
diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs index 6d0df04dd..aba6bf5dc 100644 --- a/crates/ide/src/goto_type_definition.rs +++ b/crates/ide/src/goto_type_definition.rs | |||
@@ -54,7 +54,7 @@ fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> { | |||
54 | 54 | ||
55 | #[cfg(test)] | 55 | #[cfg(test)] |
56 | mod tests { | 56 | mod tests { |
57 | use base_db::FileRange; | 57 | use ide_db::base_db::FileRange; |
58 | 58 | ||
59 | use crate::fixture; | 59 | use crate::fixture; |
60 | 60 | ||
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index 845333e2a..832192881 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | use base_db::SourceDatabase; | ||
2 | use hir::{ | 1 | use hir::{ |
3 | Adt, AsAssocItem, AssocItemContainer, Documentation, FieldSource, HasSource, HirDisplay, | 2 | Adt, AsAssocItem, AssocItemContainer, Documentation, FieldSource, HasSource, HirDisplay, |
4 | Module, ModuleDef, ModuleSource, Semantics, | 3 | Module, ModuleDef, ModuleSource, Semantics, |
5 | }; | 4 | }; |
5 | use ide_db::base_db::SourceDatabase; | ||
6 | use ide_db::{ | 6 | use ide_db::{ |
7 | defs::{Definition, NameClass, NameRefClass}, | 7 | defs::{Definition, NameClass, NameRefClass}, |
8 | RootDatabase, | 8 | RootDatabase, |
@@ -300,7 +300,7 @@ fn definition_owner_name(db: &RootDatabase, def: &Definition) -> Option<String> | |||
300 | 300 | ||
301 | fn render_path(db: &RootDatabase, module: Module, item_name: Option<String>) -> String { | 301 | fn render_path(db: &RootDatabase, module: Module, item_name: Option<String>) -> String { |
302 | let crate_name = | 302 | let crate_name = |
303 | db.crate_graph()[module.krate().into()].declaration_name.as_ref().map(ToString::to_string); | 303 | db.crate_graph()[module.krate().into()].display_name.as_ref().map(|it| it.to_string()); |
304 | let module_path = module | 304 | let module_path = module |
305 | .path_to_root(db) | 305 | .path_to_root(db) |
306 | .into_iter() | 306 | .into_iter() |
@@ -385,8 +385,8 @@ fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> { | |||
385 | 385 | ||
386 | #[cfg(test)] | 386 | #[cfg(test)] |
387 | mod tests { | 387 | mod tests { |
388 | use base_db::FileLoader; | ||
389 | use expect_test::{expect, Expect}; | 388 | use expect_test::{expect, Expect}; |
389 | use ide_db::base_db::FileLoader; | ||
390 | 390 | ||
391 | use crate::fixture; | 391 | use crate::fixture; |
392 | 392 | ||
@@ -638,6 +638,33 @@ fn main() { } | |||
638 | } | 638 | } |
639 | 639 | ||
640 | #[test] | 640 | #[test] |
641 | fn hover_shows_fn_doc_attr_raw_string() { | ||
642 | check( | ||
643 | r##" | ||
644 | #[doc = r#"Raw string doc attr"#] | ||
645 | pub fn foo<|>(_: &Path) {} | ||
646 | |||
647 | fn main() { } | ||
648 | "##, | ||
649 | expect![[r##" | ||
650 | *foo* | ||
651 | |||
652 | ```rust | ||
653 | test | ||
654 | ``` | ||
655 | |||
656 | ```rust | ||
657 | pub fn foo(_: &Path) | ||
658 | ``` | ||
659 | |||
660 | --- | ||
661 | |||
662 | Raw string doc attr | ||
663 | "##]], | ||
664 | ); | ||
665 | } | ||
666 | |||
667 | #[test] | ||
641 | fn hover_shows_struct_field_info() { | 668 | fn hover_shows_struct_field_info() { |
642 | // Hovering over the field when instantiating | 669 | // Hovering over the field when instantiating |
643 | check( | 670 | check( |
@@ -2128,7 +2155,7 @@ fn foo_<|>test() {} | |||
2128 | ignore: false, | 2155 | ignore: false, |
2129 | }, | 2156 | }, |
2130 | }, | 2157 | }, |
2131 | cfg_exprs: [], | 2158 | cfg: None, |
2132 | }, | 2159 | }, |
2133 | ), | 2160 | ), |
2134 | ] | 2161 | ] |
@@ -2166,7 +2193,7 @@ mod tests<|> { | |||
2166 | kind: TestMod { | 2193 | kind: TestMod { |
2167 | path: "tests", | 2194 | path: "tests", |
2168 | }, | 2195 | }, |
2169 | cfg_exprs: [], | 2196 | cfg: None, |
2170 | }, | 2197 | }, |
2171 | ), | 2198 | ), |
2172 | ] | 2199 | ] |
diff --git a/crates/ide/src/inlay_hints.rs b/crates/ide/src/inlay_hints.rs index e2079bbcf..49d8e4ae1 100644 --- a/crates/ide/src/inlay_hints.rs +++ b/crates/ide/src/inlay_hints.rs | |||
@@ -1,15 +1,14 @@ | |||
1 | use assists::utils::FamousDefs; | 1 | use assists::utils::FamousDefs; |
2 | use either::Either; | ||
2 | use hir::{known, HirDisplay, Semantics}; | 3 | use hir::{known, HirDisplay, Semantics}; |
3 | use ide_db::RootDatabase; | 4 | use ide_db::RootDatabase; |
4 | use stdx::to_lower_snake_case; | 5 | use stdx::to_lower_snake_case; |
5 | use syntax::{ | 6 | use syntax::{ |
6 | ast::{self, ArgListOwner, AstNode}, | 7 | ast::{self, ArgListOwner, AstNode, NameOwner}, |
7 | match_ast, Direction, NodeOrToken, SmolStr, SyntaxKind, TextRange, T, | 8 | match_ast, Direction, NodeOrToken, SmolStr, SyntaxKind, TextRange, T, |
8 | }; | 9 | }; |
9 | 10 | ||
10 | use crate::FileId; | 11 | use crate::FileId; |
11 | use ast::NameOwner; | ||
12 | use either::Either; | ||
13 | 12 | ||
14 | #[derive(Clone, Debug, PartialEq, Eq)] | 13 | #[derive(Clone, Debug, PartialEq, Eq)] |
15 | pub struct InlayHintsConfig { | 14 | pub struct InlayHintsConfig { |
@@ -100,6 +99,9 @@ fn get_chaining_hints( | |||
100 | return None; | 99 | return None; |
101 | } | 100 | } |
102 | 101 | ||
102 | let krate = sema.scope(expr.syntax()).module().map(|it| it.krate()); | ||
103 | let famous_defs = FamousDefs(&sema, krate); | ||
104 | |||
103 | let mut tokens = expr | 105 | let mut tokens = expr |
104 | .syntax() | 106 | .syntax() |
105 | .siblings_with_tokens(Direction::Next) | 107 | .siblings_with_tokens(Direction::Next) |
@@ -129,7 +131,7 @@ fn get_chaining_hints( | |||
129 | acc.push(InlayHint { | 131 | acc.push(InlayHint { |
130 | range: expr.syntax().text_range(), | 132 | range: expr.syntax().text_range(), |
131 | kind: InlayKind::ChainingHint, | 133 | kind: InlayKind::ChainingHint, |
132 | label: hint_iterator(sema, config, &ty).unwrap_or_else(|| { | 134 | label: hint_iterator(sema, &famous_defs, config, &ty).unwrap_or_else(|| { |
133 | ty.display_truncated(sema.db, config.max_length).to_string().into() | 135 | ty.display_truncated(sema.db, config.max_length).to_string().into() |
134 | }), | 136 | }), |
135 | }); | 137 | }); |
@@ -189,6 +191,9 @@ fn get_bind_pat_hints( | |||
189 | return None; | 191 | return None; |
190 | } | 192 | } |
191 | 193 | ||
194 | let krate = sema.scope(pat.syntax()).module().map(|it| it.krate()); | ||
195 | let famous_defs = FamousDefs(&sema, krate); | ||
196 | |||
192 | let ty = sema.type_of_pat(&pat.clone().into())?; | 197 | let ty = sema.type_of_pat(&pat.clone().into())?; |
193 | 198 | ||
194 | if should_not_display_type_hint(sema, &pat, &ty) { | 199 | if should_not_display_type_hint(sema, &pat, &ty) { |
@@ -197,7 +202,7 @@ fn get_bind_pat_hints( | |||
197 | acc.push(InlayHint { | 202 | acc.push(InlayHint { |
198 | range: pat.syntax().text_range(), | 203 | range: pat.syntax().text_range(), |
199 | kind: InlayKind::TypeHint, | 204 | kind: InlayKind::TypeHint, |
200 | label: hint_iterator(sema, config, &ty) | 205 | label: hint_iterator(sema, &famous_defs, config, &ty) |
201 | .unwrap_or_else(|| ty.display_truncated(sema.db, config.max_length).to_string().into()), | 206 | .unwrap_or_else(|| ty.display_truncated(sema.db, config.max_length).to_string().into()), |
202 | }); | 207 | }); |
203 | 208 | ||
@@ -207,6 +212,7 @@ fn get_bind_pat_hints( | |||
207 | /// Checks if the type is an Iterator from std::iter and replaces its hint with an `impl Iterator<Item = Ty>`. | 212 | /// Checks if the type is an Iterator from std::iter and replaces its hint with an `impl Iterator<Item = Ty>`. |
208 | fn hint_iterator( | 213 | fn hint_iterator( |
209 | sema: &Semantics<RootDatabase>, | 214 | sema: &Semantics<RootDatabase>, |
215 | famous_defs: &FamousDefs, | ||
210 | config: &InlayHintsConfig, | 216 | config: &InlayHintsConfig, |
211 | ty: &hir::Type, | 217 | ty: &hir::Type, |
212 | ) -> Option<SmolStr> { | 218 | ) -> Option<SmolStr> { |
@@ -215,11 +221,11 @@ fn hint_iterator( | |||
215 | .last() | 221 | .last() |
216 | .and_then(|strukt| strukt.as_adt())?; | 222 | .and_then(|strukt| strukt.as_adt())?; |
217 | let krate = strukt.krate(db)?; | 223 | let krate = strukt.krate(db)?; |
218 | if krate.declaration_name(db).as_deref() != Some("core") { | 224 | if krate != famous_defs.core()? { |
219 | return None; | 225 | return None; |
220 | } | 226 | } |
221 | let iter_trait = FamousDefs(sema, krate).core_iter_Iterator()?; | 227 | let iter_trait = famous_defs.core_iter_Iterator()?; |
222 | let iter_mod = FamousDefs(sema, krate).core_iter()?; | 228 | let iter_mod = famous_defs.core_iter()?; |
223 | // assert this struct comes from `core::iter` | 229 | // assert this struct comes from `core::iter` |
224 | iter_mod.visibility_of(db, &strukt.into()).filter(|&vis| vis == hir::Visibility::Public)?; | 230 | iter_mod.visibility_of(db, &strukt.into()).filter(|&vis| vis == hir::Visibility::Public)?; |
225 | if ty.impls_trait(db, iter_trait, &[]) { | 231 | if ty.impls_trait(db, iter_trait, &[]) { |
@@ -231,7 +237,7 @@ fn hint_iterator( | |||
231 | const LABEL_START: &str = "impl Iterator<Item = "; | 237 | const LABEL_START: &str = "impl Iterator<Item = "; |
232 | const LABEL_END: &str = ">"; | 238 | const LABEL_END: &str = ">"; |
233 | 239 | ||
234 | let ty_display = hint_iterator(sema, config, &ty) | 240 | let ty_display = hint_iterator(sema, famous_defs, config, &ty) |
235 | .map(|assoc_type_impl| assoc_type_impl.to_string()) | 241 | .map(|assoc_type_impl| assoc_type_impl.to_string()) |
236 | .unwrap_or_else(|| { | 242 | .unwrap_or_else(|| { |
237 | ty.display_truncated( | 243 | ty.display_truncated( |
@@ -372,7 +378,11 @@ fn is_enum_name_similar_to_param_name( | |||
372 | fn get_string_representation(expr: &ast::Expr) -> Option<String> { | 378 | fn get_string_representation(expr: &ast::Expr) -> Option<String> { |
373 | match expr { | 379 | match expr { |
374 | ast::Expr::MethodCallExpr(method_call_expr) => { | 380 | ast::Expr::MethodCallExpr(method_call_expr) => { |
375 | Some(method_call_expr.name_ref()?.to_string()) | 381 | let name_ref = method_call_expr.name_ref()?; |
382 | match name_ref.text().as_str() { | ||
383 | "clone" => method_call_expr.receiver().map(|rec| rec.to_string()), | ||
384 | name_ref => Some(name_ref.to_owned()), | ||
385 | } | ||
376 | } | 386 | } |
377 | ast::Expr::RefExpr(ref_expr) => get_string_representation(&ref_expr.expr()?), | 387 | ast::Expr::RefExpr(ref_expr) => get_string_representation(&ref_expr.expr()?), |
378 | _ => Some(expr.to_string()), | 388 | _ => Some(expr.to_string()), |
@@ -1202,4 +1212,27 @@ fn main() { | |||
1202 | "#, | 1212 | "#, |
1203 | ); | 1213 | ); |
1204 | } | 1214 | } |
1215 | |||
1216 | #[test] | ||
1217 | fn hide_param_hints_for_clones() { | ||
1218 | check_with_config( | ||
1219 | InlayHintsConfig { | ||
1220 | parameter_hints: true, | ||
1221 | type_hints: false, | ||
1222 | chaining_hints: false, | ||
1223 | max_length: None, | ||
1224 | }, | ||
1225 | r#" | ||
1226 | fn foo(bar: i32, baz: String, qux: f32) {} | ||
1227 | |||
1228 | fn main() { | ||
1229 | let bar = 3; | ||
1230 | let baz = &"baz"; | ||
1231 | let fez = 1.0; | ||
1232 | foo(bar.clone(), baz.clone(), fez.clone()); | ||
1233 | //^^^^^^^^^^^ qux | ||
1234 | } | ||
1235 | "#, | ||
1236 | ); | ||
1237 | } | ||
1205 | } | 1238 | } |
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index aaf9b3b4b..4bc733b70 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs | |||
@@ -23,8 +23,6 @@ mod prime_caches; | |||
23 | mod display; | 23 | mod display; |
24 | 24 | ||
25 | mod call_hierarchy; | 25 | mod call_hierarchy; |
26 | mod call_info; | ||
27 | mod completion; | ||
28 | mod diagnostics; | 26 | mod diagnostics; |
29 | mod expand_macro; | 27 | mod expand_macro; |
30 | mod extend_selection; | 28 | mod extend_selection; |
@@ -50,11 +48,11 @@ mod doc_links; | |||
50 | 48 | ||
51 | use std::sync::Arc; | 49 | use std::sync::Arc; |
52 | 50 | ||
53 | use base_db::{ | 51 | use cfg::CfgOptions; |
52 | use ide_db::base_db::{ | ||
54 | salsa::{self, ParallelDatabase}, | 53 | salsa::{self, ParallelDatabase}, |
55 | CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath, | 54 | CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath, |
56 | }; | 55 | }; |
57 | use cfg::CfgOptions; | ||
58 | use ide_db::{ | 56 | use ide_db::{ |
59 | symbol_index::{self, FileSymbol}, | 57 | symbol_index::{self, FileSymbol}, |
60 | LineIndexDatabase, | 58 | LineIndexDatabase, |
@@ -65,10 +63,6 @@ use crate::display::ToNav; | |||
65 | 63 | ||
66 | pub use crate::{ | 64 | pub use crate::{ |
67 | call_hierarchy::CallItem, | 65 | call_hierarchy::CallItem, |
68 | call_info::CallInfo, | ||
69 | completion::{ | ||
70 | CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat, | ||
71 | }, | ||
72 | diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity}, | 66 | diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity}, |
73 | display::NavigationTarget, | 67 | display::NavigationTarget, |
74 | expand_macro::ExpandedMacro, | 68 | expand_macro::ExpandedMacro, |
@@ -86,15 +80,19 @@ pub use crate::{ | |||
86 | Highlight, HighlightModifier, HighlightModifiers, HighlightTag, HighlightedRange, | 80 | Highlight, HighlightModifier, HighlightModifiers, HighlightTag, HighlightedRange, |
87 | }, | 81 | }, |
88 | }; | 82 | }; |
83 | pub use completion::{ | ||
84 | CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat, | ||
85 | }; | ||
86 | pub use ide_db::call_info::CallInfo; | ||
89 | 87 | ||
90 | pub use assists::{ | 88 | pub use assists::{ |
91 | utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist, | 89 | utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist, |
92 | }; | 90 | }; |
93 | pub use base_db::{ | 91 | pub use hir::{Documentation, Semantics}; |
92 | pub use ide_db::base_db::{ | ||
94 | Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot, | 93 | Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot, |
95 | SourceRootId, | 94 | SourceRootId, |
96 | }; | 95 | }; |
97 | pub use hir::{Documentation, Semantics}; | ||
98 | pub use ide_db::{ | 96 | pub use ide_db::{ |
99 | label::Label, | 97 | label::Label, |
100 | line_index::{LineCol, LineIndex}, | 98 | line_index::{LineCol, LineIndex}, |
@@ -398,7 +396,7 @@ impl Analysis { | |||
398 | 396 | ||
399 | /// Computes parameter information for the given call expression. | 397 | /// Computes parameter information for the given call expression. |
400 | pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> { | 398 | pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> { |
401 | self.with_db(|db| call_info::call_info(db, position)) | 399 | self.with_db(|db| ide_db::call_info::call_info(db, position)) |
402 | } | 400 | } |
403 | 401 | ||
404 | /// Computes call hierarchy candidates for the given file position. | 402 | /// Computes call hierarchy candidates for the given file position. |
diff --git a/crates/ide/src/parent_module.rs b/crates/ide/src/parent_module.rs index ef94acfec..6cc3b2991 100644 --- a/crates/ide/src/parent_module.rs +++ b/crates/ide/src/parent_module.rs | |||
@@ -1,5 +1,5 @@ | |||
1 | use base_db::{CrateId, FileId, FilePosition}; | ||
2 | use hir::Semantics; | 1 | use hir::Semantics; |
2 | use ide_db::base_db::{CrateId, FileId, FilePosition}; | ||
3 | use ide_db::RootDatabase; | 3 | use ide_db::RootDatabase; |
4 | use syntax::{ | 4 | use syntax::{ |
5 | algo::find_node_at_offset, | 5 | algo::find_node_at_offset, |
diff --git a/crates/ide/src/prime_caches.rs b/crates/ide/src/prime_caches.rs index 9687c2734..ea0acfaa0 100644 --- a/crates/ide/src/prime_caches.rs +++ b/crates/ide/src/prime_caches.rs | |||
@@ -3,8 +3,8 @@ | |||
3 | //! request takes longer to compute. This modules implemented prepopulating of | 3 | //! request takes longer to compute. This modules implemented prepopulating of |
4 | //! various caches, it's not really advanced at the moment. | 4 | //! various caches, it's not really advanced at the moment. |
5 | 5 | ||
6 | use base_db::SourceDatabase; | ||
7 | use hir::db::DefDatabase; | 6 | use hir::db::DefDatabase; |
7 | use ide_db::base_db::SourceDatabase; | ||
8 | 8 | ||
9 | use crate::RootDatabase; | 9 | use crate::RootDatabase; |
10 | 10 | ||
@@ -32,8 +32,7 @@ pub(crate) fn prime_caches(db: &RootDatabase, cb: &(dyn Fn(PrimeCachesProgress) | |||
32 | // Unfortunately rayon prevents panics from propagation out of a `scope`, which breaks | 32 | // Unfortunately rayon prevents panics from propagation out of a `scope`, which breaks |
33 | // cancellation, so we cannot use rayon. | 33 | // cancellation, so we cannot use rayon. |
34 | for (i, krate) in topo.iter().enumerate() { | 34 | for (i, krate) in topo.iter().enumerate() { |
35 | let crate_name = | 35 | let crate_name = graph[*krate].display_name.as_deref().unwrap_or_default().to_string(); |
36 | graph[*krate].declaration_name.as_ref().map(ToString::to_string).unwrap_or_default(); | ||
37 | 36 | ||
38 | cb(PrimeCachesProgress::StartedOnCrate { | 37 | cb(PrimeCachesProgress::StartedOnCrate { |
39 | on_crate: crate_name, | 38 | on_crate: crate_name, |
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 67ec257a8..a517081d5 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs | |||
@@ -191,8 +191,8 @@ fn get_struct_def_name_for_struct_literal_search( | |||
191 | 191 | ||
192 | #[cfg(test)] | 192 | #[cfg(test)] |
193 | mod tests { | 193 | mod tests { |
194 | use base_db::FileId; | ||
195 | use expect_test::{expect, Expect}; | 194 | use expect_test::{expect, Expect}; |
195 | use ide_db::base_db::FileId; | ||
196 | use stdx::format_to; | 196 | use stdx::format_to; |
197 | 197 | ||
198 | use crate::{fixture, SearchScope}; | 198 | use crate::{fixture, SearchScope}; |
diff --git a/crates/ide/src/references/rename.rs b/crates/ide/src/references/rename.rs index 35aafc49d..26ac2371a 100644 --- a/crates/ide/src/references/rename.rs +++ b/crates/ide/src/references/rename.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use base_db::SourceDatabaseExt; | ||
4 | use hir::{Module, ModuleDef, ModuleSource, Semantics}; | 3 | use hir::{Module, ModuleDef, ModuleSource, Semantics}; |
4 | use ide_db::base_db::SourceDatabaseExt; | ||
5 | use ide_db::{ | 5 | use ide_db::{ |
6 | defs::{Definition, NameClass, NameRefClass}, | 6 | defs::{Definition, NameClass, NameRefClass}, |
7 | RootDatabase, | 7 | RootDatabase, |
diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 752ef2f21..eb82456ad 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs | |||
@@ -15,7 +15,7 @@ use crate::{display::ToNav, FileId, NavigationTarget}; | |||
15 | pub struct Runnable { | 15 | pub struct Runnable { |
16 | pub nav: NavigationTarget, | 16 | pub nav: NavigationTarget, |
17 | pub kind: RunnableKind, | 17 | pub kind: RunnableKind, |
18 | pub cfg_exprs: Vec<CfgExpr>, | 18 | pub cfg: Option<CfgExpr>, |
19 | } | 19 | } |
20 | 20 | ||
21 | #[derive(Debug, Clone)] | 21 | #[derive(Debug, Clone)] |
@@ -168,7 +168,7 @@ fn runnable_fn( | |||
168 | }; | 168 | }; |
169 | 169 | ||
170 | let attrs = Attrs::from_attrs_owner(sema.db, InFile::new(HirFileId::from(file_id), &fn_def)); | 170 | let attrs = Attrs::from_attrs_owner(sema.db, InFile::new(HirFileId::from(file_id), &fn_def)); |
171 | let cfg_exprs = attrs.cfg().collect(); | 171 | let cfg = attrs.cfg(); |
172 | 172 | ||
173 | let nav = if let RunnableKind::DocTest { .. } = kind { | 173 | let nav = if let RunnableKind::DocTest { .. } = kind { |
174 | NavigationTarget::from_doc_commented( | 174 | NavigationTarget::from_doc_commented( |
@@ -179,7 +179,7 @@ fn runnable_fn( | |||
179 | } else { | 179 | } else { |
180 | NavigationTarget::from_named(sema.db, InFile::new(file_id.into(), &fn_def)) | 180 | NavigationTarget::from_named(sema.db, InFile::new(file_id.into(), &fn_def)) |
181 | }; | 181 | }; |
182 | Some(Runnable { nav, kind, cfg_exprs }) | 182 | Some(Runnable { nav, kind, cfg }) |
183 | } | 183 | } |
184 | 184 | ||
185 | #[derive(Debug, Copy, Clone)] | 185 | #[derive(Debug, Copy, Clone)] |
@@ -255,9 +255,9 @@ fn runnable_mod( | |||
255 | .join("::"); | 255 | .join("::"); |
256 | 256 | ||
257 | let attrs = Attrs::from_attrs_owner(sema.db, InFile::new(HirFileId::from(file_id), &module)); | 257 | let attrs = Attrs::from_attrs_owner(sema.db, InFile::new(HirFileId::from(file_id), &module)); |
258 | let cfg_exprs = attrs.cfg().collect(); | 258 | let cfg = attrs.cfg(); |
259 | let nav = module_def.to_nav(sema.db); | 259 | let nav = module_def.to_nav(sema.db); |
260 | Some(Runnable { nav, kind: RunnableKind::TestMod { path }, cfg_exprs }) | 260 | Some(Runnable { nav, kind: RunnableKind::TestMod { path }, cfg }) |
261 | } | 261 | } |
262 | 262 | ||
263 | // We could create runnables for modules with number_of_test_submodules > 0, | 263 | // We could create runnables for modules with number_of_test_submodules > 0, |
@@ -348,7 +348,7 @@ fn bench() {} | |||
348 | docs: None, | 348 | docs: None, |
349 | }, | 349 | }, |
350 | kind: Bin, | 350 | kind: Bin, |
351 | cfg_exprs: [], | 351 | cfg: None, |
352 | }, | 352 | }, |
353 | Runnable { | 353 | Runnable { |
354 | nav: NavigationTarget { | 354 | nav: NavigationTarget { |
@@ -373,7 +373,7 @@ fn bench() {} | |||
373 | ignore: false, | 373 | ignore: false, |
374 | }, | 374 | }, |
375 | }, | 375 | }, |
376 | cfg_exprs: [], | 376 | cfg: None, |
377 | }, | 377 | }, |
378 | Runnable { | 378 | Runnable { |
379 | nav: NavigationTarget { | 379 | nav: NavigationTarget { |
@@ -398,7 +398,7 @@ fn bench() {} | |||
398 | ignore: true, | 398 | ignore: true, |
399 | }, | 399 | }, |
400 | }, | 400 | }, |
401 | cfg_exprs: [], | 401 | cfg: None, |
402 | }, | 402 | }, |
403 | Runnable { | 403 | Runnable { |
404 | nav: NavigationTarget { | 404 | nav: NavigationTarget { |
@@ -420,7 +420,7 @@ fn bench() {} | |||
420 | "bench", | 420 | "bench", |
421 | ), | 421 | ), |
422 | }, | 422 | }, |
423 | cfg_exprs: [], | 423 | cfg: None, |
424 | }, | 424 | }, |
425 | ] | 425 | ] |
426 | "#]], | 426 | "#]], |
@@ -507,7 +507,7 @@ fn should_have_no_runnable_6() {} | |||
507 | docs: None, | 507 | docs: None, |
508 | }, | 508 | }, |
509 | kind: Bin, | 509 | kind: Bin, |
510 | cfg_exprs: [], | 510 | cfg: None, |
511 | }, | 511 | }, |
512 | Runnable { | 512 | Runnable { |
513 | nav: NavigationTarget { | 513 | nav: NavigationTarget { |
@@ -527,7 +527,7 @@ fn should_have_no_runnable_6() {} | |||
527 | "should_have_runnable", | 527 | "should_have_runnable", |
528 | ), | 528 | ), |
529 | }, | 529 | }, |
530 | cfg_exprs: [], | 530 | cfg: None, |
531 | }, | 531 | }, |
532 | Runnable { | 532 | Runnable { |
533 | nav: NavigationTarget { | 533 | nav: NavigationTarget { |
@@ -547,7 +547,7 @@ fn should_have_no_runnable_6() {} | |||
547 | "should_have_runnable_1", | 547 | "should_have_runnable_1", |
548 | ), | 548 | ), |
549 | }, | 549 | }, |
550 | cfg_exprs: [], | 550 | cfg: None, |
551 | }, | 551 | }, |
552 | Runnable { | 552 | Runnable { |
553 | nav: NavigationTarget { | 553 | nav: NavigationTarget { |
@@ -567,7 +567,7 @@ fn should_have_no_runnable_6() {} | |||
567 | "should_have_runnable_2", | 567 | "should_have_runnable_2", |
568 | ), | 568 | ), |
569 | }, | 569 | }, |
570 | cfg_exprs: [], | 570 | cfg: None, |
571 | }, | 571 | }, |
572 | ] | 572 | ] |
573 | "#]], | 573 | "#]], |
@@ -609,7 +609,7 @@ impl Data { | |||
609 | docs: None, | 609 | docs: None, |
610 | }, | 610 | }, |
611 | kind: Bin, | 611 | kind: Bin, |
612 | cfg_exprs: [], | 612 | cfg: None, |
613 | }, | 613 | }, |
614 | Runnable { | 614 | Runnable { |
615 | nav: NavigationTarget { | 615 | nav: NavigationTarget { |
@@ -629,7 +629,7 @@ impl Data { | |||
629 | "Data::foo", | 629 | "Data::foo", |
630 | ), | 630 | ), |
631 | }, | 631 | }, |
632 | cfg_exprs: [], | 632 | cfg: None, |
633 | }, | 633 | }, |
634 | ] | 634 | ] |
635 | "#]], | 635 | "#]], |
@@ -668,7 +668,7 @@ mod test_mod { | |||
668 | kind: TestMod { | 668 | kind: TestMod { |
669 | path: "test_mod", | 669 | path: "test_mod", |
670 | }, | 670 | }, |
671 | cfg_exprs: [], | 671 | cfg: None, |
672 | }, | 672 | }, |
673 | Runnable { | 673 | Runnable { |
674 | nav: NavigationTarget { | 674 | nav: NavigationTarget { |
@@ -693,7 +693,7 @@ mod test_mod { | |||
693 | ignore: false, | 693 | ignore: false, |
694 | }, | 694 | }, |
695 | }, | 695 | }, |
696 | cfg_exprs: [], | 696 | cfg: None, |
697 | }, | 697 | }, |
698 | ] | 698 | ] |
699 | "#]], | 699 | "#]], |
@@ -748,7 +748,7 @@ mod root_tests { | |||
748 | kind: TestMod { | 748 | kind: TestMod { |
749 | path: "root_tests::nested_tests_0", | 749 | path: "root_tests::nested_tests_0", |
750 | }, | 750 | }, |
751 | cfg_exprs: [], | 751 | cfg: None, |
752 | }, | 752 | }, |
753 | Runnable { | 753 | Runnable { |
754 | nav: NavigationTarget { | 754 | nav: NavigationTarget { |
@@ -768,7 +768,7 @@ mod root_tests { | |||
768 | kind: TestMod { | 768 | kind: TestMod { |
769 | path: "root_tests::nested_tests_0::nested_tests_1", | 769 | path: "root_tests::nested_tests_0::nested_tests_1", |
770 | }, | 770 | }, |
771 | cfg_exprs: [], | 771 | cfg: None, |
772 | }, | 772 | }, |
773 | Runnable { | 773 | Runnable { |
774 | nav: NavigationTarget { | 774 | nav: NavigationTarget { |
@@ -793,7 +793,7 @@ mod root_tests { | |||
793 | ignore: false, | 793 | ignore: false, |
794 | }, | 794 | }, |
795 | }, | 795 | }, |
796 | cfg_exprs: [], | 796 | cfg: None, |
797 | }, | 797 | }, |
798 | Runnable { | 798 | Runnable { |
799 | nav: NavigationTarget { | 799 | nav: NavigationTarget { |
@@ -818,7 +818,7 @@ mod root_tests { | |||
818 | ignore: false, | 818 | ignore: false, |
819 | }, | 819 | }, |
820 | }, | 820 | }, |
821 | cfg_exprs: [], | 821 | cfg: None, |
822 | }, | 822 | }, |
823 | Runnable { | 823 | Runnable { |
824 | nav: NavigationTarget { | 824 | nav: NavigationTarget { |
@@ -838,7 +838,7 @@ mod root_tests { | |||
838 | kind: TestMod { | 838 | kind: TestMod { |
839 | path: "root_tests::nested_tests_0::nested_tests_2", | 839 | path: "root_tests::nested_tests_0::nested_tests_2", |
840 | }, | 840 | }, |
841 | cfg_exprs: [], | 841 | cfg: None, |
842 | }, | 842 | }, |
843 | Runnable { | 843 | Runnable { |
844 | nav: NavigationTarget { | 844 | nav: NavigationTarget { |
@@ -863,7 +863,7 @@ mod root_tests { | |||
863 | ignore: false, | 863 | ignore: false, |
864 | }, | 864 | }, |
865 | }, | 865 | }, |
866 | cfg_exprs: [], | 866 | cfg: None, |
867 | }, | 867 | }, |
868 | ] | 868 | ] |
869 | "#]], | 869 | "#]], |
@@ -906,12 +906,14 @@ fn test_foo1() {} | |||
906 | ignore: false, | 906 | ignore: false, |
907 | }, | 907 | }, |
908 | }, | 908 | }, |
909 | cfg_exprs: [ | 909 | cfg: Some( |
910 | KeyValue { | 910 | Atom( |
911 | key: "feature", | 911 | KeyValue { |
912 | value: "foo", | 912 | key: "feature", |
913 | }, | 913 | value: "foo", |
914 | ], | 914 | }, |
915 | ), | ||
916 | ), | ||
915 | }, | 917 | }, |
916 | ] | 918 | ] |
917 | "#]], | 919 | "#]], |
@@ -954,20 +956,24 @@ fn test_foo1() {} | |||
954 | ignore: false, | 956 | ignore: false, |
955 | }, | 957 | }, |
956 | }, | 958 | }, |
957 | cfg_exprs: [ | 959 | cfg: Some( |
958 | All( | 960 | All( |
959 | [ | 961 | [ |
960 | KeyValue { | 962 | Atom( |
961 | key: "feature", | 963 | KeyValue { |
962 | value: "foo", | 964 | key: "feature", |
963 | }, | 965 | value: "foo", |
964 | KeyValue { | 966 | }, |
965 | key: "feature", | 967 | ), |
966 | value: "bar", | 968 | Atom( |
967 | }, | 969 | KeyValue { |
970 | key: "feature", | ||
971 | value: "bar", | ||
972 | }, | ||
973 | ), | ||
968 | ], | 974 | ], |
969 | ), | 975 | ), |
970 | ], | 976 | ), |
971 | }, | 977 | }, |
972 | ] | 978 | ] |
973 | "#]], | 979 | "#]], |
diff --git a/crates/ide/src/status.rs b/crates/ide/src/status.rs index f67f10491..8e91c99d7 100644 --- a/crates/ide/src/status.rs +++ b/crates/ide/src/status.rs | |||
@@ -1,10 +1,10 @@ | |||
1 | use std::{fmt, iter::FromIterator, sync::Arc}; | 1 | use std::{fmt, iter::FromIterator, sync::Arc}; |
2 | 2 | ||
3 | use base_db::{ | 3 | use hir::MacroFile; |
4 | use ide_db::base_db::{ | ||
4 | salsa::debug::{DebugQueryTable, TableEntry}, | 5 | salsa::debug::{DebugQueryTable, TableEntry}, |
5 | CrateId, FileId, FileTextQuery, SourceDatabase, SourceRootId, | 6 | CrateId, FileId, FileTextQuery, SourceDatabase, SourceRootId, |
6 | }; | 7 | }; |
7 | use hir::MacroFile; | ||
8 | use ide_db::{ | 8 | use ide_db::{ |
9 | symbol_index::{LibrarySymbolsQuery, SymbolIndex}, | 9 | symbol_index::{LibrarySymbolsQuery, SymbolIndex}, |
10 | RootDatabase, | 10 | RootDatabase, |
@@ -16,7 +16,7 @@ use stdx::format_to; | |||
16 | use syntax::{ast, Parse, SyntaxNode}; | 16 | use syntax::{ast, Parse, SyntaxNode}; |
17 | 17 | ||
18 | fn syntax_tree_stats(db: &RootDatabase) -> SyntaxTreeStats { | 18 | fn syntax_tree_stats(db: &RootDatabase) -> SyntaxTreeStats { |
19 | base_db::ParseQuery.in_db(db).entries::<SyntaxTreeStats>() | 19 | ide_db::base_db::ParseQuery.in_db(db).entries::<SyntaxTreeStats>() |
20 | } | 20 | } |
21 | fn macro_syntax_tree_stats(db: &RootDatabase) -> SyntaxTreeStats { | 21 | fn macro_syntax_tree_stats(db: &RootDatabase) -> SyntaxTreeStats { |
22 | hir::db::ParseMacroQuery.in_db(db).entries::<SyntaxTreeStats>() | 22 | hir::db::ParseMacroQuery.in_db(db).entries::<SyntaxTreeStats>() |
@@ -45,7 +45,7 @@ pub(crate) fn status(db: &RootDatabase, file_id: Option<FileId>) -> String { | |||
45 | match krate { | 45 | match krate { |
46 | Some(krate) => { | 46 | Some(krate) => { |
47 | let crate_graph = db.crate_graph(); | 47 | let crate_graph = db.crate_graph(); |
48 | let display_crate = |krate: CrateId| match &crate_graph[krate].declaration_name { | 48 | let display_crate = |krate: CrateId| match &crate_graph[krate].display_name { |
49 | Some(it) => format!("{}({:?})", it, krate), | 49 | Some(it) => format!("{}({:?})", it, krate), |
50 | None => format!("{:?}", krate), | 50 | None => format!("{:?}", krate), |
51 | }; | 51 | }; |
diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs index b35c03162..9f864179e 100644 --- a/crates/ide/src/syntax_highlighting.rs +++ b/crates/ide/src/syntax_highlighting.rs | |||
@@ -579,7 +579,14 @@ fn highlight_element( | |||
579 | } | 579 | } |
580 | } | 580 | } |
581 | T![-] if element.parent().and_then(ast::PrefixExpr::cast).is_some() => { | 581 | T![-] if element.parent().and_then(ast::PrefixExpr::cast).is_some() => { |
582 | HighlightTag::NumericLiteral.into() | 582 | let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?; |
583 | |||
584 | let expr = prefix_expr.expr()?; | ||
585 | match expr { | ||
586 | ast::Expr::Literal(_) => HighlightTag::NumericLiteral, | ||
587 | _ => HighlightTag::Operator, | ||
588 | } | ||
589 | .into() | ||
583 | } | 590 | } |
584 | _ if element.parent().and_then(ast::PrefixExpr::cast).is_some() => { | 591 | _ if element.parent().and_then(ast::PrefixExpr::cast).is_some() => { |
585 | HighlightTag::Operator.into() | 592 | HighlightTag::Operator.into() |
@@ -763,6 +770,9 @@ fn highlight_def(db: &RootDatabase, def: Definition) -> Highlight { | |||
763 | if local.is_mut(db) || local.ty(db).is_mutable_reference() { | 770 | if local.is_mut(db) || local.ty(db).is_mutable_reference() { |
764 | h |= HighlightModifier::Mutable; | 771 | h |= HighlightModifier::Mutable; |
765 | } | 772 | } |
773 | if local.ty(db).as_callable(db).is_some() || local.ty(db).impls_fnonce(db) { | ||
774 | h |= HighlightModifier::Callable; | ||
775 | } | ||
766 | return h; | 776 | return h; |
767 | } | 777 | } |
768 | } | 778 | } |
diff --git a/crates/ide/src/syntax_highlighting/html.rs b/crates/ide/src/syntax_highlighting/html.rs index 57e2d2923..abcc5cccc 100644 --- a/crates/ide/src/syntax_highlighting/html.rs +++ b/crates/ide/src/syntax_highlighting/html.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | //! Renders a bit of code as HTML. | 1 | //! Renders a bit of code as HTML. |
2 | 2 | ||
3 | use base_db::SourceDatabase; | 3 | use ide_db::base_db::SourceDatabase; |
4 | use oorandom::Rand32; | 4 | use oorandom::Rand32; |
5 | use stdx::format_to; | 5 | use stdx::format_to; |
6 | use syntax::{AstNode, TextRange, TextSize}; | 6 | use syntax::{AstNode, TextRange, TextSize}; |
diff --git a/crates/ide/src/syntax_highlighting/injection.rs b/crates/ide/src/syntax_highlighting/injection.rs index 43f4e6fea..59a74bc02 100644 --- a/crates/ide/src/syntax_highlighting/injection.rs +++ b/crates/ide/src/syntax_highlighting/injection.rs | |||
@@ -4,13 +4,11 @@ use std::{collections::BTreeMap, convert::TryFrom}; | |||
4 | 4 | ||
5 | use ast::{HasQuotes, HasStringValue}; | 5 | use ast::{HasQuotes, HasStringValue}; |
6 | use hir::Semantics; | 6 | use hir::Semantics; |
7 | use ide_db::call_info::ActiveParameter; | ||
7 | use itertools::Itertools; | 8 | use itertools::Itertools; |
8 | use syntax::{ast, AstToken, SyntaxNode, SyntaxToken, TextRange, TextSize}; | 9 | use syntax::{ast, AstToken, SyntaxNode, SyntaxToken, TextRange, TextSize}; |
9 | 10 | ||
10 | use crate::{ | 11 | use crate::{Analysis, Highlight, HighlightModifier, HighlightTag, HighlightedRange, RootDatabase}; |
11 | call_info::ActiveParameter, Analysis, Highlight, HighlightModifier, HighlightTag, | ||
12 | HighlightedRange, RootDatabase, | ||
13 | }; | ||
14 | 12 | ||
15 | use super::HighlightedRangeStack; | 13 | use super::HighlightedRangeStack; |
16 | 14 | ||
diff --git a/crates/ide/src/syntax_highlighting/tags.rs b/crates/ide/src/syntax_highlighting/tags.rs index c1b817f06..e8f78ad52 100644 --- a/crates/ide/src/syntax_highlighting/tags.rs +++ b/crates/ide/src/syntax_highlighting/tags.rs | |||
@@ -64,6 +64,7 @@ pub enum HighlightModifier { | |||
64 | Mutable, | 64 | Mutable, |
65 | Consuming, | 65 | Consuming, |
66 | Unsafe, | 66 | Unsafe, |
67 | Callable, | ||
67 | } | 68 | } |
68 | 69 | ||
69 | impl HighlightTag { | 70 | impl HighlightTag { |
@@ -122,6 +123,7 @@ impl HighlightModifier { | |||
122 | HighlightModifier::Mutable, | 123 | HighlightModifier::Mutable, |
123 | HighlightModifier::Consuming, | 124 | HighlightModifier::Consuming, |
124 | HighlightModifier::Unsafe, | 125 | HighlightModifier::Unsafe, |
126 | HighlightModifier::Callable, | ||
125 | ]; | 127 | ]; |
126 | 128 | ||
127 | fn as_str(self) -> &'static str { | 129 | fn as_str(self) -> &'static str { |
@@ -134,6 +136,7 @@ impl HighlightModifier { | |||
134 | HighlightModifier::Mutable => "mutable", | 136 | HighlightModifier::Mutable => "mutable", |
135 | HighlightModifier::Consuming => "consuming", | 137 | HighlightModifier::Consuming => "consuming", |
136 | HighlightModifier::Unsafe => "unsafe", | 138 | HighlightModifier::Unsafe => "unsafe", |
139 | HighlightModifier::Callable => "callable", | ||
137 | } | 140 | } |
138 | } | 141 | } |
139 | 142 | ||
diff --git a/crates/ide/src/syntax_highlighting/test_data/highlighting.html b/crates/ide/src/syntax_highlighting/test_data/highlighting.html index 0bb0928e4..c6b4f5a00 100644 --- a/crates/ide/src/syntax_highlighting/test_data/highlighting.html +++ b/crates/ide/src/syntax_highlighting/test_data/highlighting.html | |||
@@ -44,6 +44,17 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd | |||
44 | <span class="keyword">pub</span> <span class="keyword">trait</span> <span class="trait declaration">Copy</span> <span class="punctuation">{</span><span class="punctuation">}</span> | 44 | <span class="keyword">pub</span> <span class="keyword">trait</span> <span class="trait declaration">Copy</span> <span class="punctuation">{</span><span class="punctuation">}</span> |
45 | <span class="punctuation">}</span> | 45 | <span class="punctuation">}</span> |
46 | 46 | ||
47 | <span class="keyword">pub</span> <span class="keyword">mod</span> <span class="module declaration">ops</span> <span class="punctuation">{</span> | ||
48 | <span class="attribute">#</span><span class="attribute">[</span><span class="function attribute">lang</span><span class="attribute"> </span><span class="operator">=</span><span class="attribute"> </span><span class="string_literal">"fn_once"</span><span class="attribute">]</span> | ||
49 | <span class="keyword">pub</span> <span class="keyword">trait</span> <span class="trait declaration">FnOnce</span><span class="punctuation"><</span><span class="type_param declaration">Args</span><span class="punctuation">></span> <span class="punctuation">{</span><span class="punctuation">}</span> | ||
50 | |||
51 | <span class="attribute">#</span><span class="attribute">[</span><span class="function attribute">lang</span><span class="attribute"> </span><span class="operator">=</span><span class="attribute"> </span><span class="string_literal">"fn_mut"</span><span class="attribute">]</span> | ||
52 | <span class="keyword">pub</span> <span class="keyword">trait</span> <span class="trait declaration">FnMut</span><span class="punctuation"><</span><span class="type_param declaration">Args</span><span class="punctuation">></span><span class="punctuation">:</span> <span class="trait">FnOnce</span><span class="punctuation"><</span><span class="type_param">Args</span><span class="punctuation">></span> <span class="punctuation">{</span><span class="punctuation">}</span> | ||
53 | |||
54 | <span class="attribute">#</span><span class="attribute">[</span><span class="function attribute">lang</span><span class="attribute"> </span><span class="operator">=</span><span class="attribute"> </span><span class="string_literal">"fn"</span><span class="attribute">]</span> | ||
55 | <span class="keyword">pub</span> <span class="keyword">trait</span> <span class="trait declaration">Fn</span><span class="punctuation"><</span><span class="type_param declaration">Args</span><span class="punctuation">></span><span class="punctuation">:</span> <span class="trait">FnMut</span><span class="punctuation"><</span><span class="type_param">Args</span><span class="punctuation">></span> <span class="punctuation">{</span><span class="punctuation">}</span> | ||
56 | <span class="punctuation">}</span> | ||
57 | |||
47 | 58 | ||
48 | <span class="keyword">struct</span> <span class="struct declaration">Foo</span> <span class="punctuation">{</span> | 59 | <span class="keyword">struct</span> <span class="struct declaration">Foo</span> <span class="punctuation">{</span> |
49 | <span class="keyword">pub</span> <span class="field declaration">x</span><span class="punctuation">:</span> <span class="builtin_type">i32</span><span class="punctuation">,</span> | 60 | <span class="keyword">pub</span> <span class="field declaration">x</span><span class="punctuation">:</span> <span class="builtin_type">i32</span><span class="punctuation">,</span> |
@@ -99,6 +110,11 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd | |||
99 | <span class="function">foo</span><span class="operator">::</span><span class="punctuation"><</span><span class="lifetime">'a</span><span class="punctuation">,</span> <span class="builtin_type">i32</span><span class="punctuation">></span><span class="punctuation">(</span><span class="punctuation">)</span> | 110 | <span class="function">foo</span><span class="operator">::</span><span class="punctuation"><</span><span class="lifetime">'a</span><span class="punctuation">,</span> <span class="builtin_type">i32</span><span class="punctuation">></span><span class="punctuation">(</span><span class="punctuation">)</span> |
100 | <span class="punctuation">}</span> | 111 | <span class="punctuation">}</span> |
101 | 112 | ||
113 | <span class="keyword">use</span> <span class="module">ops</span><span class="operator">::</span><span class="trait">Fn</span><span class="punctuation">;</span> | ||
114 | <span class="keyword">fn</span> <span class="function declaration">baz</span><span class="punctuation"><</span><span class="type_param declaration">F</span><span class="punctuation">:</span> <span class="trait">Fn</span><span class="punctuation">(</span><span class="punctuation">)</span> <span class="operator">-></span> <span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">></span><span class="punctuation">(</span><span class="value_param declaration callable">f</span><span class="punctuation">:</span> <span class="type_param">F</span><span class="punctuation">)</span> <span class="punctuation">{</span> | ||
115 | <span class="value_param callable">f</span><span class="punctuation">(</span><span class="punctuation">)</span> | ||
116 | <span class="punctuation">}</span> | ||
117 | |||
102 | <span class="macro">macro_rules!</span> <span class="macro declaration">def_fn</span> <span class="punctuation">{</span> | 118 | <span class="macro">macro_rules!</span> <span class="macro declaration">def_fn</span> <span class="punctuation">{</span> |
103 | <span class="punctuation">(</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">:</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">)</span> <span class="operator">=</span><span class="punctuation">></span> <span class="punctuation">{</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">}</span> | 119 | <span class="punctuation">(</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">:</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">)</span> <span class="operator">=</span><span class="punctuation">></span> <span class="punctuation">{</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">}</span> |
104 | <span class="punctuation">}</span> | 120 | <span class="punctuation">}</span> |
@@ -157,6 +173,12 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd | |||
157 | <span class="variable mutable">copy</span><span class="punctuation">.</span><span class="function">quop</span><span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">;</span> | 173 | <span class="variable mutable">copy</span><span class="punctuation">.</span><span class="function">quop</span><span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">;</span> |
158 | <span class="variable mutable">copy</span><span class="punctuation">.</span><span class="function mutable">qux</span><span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">;</span> | 174 | <span class="variable mutable">copy</span><span class="punctuation">.</span><span class="function mutable">qux</span><span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">;</span> |
159 | <span class="variable mutable">copy</span><span class="punctuation">.</span><span class="function">baz</span><span class="punctuation">(</span><span class="variable mutable">copy</span><span class="punctuation">)</span><span class="punctuation">;</span> | 175 | <span class="variable mutable">copy</span><span class="punctuation">.</span><span class="function">baz</span><span class="punctuation">(</span><span class="variable mutable">copy</span><span class="punctuation">)</span><span class="punctuation">;</span> |
176 | |||
177 | <span class="keyword">let</span> <span class="variable declaration callable">a</span> <span class="operator">=</span> <span class="punctuation">|</span><span class="value_param declaration">x</span><span class="punctuation">|</span> <span class="value_param">x</span><span class="punctuation">;</span> | ||
178 | <span class="keyword">let</span> <span class="variable declaration callable">bar</span> <span class="operator">=</span> <span class="struct">Foo</span><span class="operator">::</span><span class="function">baz</span><span class="punctuation">;</span> | ||
179 | |||
180 | <span class="keyword">let</span> <span class="variable declaration">baz</span> <span class="operator">=</span> <span class="numeric_literal">-</span><span class="numeric_literal">42</span><span class="punctuation">;</span> | ||
181 | <span class="keyword">let</span> <span class="variable declaration">baz</span> <span class="operator">=</span> <span class="operator">-</span><span class="variable">baz</span><span class="punctuation">;</span> | ||
160 | <span class="punctuation">}</span> | 182 | <span class="punctuation">}</span> |
161 | 183 | ||
162 | <span class="keyword">enum</span> <span class="enum declaration">Option</span><span class="punctuation"><</span><span class="type_param declaration">T</span><span class="punctuation">></span> <span class="punctuation">{</span> | 184 | <span class="keyword">enum</span> <span class="enum declaration">Option</span><span class="punctuation"><</span><span class="type_param declaration">T</span><span class="punctuation">></span> <span class="punctuation">{</span> |
diff --git a/crates/ide/src/syntax_highlighting/tests.rs b/crates/ide/src/syntax_highlighting/tests.rs index 126363b8b..dd43f9dd9 100644 --- a/crates/ide/src/syntax_highlighting/tests.rs +++ b/crates/ide/src/syntax_highlighting/tests.rs | |||
@@ -18,6 +18,17 @@ pub mod marker { | |||
18 | pub trait Copy {} | 18 | pub trait Copy {} |
19 | } | 19 | } |
20 | 20 | ||
21 | pub mod ops { | ||
22 | #[lang = "fn_once"] | ||
23 | pub trait FnOnce<Args> {} | ||
24 | |||
25 | #[lang = "fn_mut"] | ||
26 | pub trait FnMut<Args>: FnOnce<Args> {} | ||
27 | |||
28 | #[lang = "fn"] | ||
29 | pub trait Fn<Args>: FnMut<Args> {} | ||
30 | } | ||
31 | |||
21 | 32 | ||
22 | struct Foo { | 33 | struct Foo { |
23 | pub x: i32, | 34 | pub x: i32, |
@@ -73,6 +84,11 @@ fn foo<'a, T>() -> T { | |||
73 | foo::<'a, i32>() | 84 | foo::<'a, i32>() |
74 | } | 85 | } |
75 | 86 | ||
87 | use ops::Fn; | ||
88 | fn baz<F: Fn() -> ()>(f: F) { | ||
89 | f() | ||
90 | } | ||
91 | |||
76 | macro_rules! def_fn { | 92 | macro_rules! def_fn { |
77 | ($($tt:tt)*) => {$($tt)*} | 93 | ($($tt:tt)*) => {$($tt)*} |
78 | } | 94 | } |
@@ -131,6 +147,12 @@ fn main() { | |||
131 | copy.quop(); | 147 | copy.quop(); |
132 | copy.qux(); | 148 | copy.qux(); |
133 | copy.baz(copy); | 149 | copy.baz(copy); |
150 | |||
151 | let a = |x| x; | ||
152 | let bar = Foo::baz; | ||
153 | |||
154 | let baz = -42; | ||
155 | let baz = -baz; | ||
134 | } | 156 | } |
135 | 157 | ||
136 | enum Option<T> { | 158 | enum Option<T> { |
diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs index 0eed2dbd7..7941610d6 100644 --- a/crates/ide/src/syntax_tree.rs +++ b/crates/ide/src/syntax_tree.rs | |||
@@ -1,4 +1,4 @@ | |||
1 | use base_db::{FileId, SourceDatabase}; | 1 | use ide_db::base_db::{FileId, SourceDatabase}; |
2 | use ide_db::RootDatabase; | 2 | use ide_db::RootDatabase; |
3 | use syntax::{ | 3 | use syntax::{ |
4 | algo, AstNode, NodeOrToken, SourceFile, | 4 | algo, AstNode, NodeOrToken, SourceFile, |
diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs index 94b91f049..43458a3a2 100644 --- a/crates/ide/src/typing.rs +++ b/crates/ide/src/typing.rs | |||
@@ -15,7 +15,7 @@ | |||
15 | 15 | ||
16 | mod on_enter; | 16 | mod on_enter; |
17 | 17 | ||
18 | use base_db::{FilePosition, SourceDatabase}; | 18 | use ide_db::base_db::{FilePosition, SourceDatabase}; |
19 | use ide_db::{source_change::SourceFileEdit, RootDatabase}; | 19 | use ide_db::{source_change::SourceFileEdit, RootDatabase}; |
20 | use syntax::{ | 20 | use syntax::{ |
21 | algo::find_node_at_offset, | 21 | algo::find_node_at_offset, |
diff --git a/crates/ide/src/typing/on_enter.rs b/crates/ide/src/typing/on_enter.rs index 98adef1d6..f4ea30352 100644 --- a/crates/ide/src/typing/on_enter.rs +++ b/crates/ide/src/typing/on_enter.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | //! Handles the `Enter` key press. At the momently, this only continues | 1 | //! Handles the `Enter` key press. At the momently, this only continues |
2 | //! comments, but should handle indent some time in the future as well. | 2 | //! comments, but should handle indent some time in the future as well. |
3 | 3 | ||
4 | use base_db::{FilePosition, SourceDatabase}; | 4 | use ide_db::base_db::{FilePosition, SourceDatabase}; |
5 | use ide_db::RootDatabase; | 5 | use ide_db::RootDatabase; |
6 | use syntax::{ | 6 | use syntax::{ |
7 | ast::{self, AstToken}, | 7 | ast::{self, AstToken}, |
diff --git a/crates/ide_db/Cargo.toml b/crates/ide_db/Cargo.toml index 320fb15e5..72a9212f1 100644 --- a/crates/ide_db/Cargo.toml +++ b/crates/ide_db/Cargo.toml | |||
@@ -14,7 +14,7 @@ wasm = [] | |||
14 | 14 | ||
15 | [dependencies] | 15 | [dependencies] |
16 | log = "0.4.8" | 16 | log = "0.4.8" |
17 | rayon = "1.3.0" | 17 | rayon = "1.5.0" |
18 | fst = { version = "0.4", default-features = false } | 18 | fst = { version = "0.4", default-features = false } |
19 | rustc-hash = "1.1.0" | 19 | rustc-hash = "1.1.0" |
20 | once_cell = "1.3.1" | 20 | once_cell = "1.3.1" |
@@ -29,3 +29,6 @@ test_utils = { path = "../test_utils", version = "0.0.0" } | |||
29 | # ide should depend only on the top-level `hir` package. if you need | 29 | # ide should depend only on the top-level `hir` package. if you need |
30 | # something from some `hir_xxx` subpackage, reexport the API via `hir`. | 30 | # something from some `hir_xxx` subpackage, reexport the API via `hir`. |
31 | hir = { path = "../hir", version = "0.0.0" } | 31 | hir = { path = "../hir", version = "0.0.0" } |
32 | |||
33 | [dev-dependencies] | ||
34 | expect-test = "1.0" | ||
diff --git a/crates/ide/src/call_info.rs b/crates/ide_db/src/call_info.rs index d7b2b926e..83a602b9a 100644 --- a/crates/ide/src/call_info.rs +++ b/crates/ide_db/src/call_info.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! This crate provides primitives for tracking the information about a call site. |
2 | use base_db::FilePosition; | ||
2 | use either::Either; | 3 | use either::Either; |
3 | use hir::{HasAttrs, HirDisplay, Semantics, Type}; | 4 | use hir::{HasAttrs, HirDisplay, Semantics, Type}; |
4 | use ide_db::RootDatabase; | ||
5 | use stdx::format_to; | 5 | use stdx::format_to; |
6 | use syntax::{ | 6 | use syntax::{ |
7 | ast::{self, ArgListOwner}, | 7 | ast::{self, ArgListOwner}, |
@@ -9,7 +9,7 @@ use syntax::{ | |||
9 | }; | 9 | }; |
10 | use test_utils::mark; | 10 | use test_utils::mark; |
11 | 11 | ||
12 | use crate::FilePosition; | 12 | use crate::RootDatabase; |
13 | 13 | ||
14 | /// Contains information about a call site. Specifically the | 14 | /// Contains information about a call site. Specifically the |
15 | /// `FunctionSignature`and current parameter. | 15 | /// `FunctionSignature`and current parameter. |
@@ -40,7 +40,7 @@ impl CallInfo { | |||
40 | } | 40 | } |
41 | 41 | ||
42 | /// Computes parameter information for the given call expression. | 42 | /// Computes parameter information for the given call expression. |
43 | pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> { | 43 | pub fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> { |
44 | let sema = Semantics::new(db); | 44 | let sema = Semantics::new(db); |
45 | let file = sema.parse(position.file_id); | 45 | let file = sema.parse(position.file_id); |
46 | let file = file.syntax(); | 46 | let file = file.syntax(); |
@@ -141,13 +141,13 @@ fn call_info_impl( | |||
141 | } | 141 | } |
142 | 142 | ||
143 | #[derive(Debug)] | 143 | #[derive(Debug)] |
144 | pub(crate) struct ActiveParameter { | 144 | pub struct ActiveParameter { |
145 | pub(crate) ty: Type, | 145 | pub ty: Type, |
146 | pub(crate) name: String, | 146 | pub name: String, |
147 | } | 147 | } |
148 | 148 | ||
149 | impl ActiveParameter { | 149 | impl ActiveParameter { |
150 | pub(crate) fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> { | 150 | pub fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> { |
151 | let sema = Semantics::new(db); | 151 | let sema = Semantics::new(db); |
152 | let file = sema.parse(position.file_id); | 152 | let file = sema.parse(position.file_id); |
153 | let file = file.syntax(); | 153 | let file = file.syntax(); |
@@ -156,7 +156,7 @@ impl ActiveParameter { | |||
156 | Self::at_token(&sema, token) | 156 | Self::at_token(&sema, token) |
157 | } | 157 | } |
158 | 158 | ||
159 | pub(crate) fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> { | 159 | pub fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> { |
160 | let (signature, active_parameter) = call_info_impl(&sema, token)?; | 160 | let (signature, active_parameter) = call_info_impl(&sema, token)?; |
161 | 161 | ||
162 | let idx = active_parameter?; | 162 | let idx = active_parameter?; |
@@ -172,7 +172,7 @@ impl ActiveParameter { | |||
172 | } | 172 | } |
173 | 173 | ||
174 | #[derive(Debug)] | 174 | #[derive(Debug)] |
175 | pub(crate) enum FnCallNode { | 175 | pub enum FnCallNode { |
176 | CallExpr(ast::CallExpr), | 176 | CallExpr(ast::CallExpr), |
177 | MethodCallExpr(ast::MethodCallExpr), | 177 | MethodCallExpr(ast::MethodCallExpr), |
178 | } | 178 | } |
@@ -196,7 +196,7 @@ impl FnCallNode { | |||
196 | }) | 196 | }) |
197 | } | 197 | } |
198 | 198 | ||
199 | pub(crate) fn with_node_exact(node: &SyntaxNode) -> Option<FnCallNode> { | 199 | pub fn with_node_exact(node: &SyntaxNode) -> Option<FnCallNode> { |
200 | match_ast! { | 200 | match_ast! { |
201 | match node { | 201 | match node { |
202 | ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)), | 202 | ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)), |
@@ -206,7 +206,7 @@ impl FnCallNode { | |||
206 | } | 206 | } |
207 | } | 207 | } |
208 | 208 | ||
209 | pub(crate) fn name_ref(&self) -> Option<ast::NameRef> { | 209 | pub fn name_ref(&self) -> Option<ast::NameRef> { |
210 | match self { | 210 | match self { |
211 | FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? { | 211 | FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? { |
212 | ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?, | 212 | ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?, |
@@ -229,14 +229,28 @@ impl FnCallNode { | |||
229 | 229 | ||
230 | #[cfg(test)] | 230 | #[cfg(test)] |
231 | mod tests { | 231 | mod tests { |
232 | use crate::RootDatabase; | ||
233 | use base_db::{fixture::ChangeFixture, FilePosition}; | ||
232 | use expect_test::{expect, Expect}; | 234 | use expect_test::{expect, Expect}; |
233 | use test_utils::mark; | 235 | use test_utils::{mark, RangeOrOffset}; |
234 | 236 | ||
235 | use crate::fixture; | 237 | /// Creates analysis from a multi-file fixture, returns positions marked with <|>. |
238 | pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) { | ||
239 | let change_fixture = ChangeFixture::parse(ra_fixture); | ||
240 | let mut database = RootDatabase::default(); | ||
241 | database.apply_change(change_fixture.change); | ||
242 | let (file_id, range_or_offset) = | ||
243 | change_fixture.file_position.expect("expected a marker (<|>)"); | ||
244 | let offset = match range_or_offset { | ||
245 | RangeOrOffset::Range(_) => panic!(), | ||
246 | RangeOrOffset::Offset(it) => it, | ||
247 | }; | ||
248 | (database, FilePosition { file_id, offset }) | ||
249 | } | ||
236 | 250 | ||
237 | fn check(ra_fixture: &str, expect: Expect) { | 251 | fn check(ra_fixture: &str, expect: Expect) { |
238 | let (analysis, position) = fixture::position(ra_fixture); | 252 | let (db, position) = position(ra_fixture); |
239 | let call_info = analysis.call_info(position).unwrap(); | 253 | let call_info = crate::call_info::call_info(&db, position); |
240 | let actual = match call_info { | 254 | let actual = match call_info { |
241 | Some(call_info) => { | 255 | Some(call_info) => { |
242 | let docs = match &call_info.doc { | 256 | let docs = match &call_info.doc { |
diff --git a/crates/ide_db/src/lib.rs b/crates/ide_db/src/lib.rs index 7eff247c7..38ebdbf79 100644 --- a/crates/ide_db/src/lib.rs +++ b/crates/ide_db/src/lib.rs | |||
@@ -10,6 +10,9 @@ pub mod defs; | |||
10 | pub mod search; | 10 | pub mod search; |
11 | pub mod imports_locator; | 11 | pub mod imports_locator; |
12 | pub mod source_change; | 12 | pub mod source_change; |
13 | pub mod ty_filter; | ||
14 | pub mod traits; | ||
15 | pub mod call_info; | ||
13 | 16 | ||
14 | use std::{fmt, sync::Arc}; | 17 | use std::{fmt, sync::Arc}; |
15 | 18 | ||
@@ -23,6 +26,9 @@ use rustc_hash::FxHashSet; | |||
23 | 26 | ||
24 | use crate::{line_index::LineIndex, symbol_index::SymbolsDatabase}; | 27 | use crate::{line_index::LineIndex, symbol_index::SymbolsDatabase}; |
25 | 28 | ||
29 | /// `base_db` is normally also needed in places where `ide_db` is used, so this re-export is for convenience. | ||
30 | pub use base_db; | ||
31 | |||
26 | #[salsa::database( | 32 | #[salsa::database( |
27 | base_db::SourceDatabaseStorage, | 33 | base_db::SourceDatabaseStorage, |
28 | base_db::SourceDatabaseExtStorage, | 34 | base_db::SourceDatabaseExtStorage, |
diff --git a/crates/ide_db/src/traits.rs b/crates/ide_db/src/traits.rs new file mode 100644 index 000000000..f57b6dd91 --- /dev/null +++ b/crates/ide_db/src/traits.rs | |||
@@ -0,0 +1,227 @@ | |||
1 | //! Functionality for obtaining data related to traits from the DB. | ||
2 | |||
3 | use crate::RootDatabase; | ||
4 | use hir::Semantics; | ||
5 | use rustc_hash::FxHashSet; | ||
6 | use syntax::{ | ||
7 | ast::{self, NameOwner}, | ||
8 | AstNode, | ||
9 | }; | ||
10 | |||
11 | /// Given the `impl` block, attempts to find the trait this `impl` corresponds to. | ||
12 | pub fn resolve_target_trait( | ||
13 | sema: &Semantics<RootDatabase>, | ||
14 | impl_def: &ast::Impl, | ||
15 | ) -> Option<hir::Trait> { | ||
16 | let ast_path = | ||
17 | impl_def.trait_().map(|it| it.syntax().clone()).and_then(ast::PathType::cast)?.path()?; | ||
18 | |||
19 | match sema.resolve_path(&ast_path) { | ||
20 | Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def), | ||
21 | _ => None, | ||
22 | } | ||
23 | } | ||
24 | |||
25 | /// Given the `impl` block, returns the list of associated items (e.g. functions or types) that are | ||
26 | /// missing in this `impl` block. | ||
27 | pub fn get_missing_assoc_items( | ||
28 | sema: &Semantics<RootDatabase>, | ||
29 | impl_def: &ast::Impl, | ||
30 | ) -> Vec<hir::AssocItem> { | ||
31 | // Names must be unique between constants and functions. However, type aliases | ||
32 | // may share the same name as a function or constant. | ||
33 | let mut impl_fns_consts = FxHashSet::default(); | ||
34 | let mut impl_type = FxHashSet::default(); | ||
35 | |||
36 | if let Some(item_list) = impl_def.assoc_item_list() { | ||
37 | for item in item_list.assoc_items() { | ||
38 | match item { | ||
39 | ast::AssocItem::Fn(f) => { | ||
40 | if let Some(n) = f.name() { | ||
41 | impl_fns_consts.insert(n.syntax().to_string()); | ||
42 | } | ||
43 | } | ||
44 | |||
45 | ast::AssocItem::TypeAlias(t) => { | ||
46 | if let Some(n) = t.name() { | ||
47 | impl_type.insert(n.syntax().to_string()); | ||
48 | } | ||
49 | } | ||
50 | |||
51 | ast::AssocItem::Const(c) => { | ||
52 | if let Some(n) = c.name() { | ||
53 | impl_fns_consts.insert(n.syntax().to_string()); | ||
54 | } | ||
55 | } | ||
56 | ast::AssocItem::MacroCall(_) => (), | ||
57 | } | ||
58 | } | ||
59 | } | ||
60 | |||
61 | resolve_target_trait(sema, impl_def).map_or(vec![], |target_trait| { | ||
62 | target_trait | ||
63 | .items(sema.db) | ||
64 | .iter() | ||
65 | .filter(|i| match i { | ||
66 | hir::AssocItem::Function(f) => { | ||
67 | !impl_fns_consts.contains(&f.name(sema.db).to_string()) | ||
68 | } | ||
69 | hir::AssocItem::TypeAlias(t) => !impl_type.contains(&t.name(sema.db).to_string()), | ||
70 | hir::AssocItem::Const(c) => c | ||
71 | .name(sema.db) | ||
72 | .map(|n| !impl_fns_consts.contains(&n.to_string())) | ||
73 | .unwrap_or_default(), | ||
74 | }) | ||
75 | .cloned() | ||
76 | .collect() | ||
77 | }) | ||
78 | } | ||
79 | |||
80 | #[cfg(test)] | ||
81 | mod tests { | ||
82 | use crate::RootDatabase; | ||
83 | use base_db::{fixture::ChangeFixture, FilePosition}; | ||
84 | use expect_test::{expect, Expect}; | ||
85 | use hir::Semantics; | ||
86 | use syntax::ast::{self, AstNode}; | ||
87 | use test_utils::RangeOrOffset; | ||
88 | |||
89 | /// Creates analysis from a multi-file fixture, returns positions marked with <|>. | ||
90 | pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) { | ||
91 | let change_fixture = ChangeFixture::parse(ra_fixture); | ||
92 | let mut database = RootDatabase::default(); | ||
93 | database.apply_change(change_fixture.change); | ||
94 | let (file_id, range_or_offset) = | ||
95 | change_fixture.file_position.expect("expected a marker (<|>)"); | ||
96 | let offset = match range_or_offset { | ||
97 | RangeOrOffset::Range(_) => panic!(), | ||
98 | RangeOrOffset::Offset(it) => it, | ||
99 | }; | ||
100 | (database, FilePosition { file_id, offset }) | ||
101 | } | ||
102 | |||
103 | fn check_trait(ra_fixture: &str, expect: Expect) { | ||
104 | let (db, position) = position(ra_fixture); | ||
105 | let sema = Semantics::new(&db); | ||
106 | let file = sema.parse(position.file_id); | ||
107 | let impl_block: ast::Impl = | ||
108 | sema.find_node_at_offset_with_descend(file.syntax(), position.offset).unwrap(); | ||
109 | let trait_ = crate::traits::resolve_target_trait(&sema, &impl_block); | ||
110 | let actual = match trait_ { | ||
111 | Some(trait_) => trait_.name(&db).to_string(), | ||
112 | None => String::new(), | ||
113 | }; | ||
114 | expect.assert_eq(&actual); | ||
115 | } | ||
116 | |||
117 | fn check_missing_assoc(ra_fixture: &str, expect: Expect) { | ||
118 | let (db, position) = position(ra_fixture); | ||
119 | let sema = Semantics::new(&db); | ||
120 | let file = sema.parse(position.file_id); | ||
121 | let impl_block: ast::Impl = | ||
122 | sema.find_node_at_offset_with_descend(file.syntax(), position.offset).unwrap(); | ||
123 | let items = crate::traits::get_missing_assoc_items(&sema, &impl_block); | ||
124 | let actual = items | ||
125 | .into_iter() | ||
126 | .map(|item| item.name(&db).unwrap().to_string()) | ||
127 | .collect::<Vec<_>>() | ||
128 | .join("\n"); | ||
129 | expect.assert_eq(&actual); | ||
130 | } | ||
131 | |||
132 | #[test] | ||
133 | fn resolve_trait() { | ||
134 | check_trait( | ||
135 | r#" | ||
136 | pub trait Foo { | ||
137 | fn bar(); | ||
138 | } | ||
139 | impl Foo for u8 { | ||
140 | <|> | ||
141 | } | ||
142 | "#, | ||
143 | expect![["Foo"]], | ||
144 | ); | ||
145 | check_trait( | ||
146 | r#" | ||
147 | pub trait Foo { | ||
148 | fn bar(); | ||
149 | } | ||
150 | impl Foo for u8 { | ||
151 | fn bar() { | ||
152 | fn baz() { | ||
153 | <|> | ||
154 | } | ||
155 | baz(); | ||
156 | } | ||
157 | } | ||
158 | "#, | ||
159 | expect![["Foo"]], | ||
160 | ); | ||
161 | check_trait( | ||
162 | r#" | ||
163 | pub trait Foo { | ||
164 | fn bar(); | ||
165 | } | ||
166 | pub struct Bar; | ||
167 | impl Bar { | ||
168 | <|> | ||
169 | } | ||
170 | "#, | ||
171 | expect![[""]], | ||
172 | ); | ||
173 | } | ||
174 | |||
175 | #[test] | ||
176 | fn missing_assoc_items() { | ||
177 | check_missing_assoc( | ||
178 | r#" | ||
179 | pub trait Foo { | ||
180 | const FOO: u8; | ||
181 | fn bar(); | ||
182 | } | ||
183 | impl Foo for u8 { | ||
184 | <|> | ||
185 | }"#, | ||
186 | expect![[r#" | ||
187 | FOO | ||
188 | bar"#]], | ||
189 | ); | ||
190 | |||
191 | check_missing_assoc( | ||
192 | r#" | ||
193 | pub trait Foo { | ||
194 | const FOO: u8; | ||
195 | fn bar(); | ||
196 | } | ||
197 | impl Foo for u8 { | ||
198 | const FOO: u8 = 10; | ||
199 | <|> | ||
200 | }"#, | ||
201 | expect![[r#" | ||
202 | bar"#]], | ||
203 | ); | ||
204 | |||
205 | check_missing_assoc( | ||
206 | r#" | ||
207 | pub trait Foo { | ||
208 | const FOO: u8; | ||
209 | fn bar(); | ||
210 | } | ||
211 | impl Foo for u8 { | ||
212 | const FOO: u8 = 10; | ||
213 | fn bar() {<|>} | ||
214 | }"#, | ||
215 | expect![[r#""#]], | ||
216 | ); | ||
217 | |||
218 | check_missing_assoc( | ||
219 | r#" | ||
220 | pub struct Foo; | ||
221 | impl Foo { | ||
222 | fn bar() {<|>} | ||
223 | }"#, | ||
224 | expect![[r#""#]], | ||
225 | ); | ||
226 | } | ||
227 | } | ||
diff --git a/crates/ide_db/src/ty_filter.rs b/crates/ide_db/src/ty_filter.rs new file mode 100644 index 000000000..63a945282 --- /dev/null +++ b/crates/ide_db/src/ty_filter.rs | |||
@@ -0,0 +1,58 @@ | |||
1 | //! This module contains structures for filtering the expected types. | ||
2 | //! Use case for structures in this module is, for example, situation when you need to process | ||
3 | //! only certain `Enum`s. | ||
4 | |||
5 | use crate::RootDatabase; | ||
6 | use hir::{Adt, Semantics, Type}; | ||
7 | use std::iter; | ||
8 | use syntax::ast::{self, make}; | ||
9 | |||
10 | /// Enum types that implement `std::ops::Try` trait. | ||
11 | #[derive(Clone, Copy)] | ||
12 | pub enum TryEnum { | ||
13 | Result, | ||
14 | Option, | ||
15 | } | ||
16 | |||
17 | impl TryEnum { | ||
18 | const ALL: [TryEnum; 2] = [TryEnum::Option, TryEnum::Result]; | ||
19 | |||
20 | /// Returns `Some(..)` if the provided type is an enum that implements `std::ops::Try`. | ||
21 | pub fn from_ty(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<TryEnum> { | ||
22 | let enum_ = match ty.as_adt() { | ||
23 | Some(Adt::Enum(it)) => it, | ||
24 | _ => return None, | ||
25 | }; | ||
26 | TryEnum::ALL.iter().find_map(|&var| { | ||
27 | if &enum_.name(sema.db).to_string() == var.type_name() { | ||
28 | return Some(var); | ||
29 | } | ||
30 | None | ||
31 | }) | ||
32 | } | ||
33 | |||
34 | pub fn happy_case(self) -> &'static str { | ||
35 | match self { | ||
36 | TryEnum::Result => "Ok", | ||
37 | TryEnum::Option => "Some", | ||
38 | } | ||
39 | } | ||
40 | |||
41 | pub fn sad_pattern(self) -> ast::Pat { | ||
42 | match self { | ||
43 | TryEnum::Result => make::tuple_struct_pat( | ||
44 | make::path_unqualified(make::path_segment(make::name_ref("Err"))), | ||
45 | iter::once(make::wildcard_pat().into()), | ||
46 | ) | ||
47 | .into(), | ||
48 | TryEnum::Option => make::ident_pat(make::name("None")).into(), | ||
49 | } | ||
50 | } | ||
51 | |||
52 | fn type_name(self) -> &'static str { | ||
53 | match self { | ||
54 | TryEnum::Result => "Result", | ||
55 | TryEnum::Option => "Option", | ||
56 | } | ||
57 | } | ||
58 | } | ||
diff --git a/crates/parser/src/grammar.rs b/crates/parser/src/grammar.rs index 562e92252..4ab206a83 100644 --- a/crates/parser/src/grammar.rs +++ b/crates/parser/src/grammar.rs | |||
@@ -184,7 +184,11 @@ fn opt_visibility(p: &mut Parser) -> bool { | |||
184 | // pub(self) struct S; | 184 | // pub(self) struct S; |
185 | // pub(self) struct S; | 185 | // pub(self) struct S; |
186 | // pub(self) struct S; | 186 | // pub(self) struct S; |
187 | T![crate] | T![self] | T![super] => { | 187 | |
188 | // test pub_parens_typepath | ||
189 | // struct B(pub (super::A)); | ||
190 | // struct B(pub (crate::A,)); | ||
191 | T![crate] | T![self] | T![super] if p.nth(2) != T![:] => { | ||
188 | p.bump_any(); | 192 | p.bump_any(); |
189 | p.bump_any(); | 193 | p.bump_any(); |
190 | p.expect(T![')']); | 194 | p.expect(T![')']); |
diff --git a/crates/proc_macro_srv/Cargo.toml b/crates/proc_macro_srv/Cargo.toml index fb84e04ae..048b32186 100644 --- a/crates/proc_macro_srv/Cargo.toml +++ b/crates/proc_macro_srv/Cargo.toml | |||
@@ -20,7 +20,7 @@ proc_macro_api = { path = "../proc_macro_api", version = "0.0.0" } | |||
20 | test_utils = { path = "../test_utils", version = "0.0.0" } | 20 | test_utils = { path = "../test_utils", version = "0.0.0" } |
21 | 21 | ||
22 | [dev-dependencies] | 22 | [dev-dependencies] |
23 | cargo_metadata = "0.11.1" | 23 | cargo_metadata = "0.12.0" |
24 | difference = "2.0.0" | 24 | difference = "2.0.0" |
25 | 25 | ||
26 | # used as proc macro test targets | 26 | # used as proc macro test targets |
diff --git a/crates/project_model/Cargo.toml b/crates/project_model/Cargo.toml index 8bee398d9..2d53bcbcc 100644 --- a/crates/project_model/Cargo.toml +++ b/crates/project_model/Cargo.toml | |||
@@ -12,7 +12,7 @@ doctest = false | |||
12 | [dependencies] | 12 | [dependencies] |
13 | log = "0.4.8" | 13 | log = "0.4.8" |
14 | rustc-hash = "1.1.0" | 14 | rustc-hash = "1.1.0" |
15 | cargo_metadata = "0.11.1" | 15 | cargo_metadata = "0.12.0" |
16 | serde = { version = "1.0.106", features = ["derive"] } | 16 | serde = { version = "1.0.106", features = ["derive"] } |
17 | serde_json = "1.0.48" | 17 | serde_json = "1.0.48" |
18 | anyhow = "1.0.26" | 18 | anyhow = "1.0.26" |
diff --git a/crates/project_model/src/lib.rs b/crates/project_model/src/lib.rs index d1e7602fc..e92cfea59 100644 --- a/crates/project_model/src/lib.rs +++ b/crates/project_model/src/lib.rs | |||
@@ -13,7 +13,7 @@ use std::{ | |||
13 | }; | 13 | }; |
14 | 14 | ||
15 | use anyhow::{bail, Context, Result}; | 15 | use anyhow::{bail, Context, Result}; |
16 | use base_db::{CrateGraph, CrateId, CrateName, Edition, Env, FileId}; | 16 | use base_db::{CrateDisplayName, CrateGraph, CrateId, CrateName, Edition, Env, FileId}; |
17 | use cfg::CfgOptions; | 17 | use cfg::CfgOptions; |
18 | use paths::{AbsPath, AbsPathBuf}; | 18 | use paths::{AbsPath, AbsPathBuf}; |
19 | use rustc_hash::{FxHashMap, FxHashSet}; | 19 | use rustc_hash::{FxHashMap, FxHashSet}; |
@@ -335,8 +335,7 @@ impl ProjectWorkspace { | |||
335 | crate_graph.add_crate_root( | 335 | crate_graph.add_crate_root( |
336 | file_id, | 336 | file_id, |
337 | krate.edition, | 337 | krate.edition, |
338 | // FIXME json definitions can store the crate name | 338 | krate.display_name.clone(), |
339 | None, | ||
340 | cfg_options, | 339 | cfg_options, |
341 | env, | 340 | env, |
342 | proc_macro.unwrap_or_default(), | 341 | proc_macro.unwrap_or_default(), |
@@ -408,10 +407,12 @@ impl ProjectWorkspace { | |||
408 | .map(|it| proc_macro_client.by_dylib_path(&it)) | 407 | .map(|it| proc_macro_client.by_dylib_path(&it)) |
409 | .unwrap_or_default(); | 408 | .unwrap_or_default(); |
410 | 409 | ||
410 | let display_name = | ||
411 | CrateDisplayName::from_canonical_name(cargo[pkg].name.clone()); | ||
411 | let crate_id = crate_graph.add_crate_root( | 412 | let crate_id = crate_graph.add_crate_root( |
412 | file_id, | 413 | file_id, |
413 | edition, | 414 | edition, |
414 | Some(CrateName::normalize_dashes(&cargo[pkg].name)), | 415 | Some(display_name), |
415 | cfg_options, | 416 | cfg_options, |
416 | env, | 417 | env, |
417 | proc_macro.clone(), | 418 | proc_macro.clone(), |
@@ -485,6 +486,11 @@ impl ProjectWorkspace { | |||
485 | } | 486 | } |
486 | } | 487 | } |
487 | } | 488 | } |
489 | if crate_graph.patch_cfg_if() { | ||
490 | log::debug!("Patched std to depend on cfg-if") | ||
491 | } else { | ||
492 | log::debug!("Did not patch std to depend on cfg-if") | ||
493 | } | ||
488 | crate_graph | 494 | crate_graph |
489 | } | 495 | } |
490 | } | 496 | } |
@@ -551,7 +557,7 @@ fn sysroot_to_crate_graph( | |||
551 | let crate_id = crate_graph.add_crate_root( | 557 | let crate_id = crate_graph.add_crate_root( |
552 | file_id, | 558 | file_id, |
553 | Edition::Edition2018, | 559 | Edition::Edition2018, |
554 | Some(name), | 560 | Some(name.into()), |
555 | cfg_options.clone(), | 561 | cfg_options.clone(), |
556 | env, | 562 | env, |
557 | proc_macro, | 563 | proc_macro, |
diff --git a/crates/project_model/src/project_json.rs b/crates/project_model/src/project_json.rs index a6895ecdd..aab279223 100644 --- a/crates/project_model/src/project_json.rs +++ b/crates/project_model/src/project_json.rs | |||
@@ -2,7 +2,7 @@ | |||
2 | 2 | ||
3 | use std::path::PathBuf; | 3 | use std::path::PathBuf; |
4 | 4 | ||
5 | use base_db::{CrateId, CrateName, Dependency, Edition}; | 5 | use base_db::{CrateDisplayName, CrateId, CrateName, Dependency, Edition}; |
6 | use paths::{AbsPath, AbsPathBuf}; | 6 | use paths::{AbsPath, AbsPathBuf}; |
7 | use rustc_hash::FxHashMap; | 7 | use rustc_hash::FxHashMap; |
8 | use serde::{de, Deserialize}; | 8 | use serde::{de, Deserialize}; |
@@ -21,6 +21,7 @@ pub struct ProjectJson { | |||
21 | /// useful in creating the crate graph. | 21 | /// useful in creating the crate graph. |
22 | #[derive(Clone, Debug, Eq, PartialEq)] | 22 | #[derive(Clone, Debug, Eq, PartialEq)] |
23 | pub struct Crate { | 23 | pub struct Crate { |
24 | pub(crate) display_name: Option<CrateDisplayName>, | ||
24 | pub(crate) root_module: AbsPathBuf, | 25 | pub(crate) root_module: AbsPathBuf, |
25 | pub(crate) edition: Edition, | 26 | pub(crate) edition: Edition, |
26 | pub(crate) deps: Vec<Dependency>, | 27 | pub(crate) deps: Vec<Dependency>, |
@@ -68,6 +69,9 @@ impl ProjectJson { | |||
68 | }; | 69 | }; |
69 | 70 | ||
70 | Crate { | 71 | Crate { |
72 | display_name: crate_data | ||
73 | .display_name | ||
74 | .map(CrateDisplayName::from_canonical_name), | ||
71 | root_module, | 75 | root_module, |
72 | edition: crate_data.edition.into(), | 76 | edition: crate_data.edition.into(), |
73 | deps: crate_data | 77 | deps: crate_data |
@@ -114,6 +118,7 @@ pub struct ProjectJsonData { | |||
114 | 118 | ||
115 | #[derive(Deserialize)] | 119 | #[derive(Deserialize)] |
116 | struct CrateData { | 120 | struct CrateData { |
121 | display_name: Option<String>, | ||
117 | root_module: PathBuf, | 122 | root_module: PathBuf, |
118 | edition: EditionData, | 123 | edition: EditionData, |
119 | deps: Vec<DepData>, | 124 | deps: Vec<DepData>, |
diff --git a/crates/rust-analyzer/Cargo.toml b/crates/rust-analyzer/Cargo.toml index df2ea6f85..d25c4bf83 100644 --- a/crates/rust-analyzer/Cargo.toml +++ b/crates/rust-analyzer/Cargo.toml | |||
@@ -17,11 +17,11 @@ path = "src/bin/main.rs" | |||
17 | [dependencies] | 17 | [dependencies] |
18 | anyhow = "1.0.26" | 18 | anyhow = "1.0.26" |
19 | crossbeam-channel = "0.5.0" | 19 | crossbeam-channel = "0.5.0" |
20 | env_logger = { version = "0.7.1", default-features = false } | 20 | env_logger = { version = "0.8.1", default-features = false } |
21 | itertools = "0.9.0" | 21 | itertools = "0.9.0" |
22 | jod-thread = "0.1.0" | 22 | jod-thread = "0.1.0" |
23 | log = "0.4.8" | 23 | log = "0.4.8" |
24 | lsp-types = { version = "0.82.0", features = ["proposed"] } | 24 | lsp-types = { version = "0.83.0", features = ["proposed"] } |
25 | parking_lot = "0.11.0" | 25 | parking_lot = "0.11.0" |
26 | pico-args = "0.3.1" | 26 | pico-args = "0.3.1" |
27 | oorandom = "11.1.2" | 27 | oorandom = "11.1.2" |
@@ -29,9 +29,12 @@ rustc-hash = "1.1.0" | |||
29 | serde = { version = "1.0.106", features = ["derive"] } | 29 | serde = { version = "1.0.106", features = ["derive"] } |
30 | serde_json = "1.0.48" | 30 | serde_json = "1.0.48" |
31 | threadpool = "1.7.1" | 31 | threadpool = "1.7.1" |
32 | rayon = "1.3.1" | 32 | rayon = "1.5" |
33 | mimalloc = { version = "0.1.19", default-features = false, optional = true } | 33 | mimalloc = { version = "0.1.19", default-features = false, optional = true } |
34 | lsp-server = "0.4.0" | 34 | lsp-server = "0.4.0" |
35 | tracing = "0.1" | ||
36 | tracing-subscriber = { version = "0.2", default-features = false, features = ["env-filter", "registry"] } | ||
37 | tracing-tree = { version = "0.1.4" } | ||
35 | 38 | ||
36 | stdx = { path = "../stdx", version = "0.0.0" } | 39 | stdx = { path = "../stdx", version = "0.0.0" } |
37 | flycheck = { path = "../flycheck", version = "0.0.0" } | 40 | flycheck = { path = "../flycheck", version = "0.0.0" } |
@@ -46,7 +49,6 @@ cfg = { path = "../cfg", version = "0.0.0" } | |||
46 | toolchain = { path = "../toolchain", version = "0.0.0" } | 49 | toolchain = { path = "../toolchain", version = "0.0.0" } |
47 | 50 | ||
48 | # This should only be used in CLI | 51 | # This should only be used in CLI |
49 | base_db = { path = "../base_db", version = "0.0.0" } | ||
50 | ide_db = { path = "../ide_db", version = "0.0.0" } | 52 | ide_db = { path = "../ide_db", version = "0.0.0" } |
51 | ssr = { path = "../ssr", version = "0.0.0" } | 53 | ssr = { path = "../ssr", version = "0.0.0" } |
52 | hir = { path = "../hir", version = "0.0.0" } | 54 | hir = { path = "../hir", version = "0.0.0" } |
diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index 97b246a32..4175e569e 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs | |||
@@ -68,10 +68,32 @@ fn setup_logging(log_file: Option<PathBuf>) -> Result<()> { | |||
68 | let filter = env::var("RA_LOG").ok(); | 68 | let filter = env::var("RA_LOG").ok(); |
69 | logger::Logger::new(log_file, filter.as_deref()).install(); | 69 | logger::Logger::new(log_file, filter.as_deref()).install(); |
70 | 70 | ||
71 | tracing_setup::setup_tracing()?; | ||
72 | |||
71 | profile::init(); | 73 | profile::init(); |
72 | Ok(()) | 74 | Ok(()) |
73 | } | 75 | } |
74 | 76 | ||
77 | mod tracing_setup { | ||
78 | use tracing::subscriber; | ||
79 | use tracing_subscriber::layer::SubscriberExt; | ||
80 | use tracing_subscriber::EnvFilter; | ||
81 | use tracing_subscriber::Registry; | ||
82 | use tracing_tree::HierarchicalLayer; | ||
83 | |||
84 | pub fn setup_tracing() -> super::Result<()> { | ||
85 | let filter = EnvFilter::from_env("CHALK_DEBUG"); | ||
86 | let layer = HierarchicalLayer::default() | ||
87 | .with_indent_lines(true) | ||
88 | .with_ansi(false) | ||
89 | .with_indent_amount(2) | ||
90 | .with_writer(std::io::stderr); | ||
91 | let subscriber = Registry::default().with(filter).with(layer); | ||
92 | subscriber::set_global_default(subscriber)?; | ||
93 | Ok(()) | ||
94 | } | ||
95 | } | ||
96 | |||
75 | fn run_server() -> Result<()> { | 97 | fn run_server() -> Result<()> { |
76 | log::info!("server will start"); | 98 | log::info!("server will start"); |
77 | 99 | ||
diff --git a/crates/rust-analyzer/src/caps.rs b/crates/rust-analyzer/src/caps.rs index c589afeaf..ff1ae9575 100644 --- a/crates/rust-analyzer/src/caps.rs +++ b/crates/rust-analyzer/src/caps.rs | |||
@@ -48,7 +48,7 @@ pub fn server_capabilities(client_caps: &ClientCapabilities) -> ServerCapabiliti | |||
48 | references_provider: Some(OneOf::Left(true)), | 48 | references_provider: Some(OneOf::Left(true)), |
49 | document_highlight_provider: Some(OneOf::Left(true)), | 49 | document_highlight_provider: Some(OneOf::Left(true)), |
50 | document_symbol_provider: Some(OneOf::Left(true)), | 50 | document_symbol_provider: Some(OneOf::Left(true)), |
51 | workspace_symbol_provider: Some(true), | 51 | workspace_symbol_provider: Some(OneOf::Left(true)), |
52 | code_action_provider: Some(code_action_provider), | 52 | code_action_provider: Some(code_action_provider), |
53 | code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(true) }), | 53 | code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(true) }), |
54 | document_formatting_provider: Some(OneOf::Left(true)), | 54 | document_formatting_provider: Some(OneOf::Left(true)), |
@@ -113,6 +113,7 @@ fn code_action_capabilities(client_caps: &ClientCapabilities) -> CodeActionProvi | |||
113 | CodeActionKind::REFACTOR_INLINE, | 113 | CodeActionKind::REFACTOR_INLINE, |
114 | CodeActionKind::REFACTOR_REWRITE, | 114 | CodeActionKind::REFACTOR_REWRITE, |
115 | ]), | 115 | ]), |
116 | resolve_provider: None, | ||
116 | work_done_progress_options: Default::default(), | 117 | work_done_progress_options: Default::default(), |
117 | }) | 118 | }) |
118 | }) | 119 | }) |
diff --git a/crates/rust-analyzer/src/cargo_target_spec.rs b/crates/rust-analyzer/src/cargo_target_spec.rs index ddc028148..1ab72bd91 100644 --- a/crates/rust-analyzer/src/cargo_target_spec.rs +++ b/crates/rust-analyzer/src/cargo_target_spec.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | //! See `CargoTargetSpec` | 1 | //! See `CargoTargetSpec` |
2 | 2 | ||
3 | use cfg::CfgExpr; | 3 | use cfg::{CfgAtom, CfgExpr}; |
4 | use ide::{FileId, RunnableKind, TestId}; | 4 | use ide::{FileId, RunnableKind, TestId}; |
5 | use project_model::{self, TargetKind}; | 5 | use project_model::{self, TargetKind}; |
6 | use vfs::AbsPathBuf; | 6 | use vfs::AbsPathBuf; |
@@ -24,7 +24,7 @@ impl CargoTargetSpec { | |||
24 | snap: &GlobalStateSnapshot, | 24 | snap: &GlobalStateSnapshot, |
25 | spec: Option<CargoTargetSpec>, | 25 | spec: Option<CargoTargetSpec>, |
26 | kind: &RunnableKind, | 26 | kind: &RunnableKind, |
27 | cfgs: &[CfgExpr], | 27 | cfg: &Option<CfgExpr>, |
28 | ) -> Result<(Vec<String>, Vec<String>)> { | 28 | ) -> Result<(Vec<String>, Vec<String>)> { |
29 | let mut args = Vec::new(); | 29 | let mut args = Vec::new(); |
30 | let mut extra_args = Vec::new(); | 30 | let mut extra_args = Vec::new(); |
@@ -87,7 +87,7 @@ impl CargoTargetSpec { | |||
87 | args.push("--all-features".to_string()); | 87 | args.push("--all-features".to_string()); |
88 | } else { | 88 | } else { |
89 | let mut features = Vec::new(); | 89 | let mut features = Vec::new(); |
90 | for cfg in cfgs { | 90 | if let Some(cfg) = cfg.as_ref() { |
91 | required_features(cfg, &mut features); | 91 | required_features(cfg, &mut features); |
92 | } | 92 | } |
93 | for feature in &snap.config.cargo.features { | 93 | for feature in &snap.config.cargo.features { |
@@ -160,7 +160,9 @@ impl CargoTargetSpec { | |||
160 | /// Fill minimal features needed | 160 | /// Fill minimal features needed |
161 | fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) { | 161 | fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) { |
162 | match cfg_expr { | 162 | match cfg_expr { |
163 | CfgExpr::KeyValue { key, value } if key == "feature" => features.push(value.to_string()), | 163 | CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => { |
164 | features.push(value.to_string()) | ||
165 | } | ||
164 | CfgExpr::All(preds) => { | 166 | CfgExpr::All(preds) => { |
165 | preds.iter().for_each(|cfg| required_features(cfg, features)); | 167 | preds.iter().for_each(|cfg| required_features(cfg, features)); |
166 | } | 168 | } |
diff --git a/crates/rust-analyzer/src/cli/analysis_bench.rs b/crates/rust-analyzer/src/cli/analysis_bench.rs index d1c095ba5..8e33986d5 100644 --- a/crates/rust-analyzer/src/cli/analysis_bench.rs +++ b/crates/rust-analyzer/src/cli/analysis_bench.rs | |||
@@ -3,13 +3,13 @@ | |||
3 | use std::{env, path::PathBuf, str::FromStr, sync::Arc, time::Instant}; | 3 | use std::{env, path::PathBuf, str::FromStr, sync::Arc, time::Instant}; |
4 | 4 | ||
5 | use anyhow::{bail, format_err, Result}; | 5 | use anyhow::{bail, format_err, Result}; |
6 | use base_db::{ | ||
7 | salsa::{Database, Durability}, | ||
8 | FileId, | ||
9 | }; | ||
10 | use ide::{ | 6 | use ide::{ |
11 | Analysis, AnalysisHost, Change, CompletionConfig, DiagnosticsConfig, FilePosition, LineCol, | 7 | Analysis, AnalysisHost, Change, CompletionConfig, DiagnosticsConfig, FilePosition, LineCol, |
12 | }; | 8 | }; |
9 | use ide_db::base_db::{ | ||
10 | salsa::{Database, Durability}, | ||
11 | FileId, | ||
12 | }; | ||
13 | use vfs::AbsPathBuf; | 13 | use vfs::AbsPathBuf; |
14 | 14 | ||
15 | use crate::{ | 15 | use crate::{ |
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index fb2b2b000..98ef0cd68 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs | |||
@@ -6,16 +6,16 @@ use std::{ | |||
6 | time::{SystemTime, UNIX_EPOCH}, | 6 | time::{SystemTime, UNIX_EPOCH}, |
7 | }; | 7 | }; |
8 | 8 | ||
9 | use base_db::{ | ||
10 | salsa::{self, ParallelDatabase}, | ||
11 | SourceDatabaseExt, | ||
12 | }; | ||
13 | use hir::{ | 9 | use hir::{ |
14 | db::{AstDatabase, DefDatabase, HirDatabase}, | 10 | db::{AstDatabase, DefDatabase, HirDatabase}, |
15 | original_range, AssocItem, Crate, HasSource, HirDisplay, ModuleDef, | 11 | original_range, AssocItem, Crate, HasSource, HirDisplay, ModuleDef, |
16 | }; | 12 | }; |
17 | use hir_def::FunctionId; | 13 | use hir_def::FunctionId; |
18 | use hir_ty::{Ty, TypeWalk}; | 14 | use hir_ty::{Ty, TypeWalk}; |
15 | use ide_db::base_db::{ | ||
16 | salsa::{self, ParallelDatabase}, | ||
17 | SourceDatabaseExt, | ||
18 | }; | ||
19 | use itertools::Itertools; | 19 | use itertools::Itertools; |
20 | use oorandom::Rand32; | 20 | use oorandom::Rand32; |
21 | use rayon::prelude::*; | 21 | use rayon::prelude::*; |
diff --git a/crates/rust-analyzer/src/cli/diagnostics.rs b/crates/rust-analyzer/src/cli/diagnostics.rs index d1d3b12f8..368f627ac 100644 --- a/crates/rust-analyzer/src/cli/diagnostics.rs +++ b/crates/rust-analyzer/src/cli/diagnostics.rs | |||
@@ -6,9 +6,9 @@ use std::path::Path; | |||
6 | use anyhow::anyhow; | 6 | use anyhow::anyhow; |
7 | use rustc_hash::FxHashSet; | 7 | use rustc_hash::FxHashSet; |
8 | 8 | ||
9 | use base_db::SourceDatabaseExt; | ||
10 | use hir::Crate; | 9 | use hir::Crate; |
11 | use ide::{DiagnosticsConfig, Severity}; | 10 | use ide::{DiagnosticsConfig, Severity}; |
11 | use ide_db::base_db::SourceDatabaseExt; | ||
12 | 12 | ||
13 | use crate::cli::{load_cargo::load_cargo, Result}; | 13 | use crate::cli::{load_cargo::load_cargo, Result}; |
14 | 14 | ||
@@ -36,12 +36,8 @@ pub fn diagnostics(path: &Path, load_output_dirs: bool, with_proc_macro: bool) - | |||
36 | for module in work { | 36 | for module in work { |
37 | let file_id = module.definition_source(db).file_id.original_file(db); | 37 | let file_id = module.definition_source(db).file_id.original_file(db); |
38 | if !visited_files.contains(&file_id) { | 38 | if !visited_files.contains(&file_id) { |
39 | let crate_name = module | 39 | let crate_name = |
40 | .krate() | 40 | module.krate().display_name(db).as_deref().unwrap_or("unknown").to_string(); |
41 | .declaration_name(db) | ||
42 | .as_ref() | ||
43 | .map(ToString::to_string) | ||
44 | .unwrap_or_else(|| "unknown".to_string()); | ||
45 | println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id)); | 41 | println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id)); |
46 | for diagnostic in analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap() | 42 | for diagnostic in analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap() |
47 | { | 43 | { |
diff --git a/crates/rust-analyzer/src/cli/load_cargo.rs b/crates/rust-analyzer/src/cli/load_cargo.rs index 7ae1c9055..ab1e2ab92 100644 --- a/crates/rust-analyzer/src/cli/load_cargo.rs +++ b/crates/rust-analyzer/src/cli/load_cargo.rs | |||
@@ -3,9 +3,9 @@ | |||
3 | use std::{path::Path, sync::Arc}; | 3 | use std::{path::Path, sync::Arc}; |
4 | 4 | ||
5 | use anyhow::Result; | 5 | use anyhow::Result; |
6 | use base_db::CrateGraph; | ||
7 | use crossbeam_channel::{unbounded, Receiver}; | 6 | use crossbeam_channel::{unbounded, Receiver}; |
8 | use ide::{AnalysisHost, Change}; | 7 | use ide::{AnalysisHost, Change}; |
8 | use ide_db::base_db::CrateGraph; | ||
9 | use project_model::{CargoConfig, ProcMacroClient, ProjectManifest, ProjectWorkspace}; | 9 | use project_model::{CargoConfig, ProcMacroClient, ProjectManifest, ProjectWorkspace}; |
10 | use vfs::{loader::Handle, AbsPath, AbsPathBuf}; | 10 | use vfs::{loader::Handle, AbsPath, AbsPathBuf}; |
11 | 11 | ||
diff --git a/crates/rust-analyzer/src/cli/ssr.rs b/crates/rust-analyzer/src/cli/ssr.rs index c11e10943..a06631dac 100644 --- a/crates/rust-analyzer/src/cli/ssr.rs +++ b/crates/rust-analyzer/src/cli/ssr.rs | |||
@@ -4,7 +4,7 @@ use crate::cli::{load_cargo::load_cargo, Result}; | |||
4 | use ssr::{MatchFinder, SsrPattern, SsrRule}; | 4 | use ssr::{MatchFinder, SsrPattern, SsrRule}; |
5 | 5 | ||
6 | pub fn apply_ssr_rules(rules: Vec<SsrRule>) -> Result<()> { | 6 | pub fn apply_ssr_rules(rules: Vec<SsrRule>) -> Result<()> { |
7 | use base_db::SourceDatabaseExt; | 7 | use ide_db::base_db::SourceDatabaseExt; |
8 | let (host, vfs) = load_cargo(&std::env::current_dir()?, true, true)?; | 8 | let (host, vfs) = load_cargo(&std::env::current_dir()?, true, true)?; |
9 | let db = host.raw_database(); | 9 | let db = host.raw_database(); |
10 | let mut match_finder = MatchFinder::at_first_file(db)?; | 10 | let mut match_finder = MatchFinder::at_first_file(db)?; |
@@ -26,7 +26,7 @@ pub fn apply_ssr_rules(rules: Vec<SsrRule>) -> Result<()> { | |||
26 | /// `debug_snippet`. This is intended for debugging and probably isn't in it's current form useful | 26 | /// `debug_snippet`. This is intended for debugging and probably isn't in it's current form useful |
27 | /// for much else. | 27 | /// for much else. |
28 | pub fn search_for_patterns(patterns: Vec<SsrPattern>, debug_snippet: Option<String>) -> Result<()> { | 28 | pub fn search_for_patterns(patterns: Vec<SsrPattern>, debug_snippet: Option<String>) -> Result<()> { |
29 | use base_db::SourceDatabaseExt; | 29 | use ide_db::base_db::SourceDatabaseExt; |
30 | use ide_db::symbol_index::SymbolsDatabase; | 30 | use ide_db::symbol_index::SymbolsDatabase; |
31 | let (host, _vfs) = load_cargo(&std::env::current_dir()?, true, true)?; | 31 | let (host, _vfs) = load_cargo(&std::env::current_dir()?, true, true)?; |
32 | let db = host.raw_database(); | 32 | let db = host.raw_database(); |
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 1b9b24698..2ed6a0d82 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs | |||
@@ -47,6 +47,7 @@ pub struct Config { | |||
47 | pub call_info_full: bool, | 47 | pub call_info_full: bool, |
48 | pub lens: LensConfig, | 48 | pub lens: LensConfig, |
49 | pub hover: HoverConfig, | 49 | pub hover: HoverConfig, |
50 | pub semantic_tokens_refresh: bool, | ||
50 | 51 | ||
51 | pub with_sysroot: bool, | 52 | pub with_sysroot: bool, |
52 | pub linked_projects: Vec<LinkedProject>, | 53 | pub linked_projects: Vec<LinkedProject>, |
@@ -193,6 +194,7 @@ impl Config { | |||
193 | call_info_full: true, | 194 | call_info_full: true, |
194 | lens: LensConfig::default(), | 195 | lens: LensConfig::default(), |
195 | hover: HoverConfig::default(), | 196 | hover: HoverConfig::default(), |
197 | semantic_tokens_refresh: false, | ||
196 | linked_projects: Vec::new(), | 198 | linked_projects: Vec::new(), |
197 | root_path, | 199 | root_path, |
198 | } | 200 | } |
@@ -402,6 +404,14 @@ impl Config { | |||
402 | self.client_caps.hover_actions = get_bool("hoverActions"); | 404 | self.client_caps.hover_actions = get_bool("hoverActions"); |
403 | self.client_caps.status_notification = get_bool("statusNotification"); | 405 | self.client_caps.status_notification = get_bool("statusNotification"); |
404 | } | 406 | } |
407 | |||
408 | if let Some(workspace_caps) = caps.workspace.as_ref() { | ||
409 | if let Some(refresh_support) = | ||
410 | workspace_caps.semantic_tokens.as_ref().and_then(|it| it.refresh_support) | ||
411 | { | ||
412 | self.semantic_tokens_refresh = refresh_support; | ||
413 | } | ||
414 | } | ||
405 | } | 415 | } |
406 | } | 416 | } |
407 | 417 | ||
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt b/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt index d06517126..58d47d32a 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt | |||
@@ -20,6 +20,7 @@ | |||
20 | "trivially_copy_pass_by_ref", | 20 | "trivially_copy_pass_by_ref", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "clippy", | 25 | "clippy", |
25 | ), | 26 | ), |
@@ -61,6 +62,7 @@ | |||
61 | ], | 62 | ], |
62 | ), | 63 | ), |
63 | tags: None, | 64 | tags: None, |
65 | data: None, | ||
64 | }, | 66 | }, |
65 | fixes: [], | 67 | fixes: [], |
66 | }, | 68 | }, |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt b/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt index f5de2f07f..6aa26bf63 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt | |||
@@ -20,12 +20,14 @@ | |||
20 | "E0277", | 20 | "E0277", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
26 | message: "can\'t compare `{integer}` with `&str`\nthe trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`", | 27 | message: "can\'t compare `{integer}` with `&str`\nthe trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`", |
27 | related_information: None, | 28 | related_information: None, |
28 | tags: None, | 29 | tags: None, |
30 | data: None, | ||
29 | }, | 31 | }, |
30 | fixes: [], | 32 | fixes: [], |
31 | }, | 33 | }, |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt b/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt index 00e8da8a7..7aaffaba2 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt | |||
@@ -16,6 +16,7 @@ | |||
16 | Error, | 16 | Error, |
17 | ), | 17 | ), |
18 | code: None, | 18 | code: None, |
19 | code_description: None, | ||
19 | source: Some( | 20 | source: Some( |
20 | "rustc", | 21 | "rustc", |
21 | ), | 22 | ), |
@@ -41,6 +42,7 @@ | |||
41 | ], | 42 | ], |
42 | ), | 43 | ), |
43 | tags: None, | 44 | tags: None, |
45 | data: None, | ||
44 | }, | 46 | }, |
45 | fixes: [], | 47 | fixes: [], |
46 | }, | 48 | }, |
@@ -61,6 +63,7 @@ | |||
61 | Error, | 63 | Error, |
62 | ), | 64 | ), |
63 | code: None, | 65 | code: None, |
66 | code_description: None, | ||
64 | source: Some( | 67 | source: Some( |
65 | "rustc", | 68 | "rustc", |
66 | ), | 69 | ), |
@@ -86,6 +89,7 @@ | |||
86 | ], | 89 | ], |
87 | ), | 90 | ), |
88 | tags: None, | 91 | tags: None, |
92 | data: None, | ||
89 | }, | 93 | }, |
90 | fixes: [], | 94 | fixes: [], |
91 | }, | 95 | }, |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt index fc54440be..584213420 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt | |||
@@ -20,12 +20,14 @@ | |||
20 | "E0053", | 20 | "E0053", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
26 | message: "method `next` has an incompatible type for trait\nexpected type `fn(&mut ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&ty::Ref<M>>`\n found type `fn(&ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&\'list ty::Ref<M>>`", | 27 | message: "method `next` has an incompatible type for trait\nexpected type `fn(&mut ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&ty::Ref<M>>`\n found type `fn(&ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&\'list ty::Ref<M>>`", |
27 | related_information: None, | 28 | related_information: None, |
28 | tags: None, | 29 | tags: None, |
30 | data: None, | ||
29 | }, | 31 | }, |
30 | fixes: [], | 32 | fixes: [], |
31 | }, | 33 | }, |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt index c269af218..2610e4e20 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt | |||
@@ -20,12 +20,14 @@ | |||
20 | "E0308", | 20 | "E0308", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
26 | message: "mismatched types\nexpected usize, found u32", | 27 | message: "mismatched types\nexpected usize, found u32", |
27 | related_information: None, | 28 | related_information: None, |
28 | tags: None, | 29 | tags: None, |
30 | data: None, | ||
29 | }, | 31 | }, |
30 | fixes: [], | 32 | fixes: [], |
31 | }, | 33 | }, |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt index 74d91bc77..8dc53391e 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt | |||
@@ -20,6 +20,7 @@ | |||
20 | "unused_variables", | 20 | "unused_variables", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
@@ -30,6 +31,7 @@ | |||
30 | Unnecessary, | 31 | Unnecessary, |
31 | ], | 32 | ], |
32 | ), | 33 | ), |
34 | data: None, | ||
33 | }, | 35 | }, |
34 | fixes: [ | 36 | fixes: [ |
35 | CodeAction { | 37 | CodeAction { |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt index 8a420c949..c8703194c 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt | |||
@@ -20,6 +20,7 @@ | |||
20 | "unused_variables", | 20 | "unused_variables", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
@@ -30,6 +31,7 @@ | |||
30 | Unnecessary, | 31 | Unnecessary, |
31 | ], | 32 | ], |
32 | ), | 33 | ), |
34 | data: None, | ||
33 | }, | 35 | }, |
34 | fixes: [ | 36 | fixes: [ |
35 | CodeAction { | 37 | CodeAction { |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt index 79910660b..dc93227ad 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt | |||
@@ -20,6 +20,7 @@ | |||
20 | "unused_variables", | 20 | "unused_variables", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
@@ -30,6 +31,7 @@ | |||
30 | Unnecessary, | 31 | Unnecessary, |
31 | ], | 32 | ], |
32 | ), | 33 | ), |
34 | data: None, | ||
33 | }, | 35 | }, |
34 | fixes: [ | 36 | fixes: [ |
35 | CodeAction { | 37 | CodeAction { |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt index efe37261d..ba1b98b33 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt | |||
@@ -20,6 +20,7 @@ | |||
20 | "E0061", | 20 | "E0061", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "rustc", | 25 | "rustc", |
25 | ), | 26 | ), |
@@ -45,6 +46,7 @@ | |||
45 | ], | 46 | ], |
46 | ), | 47 | ), |
47 | tags: None, | 48 | tags: None, |
49 | data: None, | ||
48 | }, | 50 | }, |
49 | fixes: [], | 51 | fixes: [], |
50 | }, | 52 | }, |
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt b/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt index 4f811ab64..81f752672 100644 --- a/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt +++ b/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt | |||
@@ -20,6 +20,7 @@ | |||
20 | "let_and_return", | 20 | "let_and_return", |
21 | ), | 21 | ), |
22 | ), | 22 | ), |
23 | code_description: None, | ||
23 | source: Some( | 24 | source: Some( |
24 | "clippy", | 25 | "clippy", |
25 | ), | 26 | ), |
@@ -45,6 +46,7 @@ | |||
45 | ], | 46 | ], |
46 | ), | 47 | ), |
47 | tags: None, | 48 | tags: None, |
49 | data: None, | ||
48 | }, | 50 | }, |
49 | fixes: [ | 51 | fixes: [ |
50 | CodeAction { | 52 | CodeAction { |
diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs index 33606edda..b949577c1 100644 --- a/crates/rust-analyzer/src/diagnostics/to_proto.rs +++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs | |||
@@ -248,10 +248,12 @@ pub(crate) fn map_rust_diagnostic_to_lsp( | |||
248 | range: in_macro_location.range, | 248 | range: in_macro_location.range, |
249 | severity, | 249 | severity, |
250 | code: code.clone().map(lsp_types::NumberOrString::String), | 250 | code: code.clone().map(lsp_types::NumberOrString::String), |
251 | code_description: None, | ||
251 | source: Some(source.clone()), | 252 | source: Some(source.clone()), |
252 | message: message.clone(), | 253 | message: message.clone(), |
253 | related_information: Some(information_for_additional_diagnostic), | 254 | related_information: Some(information_for_additional_diagnostic), |
254 | tags: if tags.is_empty() { None } else { Some(tags.clone()) }, | 255 | tags: if tags.is_empty() { None } else { Some(tags.clone()) }, |
256 | data: None, | ||
255 | }; | 257 | }; |
256 | 258 | ||
257 | Some(MappedRustDiagnostic { | 259 | Some(MappedRustDiagnostic { |
@@ -267,6 +269,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp( | |||
267 | range: location.range, | 269 | range: location.range, |
268 | severity, | 270 | severity, |
269 | code: code.clone().map(lsp_types::NumberOrString::String), | 271 | code: code.clone().map(lsp_types::NumberOrString::String), |
272 | code_description: None, | ||
270 | source: Some(source.clone()), | 273 | source: Some(source.clone()), |
271 | message, | 274 | message, |
272 | related_information: if related_information.is_empty() { | 275 | related_information: if related_information.is_empty() { |
@@ -275,6 +278,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp( | |||
275 | Some(related_information.clone()) | 278 | Some(related_information.clone()) |
276 | }, | 279 | }, |
277 | tags: if tags.is_empty() { None } else { Some(tags.clone()) }, | 280 | tags: if tags.is_empty() { None } else { Some(tags.clone()) }, |
281 | data: None, | ||
278 | }; | 282 | }; |
279 | 283 | ||
280 | let main_diagnostic = | 284 | let main_diagnostic = |
diff --git a/crates/rust-analyzer/src/dispatch.rs b/crates/rust-analyzer/src/dispatch.rs index 9c8815e29..7a87515e9 100644 --- a/crates/rust-analyzer/src/dispatch.rs +++ b/crates/rust-analyzer/src/dispatch.rs | |||
@@ -34,7 +34,7 @@ impl<'a> RequestDispatcher<'a> { | |||
34 | }; | 34 | }; |
35 | let world = panic::AssertUnwindSafe(&mut *self.global_state); | 35 | let world = panic::AssertUnwindSafe(&mut *self.global_state); |
36 | let response = panic::catch_unwind(move || { | 36 | let response = panic::catch_unwind(move || { |
37 | stdx::panic_context::enter(format!("request: {} {:#?}", R::METHOD, params)); | 37 | let _pctx = stdx::panic_context::enter(format!("request: {} {:#?}", R::METHOD, params)); |
38 | let result = f(world.0, params); | 38 | let result = f(world.0, params); |
39 | result_to_response::<R>(id, result) | 39 | result_to_response::<R>(id, result) |
40 | }) | 40 | }) |
@@ -64,7 +64,7 @@ impl<'a> RequestDispatcher<'a> { | |||
64 | let world = self.global_state.snapshot(); | 64 | let world = self.global_state.snapshot(); |
65 | 65 | ||
66 | move || { | 66 | move || { |
67 | let _ctx = | 67 | let _pctx = |
68 | stdx::panic_context::enter(format!("request: {} {:#?}", R::METHOD, params)); | 68 | stdx::panic_context::enter(format!("request: {} {:#?}", R::METHOD, params)); |
69 | let result = f(world, params); | 69 | let result = f(world, params); |
70 | Task::Response(result_to_response::<R>(id, result)) | 70 | Task::Response(result_to_response::<R>(id, result)) |
@@ -160,7 +160,7 @@ impl<'a> NotificationDispatcher<'a> { | |||
160 | return Ok(self); | 160 | return Ok(self); |
161 | } | 161 | } |
162 | }; | 162 | }; |
163 | stdx::panic_context::enter(format!("notification: {}", N::METHOD)); | 163 | let _pctx = stdx::panic_context::enter(format!("notification: {}", N::METHOD)); |
164 | f(self.global_state, params)?; | 164 | f(self.global_state, params)?; |
165 | Ok(self) | 165 | Ok(self) |
166 | } | 166 | } |
diff --git a/crates/rust-analyzer/src/from_proto.rs b/crates/rust-analyzer/src/from_proto.rs index 5b9f52993..aa6b808d6 100644 --- a/crates/rust-analyzer/src/from_proto.rs +++ b/crates/rust-analyzer/src/from_proto.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! Conversion lsp_types types to rust-analyzer specific ones. | 1 | //! Conversion lsp_types types to rust-analyzer specific ones. |
2 | use std::convert::TryFrom; | 2 | use std::convert::TryFrom; |
3 | 3 | ||
4 | use base_db::{FileId, FilePosition, FileRange}; | ||
5 | use ide::{AssistKind, LineCol, LineIndex}; | 4 | use ide::{AssistKind, LineCol, LineIndex}; |
5 | use ide_db::base_db::{FileId, FilePosition, FileRange}; | ||
6 | use syntax::{TextRange, TextSize}; | 6 | use syntax::{TextRange, TextSize}; |
7 | use vfs::AbsPathBuf; | 7 | use vfs::AbsPathBuf; |
8 | 8 | ||
diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs index dafab6a6a..673a2eebc 100644 --- a/crates/rust-analyzer/src/global_state.rs +++ b/crates/rust-analyzer/src/global_state.rs | |||
@@ -5,10 +5,10 @@ | |||
5 | 5 | ||
6 | use std::{sync::Arc, time::Instant}; | 6 | use std::{sync::Arc, time::Instant}; |
7 | 7 | ||
8 | use base_db::{CrateId, VfsPath}; | ||
9 | use crossbeam_channel::{unbounded, Receiver, Sender}; | 8 | use crossbeam_channel::{unbounded, Receiver, Sender}; |
10 | use flycheck::FlycheckHandle; | 9 | use flycheck::FlycheckHandle; |
11 | use ide::{Analysis, AnalysisHost, Change, FileId}; | 10 | use ide::{Analysis, AnalysisHost, Change, FileId}; |
11 | use ide_db::base_db::{CrateId, VfsPath}; | ||
12 | use lsp_types::{SemanticTokens, Url}; | 12 | use lsp_types::{SemanticTokens, Url}; |
13 | use parking_lot::{Mutex, RwLock}; | 13 | use parking_lot::{Mutex, RwLock}; |
14 | use project_model::{CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target}; | 14 | use project_model::{CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target}; |
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index 215be850f..049c583a4 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs | |||
@@ -16,12 +16,12 @@ use lsp_server::ErrorCode; | |||
16 | use lsp_types::{ | 16 | use lsp_types::{ |
17 | CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem, | 17 | CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem, |
18 | CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, | 18 | CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, |
19 | CodeActionKind, CodeLens, Command, CompletionItem, Diagnostic, DocumentFormattingParams, | 19 | CodeActionKind, CodeLens, Command, CompletionItem, Diagnostic, DiagnosticTag, |
20 | DocumentHighlight, DocumentSymbol, FoldingRange, FoldingRangeParams, HoverContents, Location, | 20 | DocumentFormattingParams, DocumentHighlight, DocumentSymbol, FoldingRange, FoldingRangeParams, |
21 | Position, PrepareRenameResponse, Range, RenameParams, SemanticTokensDeltaParams, | 21 | HoverContents, Location, Position, PrepareRenameResponse, Range, RenameParams, |
22 | SemanticTokensFullDeltaResult, SemanticTokensParams, SemanticTokensRangeParams, | 22 | SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams, |
23 | SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation, SymbolTag, | 23 | SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation, |
24 | TextDocumentIdentifier, Url, WorkspaceEdit, | 24 | SymbolTag, TextDocumentIdentifier, Url, WorkspaceEdit, |
25 | }; | 25 | }; |
26 | use project_model::TargetKind; | 26 | use project_model::TargetKind; |
27 | use serde::{Deserialize, Serialize}; | 27 | use serde::{Deserialize, Serialize}; |
@@ -570,7 +570,7 @@ pub(crate) fn handle_completion( | |||
570 | let line_endings = snap.file_line_endings(position.file_id); | 570 | let line_endings = snap.file_line_endings(position.file_id); |
571 | let items: Vec<CompletionItem> = items | 571 | let items: Vec<CompletionItem> = items |
572 | .into_iter() | 572 | .into_iter() |
573 | .map(|item| to_proto::completion_item(&line_index, line_endings, item)) | 573 | .flat_map(|item| to_proto::completion_item(&line_index, line_endings, item)) |
574 | .collect(); | 574 | .collect(); |
575 | 575 | ||
576 | Ok(Some(items.into())) | 576 | Ok(Some(items.into())) |
@@ -1121,10 +1121,12 @@ pub(crate) fn publish_diagnostics( | |||
1121 | range: to_proto::range(&line_index, d.range), | 1121 | range: to_proto::range(&line_index, d.range), |
1122 | severity: Some(to_proto::diagnostic_severity(d.severity)), | 1122 | severity: Some(to_proto::diagnostic_severity(d.severity)), |
1123 | code: None, | 1123 | code: None, |
1124 | code_description: None, | ||
1124 | source: Some("rust-analyzer".to_string()), | 1125 | source: Some("rust-analyzer".to_string()), |
1125 | message: d.message, | 1126 | message: d.message, |
1126 | related_information: None, | 1127 | related_information: None, |
1127 | tags: None, | 1128 | tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None }, |
1129 | data: None, | ||
1128 | }) | 1130 | }) |
1129 | .collect(); | 1131 | .collect(); |
1130 | Ok(diagnostics) | 1132 | Ok(diagnostics) |
diff --git a/crates/rust-analyzer/src/lsp_utils.rs b/crates/rust-analyzer/src/lsp_utils.rs index bd888f634..1d271a9d8 100644 --- a/crates/rust-analyzer/src/lsp_utils.rs +++ b/crates/rust-analyzer/src/lsp_utils.rs | |||
@@ -1,8 +1,8 @@ | |||
1 | //! Utilities for LSP-related boilerplate code. | 1 | //! Utilities for LSP-related boilerplate code. |
2 | use std::{error::Error, ops::Range}; | 2 | use std::{error::Error, ops::Range}; |
3 | 3 | ||
4 | use base_db::Canceled; | ||
5 | use ide::LineIndex; | 4 | use ide::LineIndex; |
5 | use ide_db::base_db::Canceled; | ||
6 | use lsp_server::Notification; | 6 | use lsp_server::Notification; |
7 | 7 | ||
8 | use crate::{from_proto, global_state::GlobalState}; | 8 | use crate::{from_proto, global_state::GlobalState}; |
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index fb18f9014..ff855fe1a 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs | |||
@@ -5,10 +5,10 @@ use std::{ | |||
5 | time::{Duration, Instant}, | 5 | time::{Duration, Instant}, |
6 | }; | 6 | }; |
7 | 7 | ||
8 | use base_db::VfsPath; | ||
9 | use crossbeam_channel::{select, Receiver}; | 8 | use crossbeam_channel::{select, Receiver}; |
10 | use ide::PrimeCachesProgress; | 9 | use ide::PrimeCachesProgress; |
11 | use ide::{Canceled, FileId}; | 10 | use ide::{Canceled, FileId}; |
11 | use ide_db::base_db::VfsPath; | ||
12 | use lsp_server::{Connection, Notification, Request, Response}; | 12 | use lsp_server::{Connection, Notification, Request, Response}; |
13 | use lsp_types::notification::Notification as _; | 13 | use lsp_types::notification::Notification as _; |
14 | use project_model::ProjectWorkspace; | 14 | use project_model::ProjectWorkspace; |
@@ -330,6 +330,12 @@ impl GlobalState { | |||
330 | .collect::<Vec<_>>(); | 330 | .collect::<Vec<_>>(); |
331 | 331 | ||
332 | self.update_file_notifications_on_threadpool(subscriptions); | 332 | self.update_file_notifications_on_threadpool(subscriptions); |
333 | |||
334 | // Refresh semantic tokens if the client supports it. | ||
335 | if self.config.semantic_tokens_refresh { | ||
336 | self.semantic_tokens_cache.lock().clear(); | ||
337 | self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ()); | ||
338 | } | ||
333 | } | 339 | } |
334 | 340 | ||
335 | if let Some(diagnostic_changes) = self.diagnostics.take_changes() { | 341 | if let Some(diagnostic_changes) = self.diagnostics.take_changes() { |
diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index f7215f129..0eabd51bd 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs | |||
@@ -1,9 +1,9 @@ | |||
1 | //! Project loading & configuration updates | 1 | //! Project loading & configuration updates |
2 | use std::{mem, sync::Arc}; | 2 | use std::{mem, sync::Arc}; |
3 | 3 | ||
4 | use base_db::{CrateGraph, SourceRoot, VfsPath}; | ||
5 | use flycheck::{FlycheckConfig, FlycheckHandle}; | 4 | use flycheck::{FlycheckConfig, FlycheckHandle}; |
6 | use ide::Change; | 5 | use ide::Change; |
6 | use ide_db::base_db::{CrateGraph, SourceRoot, VfsPath}; | ||
7 | use project_model::{ProcMacroClient, ProjectWorkspace}; | 7 | use project_model::{ProcMacroClient, ProjectWorkspace}; |
8 | use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind}; | 8 | use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind}; |
9 | 9 | ||
diff --git a/crates/rust-analyzer/src/semantic_tokens.rs b/crates/rust-analyzer/src/semantic_tokens.rs index a6c4d6099..7df28c9dd 100644 --- a/crates/rust-analyzer/src/semantic_tokens.rs +++ b/crates/rust-analyzer/src/semantic_tokens.rs | |||
@@ -77,6 +77,7 @@ define_semantic_token_modifiers![ | |||
77 | (CONSUMING, "consuming"), | 77 | (CONSUMING, "consuming"), |
78 | (UNSAFE, "unsafe"), | 78 | (UNSAFE, "unsafe"), |
79 | (ATTRIBUTE_MODIFIER, "attribute"), | 79 | (ATTRIBUTE_MODIFIER, "attribute"), |
80 | (CALLABLE, "callable"), | ||
80 | ]; | 81 | ]; |
81 | 82 | ||
82 | #[derive(Default)] | 83 | #[derive(Default)] |
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs index aeacde0f7..92b7c7b68 100644 --- a/crates/rust-analyzer/src/to_proto.rs +++ b/crates/rust-analyzer/src/to_proto.rs | |||
@@ -4,13 +4,13 @@ use std::{ | |||
4 | sync::atomic::{AtomicU32, Ordering}, | 4 | sync::atomic::{AtomicU32, Ordering}, |
5 | }; | 5 | }; |
6 | 6 | ||
7 | use base_db::{FileId, FileRange}; | ||
8 | use ide::{ | 7 | use ide::{ |
9 | Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind, Documentation, | 8 | Assist, AssistKind, CallInfo, CompletionItem, CompletionItemKind, Documentation, |
10 | FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag, HighlightedRange, | 9 | FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag, HighlightedRange, |
11 | Indel, InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup, NavigationTarget, | 10 | Indel, InlayHint, InlayKind, InsertTextFormat, LineIndex, Markup, NavigationTarget, |
12 | ReferenceAccess, ResolvedAssist, Runnable, Severity, SourceChange, SourceFileEdit, TextEdit, | 11 | ReferenceAccess, ResolvedAssist, Runnable, Severity, SourceChange, SourceFileEdit, TextEdit, |
13 | }; | 12 | }; |
13 | use ide_db::base_db::{FileId, FileRange}; | ||
14 | use itertools::Itertools; | 14 | use itertools::Itertools; |
15 | use syntax::{SyntaxKind, TextRange, TextSize}; | 15 | use syntax::{SyntaxKind, TextRange, TextSize}; |
16 | 16 | ||
@@ -160,7 +160,13 @@ pub(crate) fn completion_item( | |||
160 | line_index: &LineIndex, | 160 | line_index: &LineIndex, |
161 | line_endings: LineEndings, | 161 | line_endings: LineEndings, |
162 | completion_item: CompletionItem, | 162 | completion_item: CompletionItem, |
163 | ) -> lsp_types::CompletionItem { | 163 | ) -> Vec<lsp_types::CompletionItem> { |
164 | fn set_score(res: &mut lsp_types::CompletionItem, label: &str) { | ||
165 | res.preselect = Some(true); | ||
166 | // HACK: sort preselect items first | ||
167 | res.sort_text = Some(format!(" {}", label)); | ||
168 | } | ||
169 | |||
164 | let mut additional_text_edits = Vec::new(); | 170 | let mut additional_text_edits = Vec::new(); |
165 | let mut text_edit = None; | 171 | let mut text_edit = None; |
166 | // LSP does not allow arbitrary edits in completion, so we have to do a | 172 | // LSP does not allow arbitrary edits in completion, so we have to do a |
@@ -200,9 +206,7 @@ pub(crate) fn completion_item( | |||
200 | }; | 206 | }; |
201 | 207 | ||
202 | if completion_item.score().is_some() { | 208 | if completion_item.score().is_some() { |
203 | res.preselect = Some(true); | 209 | set_score(&mut res, completion_item.label()); |
204 | // HACK: sort preselect items first | ||
205 | res.sort_text = Some(format!(" {}", completion_item.label())); | ||
206 | } | 210 | } |
207 | 211 | ||
208 | if completion_item.deprecated() { | 212 | if completion_item.deprecated() { |
@@ -217,9 +221,22 @@ pub(crate) fn completion_item( | |||
217 | }); | 221 | }); |
218 | } | 222 | } |
219 | 223 | ||
220 | res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format())); | 224 | let mut all_results = match completion_item.ref_match() { |
225 | Some(ref_match) => { | ||
226 | let mut refed = res.clone(); | ||
227 | let (mutability, _score) = ref_match; | ||
228 | let label = format!("&{}{}", mutability.as_keyword_for_ref(), refed.label); | ||
229 | set_score(&mut refed, &label); | ||
230 | refed.label = label; | ||
231 | vec![res, refed] | ||
232 | } | ||
233 | None => vec![res], | ||
234 | }; | ||
221 | 235 | ||
222 | res | 236 | for mut r in all_results.iter_mut() { |
237 | r.insert_text_format = Some(insert_text_format(completion_item.insert_text_format())); | ||
238 | } | ||
239 | all_results | ||
223 | } | 240 | } |
224 | 241 | ||
225 | pub(crate) fn signature_help( | 242 | pub(crate) fn signature_help( |
@@ -408,6 +425,7 @@ fn semantic_token_type_and_modifiers( | |||
408 | HighlightModifier::Mutable => semantic_tokens::MUTABLE, | 425 | HighlightModifier::Mutable => semantic_tokens::MUTABLE, |
409 | HighlightModifier::Consuming => semantic_tokens::CONSUMING, | 426 | HighlightModifier::Consuming => semantic_tokens::CONSUMING, |
410 | HighlightModifier::Unsafe => semantic_tokens::UNSAFE, | 427 | HighlightModifier::Unsafe => semantic_tokens::UNSAFE, |
428 | HighlightModifier::Callable => semantic_tokens::CALLABLE, | ||
411 | }; | 429 | }; |
412 | mods |= modifier; | 430 | mods |= modifier; |
413 | } | 431 | } |
@@ -691,7 +709,16 @@ pub(crate) fn call_hierarchy_item( | |||
691 | let detail = target.description.clone(); | 709 | let detail = target.description.clone(); |
692 | let kind = symbol_kind(target.kind); | 710 | let kind = symbol_kind(target.kind); |
693 | let (uri, range, selection_range) = location_info(snap, target)?; | 711 | let (uri, range, selection_range) = location_info(snap, target)?; |
694 | Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range }) | 712 | Ok(lsp_types::CallHierarchyItem { |
713 | name, | ||
714 | kind, | ||
715 | tags: None, | ||
716 | detail, | ||
717 | uri, | ||
718 | range, | ||
719 | selection_range, | ||
720 | data: None, | ||
721 | }) | ||
695 | } | 722 | } |
696 | 723 | ||
697 | pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind { | 724 | pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind { |
@@ -745,7 +772,7 @@ pub(crate) fn runnable( | |||
745 | let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone()); | 772 | let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone()); |
746 | let target = spec.as_ref().map(|s| s.target.clone()); | 773 | let target = spec.as_ref().map(|s| s.target.clone()); |
747 | let (cargo_args, executable_args) = | 774 | let (cargo_args, executable_args) = |
748 | CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg_exprs)?; | 775 | CargoTargetSpec::runnable_args(snap, spec, &runnable.kind, &runnable.cfg)?; |
749 | let label = runnable.label(target); | 776 | let label = runnable.label(target); |
750 | let location = location_link(snap, None, runnable.nav)?; | 777 | let location = location_link(snap, None, runnable.nav)?; |
751 | 778 | ||
@@ -776,6 +803,48 @@ mod tests { | |||
776 | use super::*; | 803 | use super::*; |
777 | 804 | ||
778 | #[test] | 805 | #[test] |
806 | fn test_completion_with_ref() { | ||
807 | let fixture = r#" | ||
808 | struct Foo; | ||
809 | fn foo(arg: &Foo) {} | ||
810 | fn main() { | ||
811 | let arg = Foo; | ||
812 | foo(<|>) | ||
813 | }"#; | ||
814 | |||
815 | let (offset, text) = test_utils::extract_offset(fixture); | ||
816 | let line_index = LineIndex::new(&text); | ||
817 | let (analysis, file_id) = Analysis::from_single_file(text); | ||
818 | let completions: Vec<(String, Option<String>)> = analysis | ||
819 | .completions( | ||
820 | &ide::CompletionConfig::default(), | ||
821 | ide_db::base_db::FilePosition { file_id, offset }, | ||
822 | ) | ||
823 | .unwrap() | ||
824 | .unwrap() | ||
825 | .into_iter() | ||
826 | .filter(|c| c.label().ends_with("arg")) | ||
827 | .map(|c| completion_item(&line_index, LineEndings::Unix, c)) | ||
828 | .flat_map(|comps| comps.into_iter().map(|c| (c.label, c.sort_text))) | ||
829 | .collect(); | ||
830 | expect_test::expect![[r#" | ||
831 | [ | ||
832 | ( | ||
833 | "arg", | ||
834 | None, | ||
835 | ), | ||
836 | ( | ||
837 | "&arg", | ||
838 | Some( | ||
839 | " &arg", | ||
840 | ), | ||
841 | ), | ||
842 | ] | ||
843 | "#]] | ||
844 | .assert_debug_eq(&completions); | ||
845 | } | ||
846 | |||
847 | #[test] | ||
779 | fn conv_fold_line_folding_only_fixup() { | 848 | fn conv_fold_line_folding_only_fixup() { |
780 | let text = r#"mod a; | 849 | let text = r#"mod a; |
781 | mod b; | 850 | mod b; |
diff --git a/crates/ssr/Cargo.toml b/crates/ssr/Cargo.toml index 408140014..98ed25fb6 100644 --- a/crates/ssr/Cargo.toml +++ b/crates/ssr/Cargo.toml | |||
@@ -16,7 +16,6 @@ itertools = "0.9.0" | |||
16 | 16 | ||
17 | text_edit = { path = "../text_edit", version = "0.0.0" } | 17 | text_edit = { path = "../text_edit", version = "0.0.0" } |
18 | syntax = { path = "../syntax", version = "0.0.0" } | 18 | syntax = { path = "../syntax", version = "0.0.0" } |
19 | base_db = { path = "../base_db", version = "0.0.0" } | ||
20 | ide_db = { path = "../ide_db", version = "0.0.0" } | 19 | ide_db = { path = "../ide_db", version = "0.0.0" } |
21 | hir = { path = "../hir", version = "0.0.0" } | 20 | hir = { path = "../hir", version = "0.0.0" } |
22 | test_utils = { path = "../test_utils", version = "0.0.0" } | 21 | test_utils = { path = "../test_utils", version = "0.0.0" } |
diff --git a/crates/ssr/src/lib.rs b/crates/ssr/src/lib.rs index ba669fd56..747ce495d 100644 --- a/crates/ssr/src/lib.rs +++ b/crates/ssr/src/lib.rs | |||
@@ -73,8 +73,8 @@ use crate::errors::bail; | |||
73 | pub use crate::errors::SsrError; | 73 | pub use crate::errors::SsrError; |
74 | pub use crate::matching::Match; | 74 | pub use crate::matching::Match; |
75 | use crate::matching::MatchFailureReason; | 75 | use crate::matching::MatchFailureReason; |
76 | use base_db::{FileId, FilePosition, FileRange}; | ||
77 | use hir::Semantics; | 76 | use hir::Semantics; |
77 | use ide_db::base_db::{FileId, FilePosition, FileRange}; | ||
78 | use ide_db::source_change::SourceFileEdit; | 78 | use ide_db::source_change::SourceFileEdit; |
79 | use resolving::ResolvedRule; | 79 | use resolving::ResolvedRule; |
80 | use rustc_hash::FxHashMap; | 80 | use rustc_hash::FxHashMap; |
@@ -126,7 +126,7 @@ impl<'db> MatchFinder<'db> { | |||
126 | 126 | ||
127 | /// Constructs an instance using the start of the first file in `db` as the lookup context. | 127 | /// Constructs an instance using the start of the first file in `db` as the lookup context. |
128 | pub fn at_first_file(db: &'db ide_db::RootDatabase) -> Result<MatchFinder<'db>, SsrError> { | 128 | pub fn at_first_file(db: &'db ide_db::RootDatabase) -> Result<MatchFinder<'db>, SsrError> { |
129 | use base_db::SourceDatabaseExt; | 129 | use ide_db::base_db::SourceDatabaseExt; |
130 | use ide_db::symbol_index::SymbolsDatabase; | 130 | use ide_db::symbol_index::SymbolsDatabase; |
131 | if let Some(first_file_id) = db | 131 | if let Some(first_file_id) = db |
132 | .local_roots() | 132 | .local_roots() |
@@ -160,7 +160,7 @@ impl<'db> MatchFinder<'db> { | |||
160 | 160 | ||
161 | /// Finds matches for all added rules and returns edits for all found matches. | 161 | /// Finds matches for all added rules and returns edits for all found matches. |
162 | pub fn edits(&self) -> Vec<SourceFileEdit> { | 162 | pub fn edits(&self) -> Vec<SourceFileEdit> { |
163 | use base_db::SourceDatabaseExt; | 163 | use ide_db::base_db::SourceDatabaseExt; |
164 | let mut matches_by_file = FxHashMap::default(); | 164 | let mut matches_by_file = FxHashMap::default(); |
165 | for m in self.matches().matches { | 165 | for m in self.matches().matches { |
166 | matches_by_file | 166 | matches_by_file |
@@ -205,7 +205,7 @@ impl<'db> MatchFinder<'db> { | |||
205 | /// them, while recording reasons why they don't match. This API is useful for command | 205 | /// them, while recording reasons why they don't match. This API is useful for command |
206 | /// line-based debugging where providing a range is difficult. | 206 | /// line-based debugging where providing a range is difficult. |
207 | pub fn debug_where_text_equal(&self, file_id: FileId, snippet: &str) -> Vec<MatchDebugInfo> { | 207 | pub fn debug_where_text_equal(&self, file_id: FileId, snippet: &str) -> Vec<MatchDebugInfo> { |
208 | use base_db::SourceDatabaseExt; | 208 | use ide_db::base_db::SourceDatabaseExt; |
209 | let file = self.sema.parse(file_id); | 209 | let file = self.sema.parse(file_id); |
210 | let mut res = Vec::new(); | 210 | let mut res = Vec::new(); |
211 | let file_text = self.sema.db.file_text(file_id); | 211 | let file_text = self.sema.db.file_text(file_id); |
diff --git a/crates/ssr/src/matching.rs b/crates/ssr/src/matching.rs index 948862a77..99b187311 100644 --- a/crates/ssr/src/matching.rs +++ b/crates/ssr/src/matching.rs | |||
@@ -6,8 +6,8 @@ use crate::{ | |||
6 | resolving::{ResolvedPattern, ResolvedRule, UfcsCallInfo}, | 6 | resolving::{ResolvedPattern, ResolvedRule, UfcsCallInfo}, |
7 | SsrMatches, | 7 | SsrMatches, |
8 | }; | 8 | }; |
9 | use base_db::FileRange; | ||
10 | use hir::Semantics; | 9 | use hir::Semantics; |
10 | use ide_db::base_db::FileRange; | ||
11 | use rustc_hash::FxHashMap; | 11 | use rustc_hash::FxHashMap; |
12 | use std::{cell::Cell, iter::Peekable}; | 12 | use std::{cell::Cell, iter::Peekable}; |
13 | use syntax::ast::{AstNode, AstToken}; | 13 | use syntax::ast::{AstNode, AstToken}; |
diff --git a/crates/ssr/src/resolving.rs b/crates/ssr/src/resolving.rs index 347cc4aad..f5ceb5729 100644 --- a/crates/ssr/src/resolving.rs +++ b/crates/ssr/src/resolving.rs | |||
@@ -2,7 +2,7 @@ | |||
2 | 2 | ||
3 | use crate::errors::error; | 3 | use crate::errors::error; |
4 | use crate::{parsing, SsrError}; | 4 | use crate::{parsing, SsrError}; |
5 | use base_db::FilePosition; | 5 | use ide_db::base_db::FilePosition; |
6 | use parsing::Placeholder; | 6 | use parsing::Placeholder; |
7 | use rustc_hash::FxHashMap; | 7 | use rustc_hash::FxHashMap; |
8 | use syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; | 8 | use syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; |
diff --git a/crates/ssr/src/search.rs b/crates/ssr/src/search.rs index a595fd269..44b5db029 100644 --- a/crates/ssr/src/search.rs +++ b/crates/ssr/src/search.rs | |||
@@ -5,7 +5,7 @@ use crate::{ | |||
5 | resolving::{ResolvedPath, ResolvedPattern, ResolvedRule}, | 5 | resolving::{ResolvedPath, ResolvedPattern, ResolvedRule}, |
6 | Match, MatchFinder, | 6 | Match, MatchFinder, |
7 | }; | 7 | }; |
8 | use base_db::{FileId, FileRange}; | 8 | use ide_db::base_db::{FileId, FileRange}; |
9 | use ide_db::{ | 9 | use ide_db::{ |
10 | defs::Definition, | 10 | defs::Definition, |
11 | search::{Reference, SearchScope}, | 11 | search::{Reference, SearchScope}, |
@@ -145,7 +145,7 @@ impl<'db> MatchFinder<'db> { | |||
145 | fn search_files_do(&self, mut callback: impl FnMut(FileId)) { | 145 | fn search_files_do(&self, mut callback: impl FnMut(FileId)) { |
146 | if self.restrict_ranges.is_empty() { | 146 | if self.restrict_ranges.is_empty() { |
147 | // Unrestricted search. | 147 | // Unrestricted search. |
148 | use base_db::SourceDatabaseExt; | 148 | use ide_db::base_db::SourceDatabaseExt; |
149 | use ide_db::symbol_index::SymbolsDatabase; | 149 | use ide_db::symbol_index::SymbolsDatabase; |
150 | for &root in self.sema.db.local_roots().iter() { | 150 | for &root in self.sema.db.local_roots().iter() { |
151 | let sr = self.sema.db.source_root(root); | 151 | let sr = self.sema.db.source_root(root); |
diff --git a/crates/ssr/src/tests.rs b/crates/ssr/src/tests.rs index 20231a9bc..63131f6ca 100644 --- a/crates/ssr/src/tests.rs +++ b/crates/ssr/src/tests.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | use crate::{MatchFinder, SsrRule}; | 1 | use crate::{MatchFinder, SsrRule}; |
2 | use base_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt}; | ||
3 | use expect_test::{expect, Expect}; | 2 | use expect_test::{expect, Expect}; |
3 | use ide_db::base_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt}; | ||
4 | use rustc_hash::FxHashSet; | 4 | use rustc_hash::FxHashSet; |
5 | use std::sync::Arc; | 5 | use std::sync::Arc; |
6 | use test_utils::{mark, RangeOrOffset}; | 6 | use test_utils::{mark, RangeOrOffset}; |
@@ -62,7 +62,7 @@ fn parser_undefined_placeholder_in_replacement() { | |||
62 | /// `code` may optionally contain a cursor marker `<|>`. If it doesn't, then the position will be | 62 | /// `code` may optionally contain a cursor marker `<|>`. If it doesn't, then the position will be |
63 | /// the start of the file. If there's a second cursor marker, then we'll return a single range. | 63 | /// the start of the file. If there's a second cursor marker, then we'll return a single range. |
64 | pub(crate) fn single_file(code: &str) -> (ide_db::RootDatabase, FilePosition, Vec<FileRange>) { | 64 | pub(crate) fn single_file(code: &str) -> (ide_db::RootDatabase, FilePosition, Vec<FileRange>) { |
65 | use base_db::fixture::WithFixture; | 65 | use ide_db::base_db::fixture::WithFixture; |
66 | use ide_db::symbol_index::SymbolsDatabase; | 66 | use ide_db::symbol_index::SymbolsDatabase; |
67 | let (mut db, file_id, range_or_offset) = if code.contains(test_utils::CURSOR_MARKER) { | 67 | let (mut db, file_id, range_or_offset) = if code.contains(test_utils::CURSOR_MARKER) { |
68 | ide_db::RootDatabase::with_range_or_offset(code) | 68 | ide_db::RootDatabase::with_range_or_offset(code) |
@@ -83,7 +83,7 @@ pub(crate) fn single_file(code: &str) -> (ide_db::RootDatabase, FilePosition, Ve | |||
83 | } | 83 | } |
84 | } | 84 | } |
85 | let mut local_roots = FxHashSet::default(); | 85 | let mut local_roots = FxHashSet::default(); |
86 | local_roots.insert(base_db::fixture::WORKSPACE); | 86 | local_roots.insert(ide_db::base_db::fixture::WORKSPACE); |
87 | db.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH); | 87 | db.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH); |
88 | (db, position, selections) | 88 | (db, position, selections) |
89 | } | 89 | } |
diff --git a/crates/stdx/src/panic_context.rs b/crates/stdx/src/panic_context.rs index fd232e0cc..8d51e20d3 100644 --- a/crates/stdx/src/panic_context.rs +++ b/crates/stdx/src/panic_context.rs | |||
@@ -4,7 +4,7 @@ | |||
4 | 4 | ||
5 | use std::{cell::RefCell, panic, sync::Once}; | 5 | use std::{cell::RefCell, panic, sync::Once}; |
6 | 6 | ||
7 | pub fn enter(context: String) -> impl Drop { | 7 | pub fn enter(context: String) -> PanicContext { |
8 | static ONCE: Once = Once::new(); | 8 | static ONCE: Once = Once::new(); |
9 | ONCE.call_once(PanicContext::init); | 9 | ONCE.call_once(PanicContext::init); |
10 | 10 | ||
@@ -13,7 +13,7 @@ pub fn enter(context: String) -> impl Drop { | |||
13 | } | 13 | } |
14 | 14 | ||
15 | #[must_use] | 15 | #[must_use] |
16 | struct PanicContext { | 16 | pub struct PanicContext { |
17 | _priv: (), | 17 | _priv: (), |
18 | } | 18 | } |
19 | 19 | ||
diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml index c343f2f70..e8de61868 100644 --- a/crates/syntax/Cargo.toml +++ b/crates/syntax/Cargo.toml | |||
@@ -13,10 +13,11 @@ doctest = false | |||
13 | [dependencies] | 13 | [dependencies] |
14 | itertools = "0.9.0" | 14 | itertools = "0.9.0" |
15 | rowan = "0.10.0" | 15 | rowan = "0.10.0" |
16 | rustc_lexer = { version = "683.0.0", package = "rustc-ap-rustc_lexer" } | 16 | rustc_lexer = { version = "685.0.0", package = "rustc-ap-rustc_lexer" } |
17 | rustc-hash = "1.1.0" | 17 | rustc-hash = "1.1.0" |
18 | arrayvec = "0.5.1" | 18 | arrayvec = "0.5.1" |
19 | once_cell = "1.3.1" | 19 | once_cell = "1.3.1" |
20 | indexmap = "1.4.0" | ||
20 | # This crate transitively depends on `smol_str` via `rowan`. | 21 | # This crate transitively depends on `smol_str` via `rowan`. |
21 | # ideally, `serde` should be enabled by `rust-analyzer`, but we enable it here | 22 | # ideally, `serde` should be enabled by `rust-analyzer`, but we enable it here |
22 | # to reduce number of compilations | 23 | # to reduce number of compilations |
@@ -26,10 +27,9 @@ serde = { version = "1.0.106", features = ["derive"] } | |||
26 | stdx = { path = "../stdx", version = "0.0.0" } | 27 | stdx = { path = "../stdx", version = "0.0.0" } |
27 | text_edit = { path = "../text_edit", version = "0.0.0" } | 28 | text_edit = { path = "../text_edit", version = "0.0.0" } |
28 | parser = { path = "../parser", version = "0.0.0" } | 29 | parser = { path = "../parser", version = "0.0.0" } |
30 | test_utils = { path = "../test_utils" } | ||
29 | 31 | ||
30 | [dev-dependencies] | 32 | [dev-dependencies] |
31 | walkdir = "2.3.1" | 33 | walkdir = "2.3.1" |
32 | rayon = "1" | 34 | rayon = "1" |
33 | expect-test = "1.0" | 35 | expect-test = "1.0" |
34 | |||
35 | test_utils = { path = "../test_utils" } | ||
diff --git a/crates/syntax/src/algo.rs b/crates/syntax/src/algo.rs index ea199f9b8..065035fe6 100644 --- a/crates/syntax/src/algo.rs +++ b/crates/syntax/src/algo.rs | |||
@@ -2,11 +2,14 @@ | |||
2 | 2 | ||
3 | use std::{ | 3 | use std::{ |
4 | fmt, | 4 | fmt, |
5 | hash::BuildHasherDefault, | ||
5 | ops::{self, RangeInclusive}, | 6 | ops::{self, RangeInclusive}, |
6 | }; | 7 | }; |
7 | 8 | ||
9 | use indexmap::IndexMap; | ||
8 | use itertools::Itertools; | 10 | use itertools::Itertools; |
9 | use rustc_hash::FxHashMap; | 11 | use rustc_hash::FxHashMap; |
12 | use test_utils::mark; | ||
10 | use text_edit::TextEditBuilder; | 13 | use text_edit::TextEditBuilder; |
11 | 14 | ||
12 | use crate::{ | 15 | use crate::{ |
@@ -106,42 +109,56 @@ pub enum InsertPosition<T> { | |||
106 | After(T), | 109 | After(T), |
107 | } | 110 | } |
108 | 111 | ||
112 | type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<rustc_hash::FxHasher>>; | ||
113 | |||
114 | #[derive(Debug)] | ||
109 | pub struct TreeDiff { | 115 | pub struct TreeDiff { |
110 | replacements: FxHashMap<SyntaxElement, SyntaxElement>, | 116 | replacements: FxHashMap<SyntaxElement, SyntaxElement>, |
117 | deletions: Vec<SyntaxElement>, | ||
118 | // the vec as well as the indexmap are both here to preserve order | ||
119 | insertions: FxIndexMap<SyntaxElement, Vec<SyntaxElement>>, | ||
111 | } | 120 | } |
112 | 121 | ||
113 | impl TreeDiff { | 122 | impl TreeDiff { |
114 | pub fn into_text_edit(&self, builder: &mut TextEditBuilder) { | 123 | pub fn into_text_edit(&self, builder: &mut TextEditBuilder) { |
124 | for (anchor, to) in self.insertions.iter() { | ||
125 | to.iter().for_each(|to| builder.insert(anchor.text_range().end(), to.to_string())); | ||
126 | } | ||
115 | for (from, to) in self.replacements.iter() { | 127 | for (from, to) in self.replacements.iter() { |
116 | builder.replace(from.text_range(), to.to_string()) | 128 | builder.replace(from.text_range(), to.to_string()) |
117 | } | 129 | } |
130 | for text_range in self.deletions.iter().map(SyntaxElement::text_range) { | ||
131 | builder.delete(text_range); | ||
132 | } | ||
118 | } | 133 | } |
119 | 134 | ||
120 | pub fn is_empty(&self) -> bool { | 135 | pub fn is_empty(&self) -> bool { |
121 | self.replacements.is_empty() | 136 | self.replacements.is_empty() && self.deletions.is_empty() && self.insertions.is_empty() |
122 | } | 137 | } |
123 | } | 138 | } |
124 | 139 | ||
125 | /// Finds minimal the diff, which, applied to `from`, will result in `to`. | 140 | /// Finds minimal the diff, which, applied to `from`, will result in `to`. |
126 | /// | 141 | /// |
127 | /// Specifically, returns a map whose keys are descendants of `from` and values | 142 | /// Specifically, returns a structure that consists of a replacements, insertions and deletions |
128 | /// are descendants of `to`, such that `replace_descendants(from, map) == to`. | 143 | /// such that applying this map on `from` will result in `to`. |
129 | /// | 144 | /// |
130 | /// A trivial solution is a singleton map `{ from: to }`, but this function | 145 | /// This function tries to find a fine-grained diff. |
131 | /// tries to find a more fine-grained diff. | ||
132 | pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff { | 146 | pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff { |
133 | let mut buf = FxHashMap::default(); | 147 | let mut diff = TreeDiff { |
134 | // FIXME: this is both horrible inefficient and gives larger than | 148 | replacements: FxHashMap::default(), |
135 | // necessary diff. I bet there's a cool algorithm to diff trees properly. | 149 | insertions: FxIndexMap::default(), |
136 | go(&mut buf, from.clone().into(), to.clone().into()); | 150 | deletions: Vec::new(), |
137 | return TreeDiff { replacements: buf }; | 151 | }; |
138 | 152 | let (from, to) = (from.clone().into(), to.clone().into()); | |
139 | fn go( | 153 | |
140 | buf: &mut FxHashMap<SyntaxElement, SyntaxElement>, | 154 | // FIXME: this is horrible inefficient. I bet there's a cool algorithm to diff trees properly. |
141 | lhs: SyntaxElement, | 155 | if !syntax_element_eq(&from, &to) { |
142 | rhs: SyntaxElement, | 156 | go(&mut diff, from, to); |
143 | ) { | 157 | } |
144 | if lhs.kind() == rhs.kind() | 158 | return diff; |
159 | |||
160 | fn syntax_element_eq(lhs: &SyntaxElement, rhs: &SyntaxElement) -> bool { | ||
161 | lhs.kind() == rhs.kind() | ||
145 | && lhs.text_range().len() == rhs.text_range().len() | 162 | && lhs.text_range().len() == rhs.text_range().len() |
146 | && match (&lhs, &rhs) { | 163 | && match (&lhs, &rhs) { |
147 | (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => { | 164 | (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => { |
@@ -150,18 +167,47 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff { | |||
150 | (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(), | 167 | (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(), |
151 | _ => false, | 168 | _ => false, |
152 | } | 169 | } |
153 | { | 170 | } |
154 | return; | 171 | |
155 | } | 172 | fn go(diff: &mut TreeDiff, lhs: SyntaxElement, rhs: SyntaxElement) { |
156 | if let (Some(lhs), Some(rhs)) = (lhs.as_node(), rhs.as_node()) { | 173 | let (lhs, rhs) = match lhs.as_node().zip(rhs.as_node()) { |
157 | if lhs.children_with_tokens().count() == rhs.children_with_tokens().count() { | 174 | Some((lhs, rhs)) => (lhs, rhs), |
158 | for (lhs, rhs) in lhs.children_with_tokens().zip(rhs.children_with_tokens()) { | 175 | _ => { |
159 | go(buf, lhs, rhs) | 176 | mark::hit!(diff_node_token_replace); |
160 | } | 177 | diff.replacements.insert(lhs, rhs); |
161 | return; | 178 | return; |
162 | } | 179 | } |
180 | }; | ||
181 | |||
182 | let mut rhs_children = rhs.children_with_tokens(); | ||
183 | let mut lhs_children = lhs.children_with_tokens(); | ||
184 | let mut last_lhs = None; | ||
185 | loop { | ||
186 | let lhs_child = lhs_children.next(); | ||
187 | match (lhs_child.clone(), rhs_children.next()) { | ||
188 | (None, None) => break, | ||
189 | (None, Some(element)) => match last_lhs.clone() { | ||
190 | Some(prev) => { | ||
191 | mark::hit!(diff_insert); | ||
192 | diff.insertions.entry(prev).or_insert_with(Vec::new).push(element); | ||
193 | } | ||
194 | // first iteration, this means we got no anchor element to insert after | ||
195 | // therefor replace the parent node instead | ||
196 | None => { | ||
197 | mark::hit!(diff_replace_parent); | ||
198 | diff.replacements.insert(lhs.clone().into(), rhs.clone().into()); | ||
199 | break; | ||
200 | } | ||
201 | }, | ||
202 | (Some(element), None) => { | ||
203 | mark::hit!(diff_delete); | ||
204 | diff.deletions.push(element); | ||
205 | } | ||
206 | (Some(ref lhs_ele), Some(ref rhs_ele)) if syntax_element_eq(lhs_ele, rhs_ele) => {} | ||
207 | (Some(lhs_ele), Some(rhs_ele)) => go(diff, lhs_ele, rhs_ele), | ||
208 | } | ||
209 | last_lhs = lhs_child.or(last_lhs); | ||
163 | } | 210 | } |
164 | buf.insert(lhs, rhs); | ||
165 | } | 211 | } |
166 | } | 212 | } |
167 | 213 | ||
@@ -243,11 +289,19 @@ fn _replace_children( | |||
243 | with_children(parent, new_children) | 289 | with_children(parent, new_children) |
244 | } | 290 | } |
245 | 291 | ||
292 | #[derive(Debug, PartialEq, Eq, Hash)] | ||
293 | enum InsertPos { | ||
294 | FirstChildOf(SyntaxNode), | ||
295 | // Before(SyntaxElement), | ||
296 | After(SyntaxElement), | ||
297 | } | ||
298 | |||
246 | #[derive(Default)] | 299 | #[derive(Default)] |
247 | pub struct SyntaxRewriter<'a> { | 300 | pub struct SyntaxRewriter<'a> { |
248 | f: Option<Box<dyn Fn(&SyntaxElement) -> Option<SyntaxElement> + 'a>>, | 301 | f: Option<Box<dyn Fn(&SyntaxElement) -> Option<SyntaxElement> + 'a>>, |
249 | //FIXME: add debug_assertions that all elements are in fact from the same file. | 302 | //FIXME: add debug_assertions that all elements are in fact from the same file. |
250 | replacements: FxHashMap<SyntaxElement, Replacement>, | 303 | replacements: FxHashMap<SyntaxElement, Replacement>, |
304 | insertions: IndexMap<InsertPos, Vec<SyntaxElement>>, | ||
251 | } | 305 | } |
252 | 306 | ||
253 | impl fmt::Debug for SyntaxRewriter<'_> { | 307 | impl fmt::Debug for SyntaxRewriter<'_> { |
@@ -258,13 +312,96 @@ impl fmt::Debug for SyntaxRewriter<'_> { | |||
258 | 312 | ||
259 | impl<'a> SyntaxRewriter<'a> { | 313 | impl<'a> SyntaxRewriter<'a> { |
260 | pub fn from_fn(f: impl Fn(&SyntaxElement) -> Option<SyntaxElement> + 'a) -> SyntaxRewriter<'a> { | 314 | pub fn from_fn(f: impl Fn(&SyntaxElement) -> Option<SyntaxElement> + 'a) -> SyntaxRewriter<'a> { |
261 | SyntaxRewriter { f: Some(Box::new(f)), replacements: FxHashMap::default() } | 315 | SyntaxRewriter { |
316 | f: Some(Box::new(f)), | ||
317 | replacements: FxHashMap::default(), | ||
318 | insertions: IndexMap::default(), | ||
319 | } | ||
262 | } | 320 | } |
263 | pub fn delete<T: Clone + Into<SyntaxElement>>(&mut self, what: &T) { | 321 | pub fn delete<T: Clone + Into<SyntaxElement>>(&mut self, what: &T) { |
264 | let what = what.clone().into(); | 322 | let what = what.clone().into(); |
265 | let replacement = Replacement::Delete; | 323 | let replacement = Replacement::Delete; |
266 | self.replacements.insert(what, replacement); | 324 | self.replacements.insert(what, replacement); |
267 | } | 325 | } |
326 | pub fn insert_before<T: Clone + Into<SyntaxElement>, U: Clone + Into<SyntaxElement>>( | ||
327 | &mut self, | ||
328 | before: &T, | ||
329 | what: &U, | ||
330 | ) { | ||
331 | let before = before.clone().into(); | ||
332 | let pos = match before.prev_sibling_or_token() { | ||
333 | Some(sibling) => InsertPos::After(sibling), | ||
334 | None => match before.parent() { | ||
335 | Some(parent) => InsertPos::FirstChildOf(parent), | ||
336 | None => return, | ||
337 | }, | ||
338 | }; | ||
339 | self.insertions.entry(pos).or_insert_with(Vec::new).push(what.clone().into()); | ||
340 | } | ||
341 | pub fn insert_after<T: Clone + Into<SyntaxElement>, U: Clone + Into<SyntaxElement>>( | ||
342 | &mut self, | ||
343 | after: &T, | ||
344 | what: &U, | ||
345 | ) { | ||
346 | self.insertions | ||
347 | .entry(InsertPos::After(after.clone().into())) | ||
348 | .or_insert_with(Vec::new) | ||
349 | .push(what.clone().into()); | ||
350 | } | ||
351 | pub fn insert_as_first_child<T: Clone + Into<SyntaxNode>, U: Clone + Into<SyntaxElement>>( | ||
352 | &mut self, | ||
353 | parent: &T, | ||
354 | what: &U, | ||
355 | ) { | ||
356 | self.insertions | ||
357 | .entry(InsertPos::FirstChildOf(parent.clone().into())) | ||
358 | .or_insert_with(Vec::new) | ||
359 | .push(what.clone().into()); | ||
360 | } | ||
361 | pub fn insert_many_before< | ||
362 | T: Clone + Into<SyntaxElement>, | ||
363 | U: IntoIterator<Item = SyntaxElement>, | ||
364 | >( | ||
365 | &mut self, | ||
366 | before: &T, | ||
367 | what: U, | ||
368 | ) { | ||
369 | let before = before.clone().into(); | ||
370 | let pos = match before.prev_sibling_or_token() { | ||
371 | Some(sibling) => InsertPos::After(sibling), | ||
372 | None => match before.parent() { | ||
373 | Some(parent) => InsertPos::FirstChildOf(parent), | ||
374 | None => return, | ||
375 | }, | ||
376 | }; | ||
377 | self.insertions.entry(pos).or_insert_with(Vec::new).extend(what); | ||
378 | } | ||
379 | pub fn insert_many_after< | ||
380 | T: Clone + Into<SyntaxElement>, | ||
381 | U: IntoIterator<Item = SyntaxElement>, | ||
382 | >( | ||
383 | &mut self, | ||
384 | after: &T, | ||
385 | what: U, | ||
386 | ) { | ||
387 | self.insertions | ||
388 | .entry(InsertPos::After(after.clone().into())) | ||
389 | .or_insert_with(Vec::new) | ||
390 | .extend(what); | ||
391 | } | ||
392 | pub fn insert_many_as_first_children< | ||
393 | T: Clone + Into<SyntaxNode>, | ||
394 | U: IntoIterator<Item = SyntaxElement>, | ||
395 | >( | ||
396 | &mut self, | ||
397 | parent: &T, | ||
398 | what: U, | ||
399 | ) { | ||
400 | self.insertions | ||
401 | .entry(InsertPos::FirstChildOf(parent.clone().into())) | ||
402 | .or_insert_with(Vec::new) | ||
403 | .extend(what) | ||
404 | } | ||
268 | pub fn replace<T: Clone + Into<SyntaxElement>>(&mut self, what: &T, with: &T) { | 405 | pub fn replace<T: Clone + Into<SyntaxElement>>(&mut self, what: &T, with: &T) { |
269 | let what = what.clone().into(); | 406 | let what = what.clone().into(); |
270 | let replacement = Replacement::Single(with.clone().into()); | 407 | let replacement = Replacement::Single(with.clone().into()); |
@@ -284,7 +421,7 @@ impl<'a> SyntaxRewriter<'a> { | |||
284 | } | 421 | } |
285 | 422 | ||
286 | pub fn rewrite(&self, node: &SyntaxNode) -> SyntaxNode { | 423 | pub fn rewrite(&self, node: &SyntaxNode) -> SyntaxNode { |
287 | if self.f.is_none() && self.replacements.is_empty() { | 424 | if self.f.is_none() && self.replacements.is_empty() && self.insertions.is_empty() { |
288 | return node.clone(); | 425 | return node.clone(); |
289 | } | 426 | } |
290 | self.rewrite_children(node) | 427 | self.rewrite_children(node) |
@@ -300,14 +437,22 @@ impl<'a> SyntaxRewriter<'a> { | |||
300 | /// | 437 | /// |
301 | /// Returns `None` when there are no replacements. | 438 | /// Returns `None` when there are no replacements. |
302 | pub fn rewrite_root(&self) -> Option<SyntaxNode> { | 439 | pub fn rewrite_root(&self) -> Option<SyntaxNode> { |
440 | fn element_to_node_or_parent(element: &SyntaxElement) -> SyntaxNode { | ||
441 | match element { | ||
442 | SyntaxElement::Node(it) => it.clone(), | ||
443 | SyntaxElement::Token(it) => it.parent(), | ||
444 | } | ||
445 | } | ||
446 | |||
303 | assert!(self.f.is_none()); | 447 | assert!(self.f.is_none()); |
304 | self.replacements | 448 | self.replacements |
305 | .keys() | 449 | .keys() |
306 | .map(|element| match element { | 450 | .map(element_to_node_or_parent) |
307 | SyntaxElement::Node(it) => it.clone(), | 451 | .chain(self.insertions.keys().map(|pos| match pos { |
308 | SyntaxElement::Token(it) => it.parent(), | 452 | InsertPos::FirstChildOf(it) => it.clone(), |
309 | }) | 453 | InsertPos::After(it) => element_to_node_or_parent(it), |
310 | // If we only have one replacement, we must return its parent node, since `rewrite` does | 454 | })) |
455 | // If we only have one replacement/insertion, we must return its parent node, since `rewrite` does | ||
311 | // not replace the node passed to it. | 456 | // not replace the node passed to it. |
312 | .map(|it| it.parent().unwrap_or(it)) | 457 | .map(|it| it.parent().unwrap_or(it)) |
313 | .fold1(|a, b| least_common_ancestor(&a, &b).unwrap()) | 458 | .fold1(|a, b| least_common_ancestor(&a, &b).unwrap()) |
@@ -321,9 +466,16 @@ impl<'a> SyntaxRewriter<'a> { | |||
321 | self.replacements.get(element).cloned() | 466 | self.replacements.get(element).cloned() |
322 | } | 467 | } |
323 | 468 | ||
469 | fn insertions(&self, pos: &InsertPos) -> Option<impl Iterator<Item = SyntaxElement> + '_> { | ||
470 | self.insertions.get(pos).map(|insertions| insertions.iter().cloned()) | ||
471 | } | ||
472 | |||
324 | fn rewrite_children(&self, node: &SyntaxNode) -> SyntaxNode { | 473 | fn rewrite_children(&self, node: &SyntaxNode) -> SyntaxNode { |
325 | // FIXME: this could be made much faster. | 474 | // FIXME: this could be made much faster. |
326 | let mut new_children = Vec::new(); | 475 | let mut new_children = Vec::new(); |
476 | if let Some(elements) = self.insertions(&InsertPos::FirstChildOf(node.clone())) { | ||
477 | new_children.extend(elements.map(element_to_green)); | ||
478 | } | ||
327 | for child in node.children_with_tokens() { | 479 | for child in node.children_with_tokens() { |
328 | self.rewrite_self(&mut new_children, &child); | 480 | self.rewrite_self(&mut new_children, &child); |
329 | } | 481 | } |
@@ -337,34 +489,45 @@ impl<'a> SyntaxRewriter<'a> { | |||
337 | ) { | 489 | ) { |
338 | if let Some(replacement) = self.replacement(&element) { | 490 | if let Some(replacement) = self.replacement(&element) { |
339 | match replacement { | 491 | match replacement { |
340 | Replacement::Single(NodeOrToken::Node(it)) => { | 492 | Replacement::Single(element) => acc.push(element_to_green(element)), |
341 | acc.push(NodeOrToken::Node(it.green().clone())) | ||
342 | } | ||
343 | Replacement::Single(NodeOrToken::Token(it)) => { | ||
344 | acc.push(NodeOrToken::Token(it.green().clone())) | ||
345 | } | ||
346 | Replacement::Many(replacements) => { | 493 | Replacement::Many(replacements) => { |
347 | acc.extend(replacements.iter().map(|it| match it { | 494 | acc.extend(replacements.into_iter().map(element_to_green)) |
348 | NodeOrToken::Node(it) => NodeOrToken::Node(it.green().clone()), | ||
349 | NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()), | ||
350 | })) | ||
351 | } | 495 | } |
352 | Replacement::Delete => (), | 496 | Replacement::Delete => (), |
353 | }; | 497 | }; |
354 | return; | 498 | } else { |
499 | match element { | ||
500 | NodeOrToken::Token(it) => acc.push(NodeOrToken::Token(it.green().clone())), | ||
501 | NodeOrToken::Node(it) => { | ||
502 | acc.push(NodeOrToken::Node(self.rewrite_children(it).green().clone())); | ||
503 | } | ||
504 | } | ||
505 | } | ||
506 | if let Some(elements) = self.insertions(&InsertPos::After(element.clone())) { | ||
507 | acc.extend(elements.map(element_to_green)); | ||
355 | } | 508 | } |
356 | let res = match element { | 509 | } |
357 | NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()), | 510 | } |
358 | NodeOrToken::Node(it) => NodeOrToken::Node(self.rewrite_children(it).green().clone()), | 511 | |
359 | }; | 512 | fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { |
360 | acc.push(res) | 513 | match element { |
514 | NodeOrToken::Node(it) => NodeOrToken::Node(it.green().clone()), | ||
515 | NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()), | ||
361 | } | 516 | } |
362 | } | 517 | } |
363 | 518 | ||
364 | impl ops::AddAssign for SyntaxRewriter<'_> { | 519 | impl ops::AddAssign for SyntaxRewriter<'_> { |
365 | fn add_assign(&mut self, rhs: SyntaxRewriter) { | 520 | fn add_assign(&mut self, rhs: SyntaxRewriter) { |
366 | assert!(rhs.f.is_none()); | 521 | assert!(rhs.f.is_none()); |
367 | self.replacements.extend(rhs.replacements) | 522 | self.replacements.extend(rhs.replacements); |
523 | for (pos, insertions) in rhs.insertions.into_iter() { | ||
524 | match self.insertions.entry(pos) { | ||
525 | indexmap::map::Entry::Occupied(mut occupied) => { | ||
526 | occupied.get_mut().extend(insertions) | ||
527 | } | ||
528 | indexmap::map::Entry::Vacant(vacant) => drop(vacant.insert(insertions)), | ||
529 | } | ||
530 | } | ||
368 | } | 531 | } |
369 | } | 532 | } |
370 | 533 | ||
@@ -404,3 +567,322 @@ fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, row | |||
404 | NodeOrToken::Token(it) => it.green().clone().into(), | 567 | NodeOrToken::Token(it) => it.green().clone().into(), |
405 | } | 568 | } |
406 | } | 569 | } |
570 | |||
571 | #[cfg(test)] | ||
572 | mod tests { | ||
573 | use expect_test::{expect, Expect}; | ||
574 | use itertools::Itertools; | ||
575 | use parser::SyntaxKind; | ||
576 | use test_utils::mark; | ||
577 | use text_edit::TextEdit; | ||
578 | |||
579 | use crate::{AstNode, SyntaxElement}; | ||
580 | |||
581 | #[test] | ||
582 | fn replace_node_token() { | ||
583 | mark::check!(diff_node_token_replace); | ||
584 | check_diff( | ||
585 | r#"use node;"#, | ||
586 | r#"ident"#, | ||
587 | expect![[r#" | ||
588 | insertions: | ||
589 | |||
590 | |||
591 | |||
592 | replacements: | ||
593 | |||
594 | Line 0: Token([email protected] "use") -> ident | ||
595 | |||
596 | deletions: | ||
597 | |||
598 | Line 1: " " | ||
599 | Line 1: node | ||
600 | Line 1: ; | ||
601 | "#]], | ||
602 | ); | ||
603 | } | ||
604 | |||
605 | #[test] | ||
606 | fn insert() { | ||
607 | mark::check!(diff_insert); | ||
608 | check_diff( | ||
609 | r#"use foo;"#, | ||
610 | r#"use foo; | ||
611 | use bar;"#, | ||
612 | expect![[r#" | ||
613 | insertions: | ||
614 | |||
615 | Line 0: Node([email protected]) | ||
616 | -> "\n" | ||
617 | -> use bar; | ||
618 | |||
619 | replacements: | ||
620 | |||
621 | |||
622 | |||
623 | deletions: | ||
624 | |||
625 | |||
626 | "#]], | ||
627 | ); | ||
628 | } | ||
629 | |||
630 | #[test] | ||
631 | fn replace_parent() { | ||
632 | mark::check!(diff_replace_parent); | ||
633 | check_diff( | ||
634 | r#""#, | ||
635 | r#"use foo::bar;"#, | ||
636 | expect![[r#" | ||
637 | insertions: | ||
638 | |||
639 | |||
640 | |||
641 | replacements: | ||
642 | |||
643 | Line 0: Node([email protected]) -> use foo::bar; | ||
644 | |||
645 | deletions: | ||
646 | |||
647 | |||
648 | "#]], | ||
649 | ); | ||
650 | } | ||
651 | |||
652 | #[test] | ||
653 | fn delete() { | ||
654 | mark::check!(diff_delete); | ||
655 | check_diff( | ||
656 | r#"use foo; | ||
657 | use bar;"#, | ||
658 | r#"use foo;"#, | ||
659 | expect![[r#" | ||
660 | insertions: | ||
661 | |||
662 | |||
663 | |||
664 | replacements: | ||
665 | |||
666 | |||
667 | |||
668 | deletions: | ||
669 | |||
670 | Line 1: "\n " | ||
671 | Line 2: use bar; | ||
672 | "#]], | ||
673 | ); | ||
674 | } | ||
675 | |||
676 | #[test] | ||
677 | fn insert_use() { | ||
678 | check_diff( | ||
679 | r#" | ||
680 | use expect_test::{expect, Expect}; | ||
681 | |||
682 | use crate::AstNode; | ||
683 | "#, | ||
684 | r#" | ||
685 | use expect_test::{expect, Expect}; | ||
686 | use text_edit::TextEdit; | ||
687 | |||
688 | use crate::AstNode; | ||
689 | "#, | ||
690 | expect![[r#" | ||
691 | insertions: | ||
692 | |||
693 | Line 4: Token([email protected] "\n") | ||
694 | -> use crate::AstNode; | ||
695 | -> "\n" | ||
696 | |||
697 | replacements: | ||
698 | |||
699 | Line 2: Token([email protected] "\n\n") -> "\n" | ||
700 | Line 4: Token([email protected] "crate") -> text_edit | ||
701 | Line 4: Token([email protected] "AstNode") -> TextEdit | ||
702 | Line 4: Token([email protected] "\n") -> "\n\n" | ||
703 | |||
704 | deletions: | ||
705 | |||
706 | |||
707 | "#]], | ||
708 | ) | ||
709 | } | ||
710 | |||
711 | #[test] | ||
712 | fn remove_use() { | ||
713 | check_diff( | ||
714 | r#" | ||
715 | use expect_test::{expect, Expect}; | ||
716 | use text_edit::TextEdit; | ||
717 | |||
718 | use crate::AstNode; | ||
719 | "#, | ||
720 | r#" | ||
721 | use expect_test::{expect, Expect}; | ||
722 | |||
723 | use crate::AstNode; | ||
724 | "#, | ||
725 | expect![[r#" | ||
726 | insertions: | ||
727 | |||
728 | |||
729 | |||
730 | replacements: | ||
731 | |||
732 | Line 2: Token([email protected] "\n") -> "\n\n" | ||
733 | Line 3: Node([email protected]) -> crate | ||
734 | Line 3: Token([email protected] "TextEdit") -> AstNode | ||
735 | Line 3: Token([email protected] "\n\n") -> "\n" | ||
736 | |||
737 | deletions: | ||
738 | |||
739 | Line 4: use crate::AstNode; | ||
740 | Line 5: "\n" | ||
741 | "#]], | ||
742 | ) | ||
743 | } | ||
744 | |||
745 | #[test] | ||
746 | fn merge_use() { | ||
747 | check_diff( | ||
748 | r#" | ||
749 | use std::{ | ||
750 | fmt, | ||
751 | hash::BuildHasherDefault, | ||
752 | ops::{self, RangeInclusive}, | ||
753 | }; | ||
754 | "#, | ||
755 | r#" | ||
756 | use std::fmt; | ||
757 | use std::hash::BuildHasherDefault; | ||
758 | use std::ops::{self, RangeInclusive}; | ||
759 | "#, | ||
760 | expect![[r#" | ||
761 | insertions: | ||
762 | |||
763 | Line 2: Node([email protected]) | ||
764 | -> :: | ||
765 | -> fmt | ||
766 | Line 6: Token([email protected] "\n") | ||
767 | -> use std::hash::BuildHasherDefault; | ||
768 | -> "\n" | ||
769 | -> use std::ops::{self, RangeInclusive}; | ||
770 | -> "\n" | ||
771 | |||
772 | replacements: | ||
773 | |||
774 | Line 2: Token([email protected] "std") -> std | ||
775 | |||
776 | deletions: | ||
777 | |||
778 | Line 2: :: | ||
779 | Line 2: { | ||
780 | fmt, | ||
781 | hash::BuildHasherDefault, | ||
782 | ops::{self, RangeInclusive}, | ||
783 | } | ||
784 | "#]], | ||
785 | ) | ||
786 | } | ||
787 | |||
788 | #[test] | ||
789 | fn early_return_assist() { | ||
790 | check_diff( | ||
791 | r#" | ||
792 | fn main() { | ||
793 | if let Ok(x) = Err(92) { | ||
794 | foo(x); | ||
795 | } | ||
796 | } | ||
797 | "#, | ||
798 | r#" | ||
799 | fn main() { | ||
800 | let x = match Err(92) { | ||
801 | Ok(it) => it, | ||
802 | _ => return, | ||
803 | }; | ||
804 | foo(x); | ||
805 | } | ||
806 | "#, | ||
807 | expect![[r#" | ||
808 | insertions: | ||
809 | |||
810 | Line 3: Node([email protected]) | ||
811 | -> " " | ||
812 | -> match Err(92) { | ||
813 | Ok(it) => it, | ||
814 | _ => return, | ||
815 | } | ||
816 | -> ; | ||
817 | Line 5: Token([email protected] "}") | ||
818 | -> "\n" | ||
819 | -> } | ||
820 | |||
821 | replacements: | ||
822 | |||
823 | Line 3: Token([email protected] "if") -> let | ||
824 | Line 3: Token([email protected] "let") -> x | ||
825 | Line 3: Node([email protected]) -> = | ||
826 | Line 5: Token([email protected] "\n") -> "\n " | ||
827 | Line 5: Token([email protected] "}") -> foo(x); | ||
828 | |||
829 | deletions: | ||
830 | |||
831 | Line 3: " " | ||
832 | Line 3: Ok(x) | ||
833 | Line 3: " " | ||
834 | Line 3: = | ||
835 | Line 3: " " | ||
836 | Line 3: Err(92) | ||
837 | "#]], | ||
838 | ) | ||
839 | } | ||
840 | |||
841 | fn check_diff(from: &str, to: &str, expected_diff: Expect) { | ||
842 | let from_node = crate::SourceFile::parse(from).tree().syntax().clone(); | ||
843 | let to_node = crate::SourceFile::parse(to).tree().syntax().clone(); | ||
844 | let diff = super::diff(&from_node, &to_node); | ||
845 | |||
846 | let line_number = | ||
847 | |syn: &SyntaxElement| from[..syn.text_range().start().into()].lines().count(); | ||
848 | |||
849 | let fmt_syntax = |syn: &SyntaxElement| match syn.kind() { | ||
850 | SyntaxKind::WHITESPACE => format!("{:?}", syn.to_string()), | ||
851 | _ => format!("{}", syn), | ||
852 | }; | ||
853 | |||
854 | let insertions = diff.insertions.iter().format_with("\n", |(k, v), f| { | ||
855 | f(&format!( | ||
856 | "Line {}: {:?}\n-> {}", | ||
857 | line_number(k), | ||
858 | k, | ||
859 | v.iter().format_with("\n-> ", |v, f| f(&fmt_syntax(v))) | ||
860 | )) | ||
861 | }); | ||
862 | |||
863 | let replacements = diff | ||
864 | .replacements | ||
865 | .iter() | ||
866 | .sorted_by_key(|(syntax, _)| syntax.text_range().start()) | ||
867 | .format_with("\n", |(k, v), f| { | ||
868 | f(&format!("Line {}: {:?} -> {}", line_number(k), k, fmt_syntax(v))) | ||
869 | }); | ||
870 | |||
871 | let deletions = diff | ||
872 | .deletions | ||
873 | .iter() | ||
874 | .format_with("\n", |v, f| f(&format!("Line {}: {}", line_number(v), &fmt_syntax(v)))); | ||
875 | |||
876 | let actual = format!( | ||
877 | "insertions:\n\n{}\n\nreplacements:\n\n{}\n\ndeletions:\n\n{}\n", | ||
878 | insertions, replacements, deletions | ||
879 | ); | ||
880 | expected_diff.assert_eq(&actual); | ||
881 | |||
882 | let mut from = from.to_owned(); | ||
883 | let mut text_edit = TextEdit::builder(); | ||
884 | diff.into_text_edit(&mut text_edit); | ||
885 | text_edit.finish().apply(&mut from); | ||
886 | assert_eq!(&*from, to, "diff did not turn `from` to `to`"); | ||
887 | } | ||
888 | } | ||
diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 74dbdfaf7..5b06cb767 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs | |||
@@ -172,6 +172,9 @@ pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr { | |||
172 | pub fn expr_method_call(receiver: ast::Expr, method: &str, arg_list: ast::ArgList) -> ast::Expr { | 172 | pub fn expr_method_call(receiver: ast::Expr, method: &str, arg_list: ast::ArgList) -> ast::Expr { |
173 | expr_from_text(&format!("{}.{}{}", receiver, method, arg_list)) | 173 | expr_from_text(&format!("{}.{}{}", receiver, method, arg_list)) |
174 | } | 174 | } |
175 | pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr { | ||
176 | expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) }) | ||
177 | } | ||
175 | fn expr_from_text(text: &str) -> ast::Expr { | 178 | fn expr_from_text(text: &str) -> ast::Expr { |
176 | ast_from_text(&format!("const C: () = {};", text)) | 179 | ast_from_text(&format!("const C: () = {};", text)) |
177 | } | 180 | } |
diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs index 50c1c157d..c5cd1c504 100644 --- a/crates/syntax/src/ast/node_ext.rs +++ b/crates/syntax/src/ast/node_ext.rs | |||
@@ -7,7 +7,7 @@ use itertools::Itertools; | |||
7 | use parser::SyntaxKind; | 7 | use parser::SyntaxKind; |
8 | 8 | ||
9 | use crate::{ | 9 | use crate::{ |
10 | ast::{self, support, AstNode, NameOwner, SyntaxNode}, | 10 | ast::{self, support, token_ext::HasStringValue, AstNode, AstToken, NameOwner, SyntaxNode}, |
11 | SmolStr, SyntaxElement, SyntaxToken, T, | 11 | SmolStr, SyntaxElement, SyntaxToken, T, |
12 | }; | 12 | }; |
13 | 13 | ||
@@ -53,8 +53,16 @@ impl ast::Attr { | |||
53 | pub fn as_simple_key_value(&self) -> Option<(SmolStr, SmolStr)> { | 53 | pub fn as_simple_key_value(&self) -> Option<(SmolStr, SmolStr)> { |
54 | let lit = self.literal()?; | 54 | let lit = self.literal()?; |
55 | let key = self.simple_name()?; | 55 | let key = self.simple_name()?; |
56 | // FIXME: escape? raw string? | 56 | let value_token = lit.syntax().first_token()?; |
57 | let value = lit.syntax().first_token()?.text().trim_matches('"').into(); | 57 | |
58 | let value: SmolStr = if let Some(s) = ast::String::cast(value_token.clone()) { | ||
59 | s.value()?.into() | ||
60 | } else if let Some(s) = ast::RawString::cast(value_token) { | ||
61 | s.value()?.into() | ||
62 | } else { | ||
63 | return None; | ||
64 | }; | ||
65 | |||
58 | Some((key, value)) | 66 | Some((key, value)) |
59 | } | 67 | } |
60 | 68 | ||
diff --git a/crates/syntax/src/display.rs b/crates/syntax/src/display.rs new file mode 100644 index 000000000..8d2c7eae4 --- /dev/null +++ b/crates/syntax/src/display.rs | |||
@@ -0,0 +1,83 @@ | |||
1 | //! This module contains utilities for turning SyntaxNodes and HIR types | ||
2 | //! into types that may be used to render in a UI. | ||
3 | |||
4 | use crate::{ | ||
5 | ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner}, | ||
6 | SyntaxKind::{ATTR, COMMENT}, | ||
7 | }; | ||
8 | |||
9 | use ast::VisibilityOwner; | ||
10 | use stdx::format_to; | ||
11 | |||
12 | pub fn function_declaration(node: &ast::Fn) -> String { | ||
13 | let mut buf = String::new(); | ||
14 | if let Some(vis) = node.visibility() { | ||
15 | format_to!(buf, "{} ", vis); | ||
16 | } | ||
17 | if node.async_token().is_some() { | ||
18 | format_to!(buf, "async "); | ||
19 | } | ||
20 | if node.const_token().is_some() { | ||
21 | format_to!(buf, "const "); | ||
22 | } | ||
23 | if node.unsafe_token().is_some() { | ||
24 | format_to!(buf, "unsafe "); | ||
25 | } | ||
26 | if let Some(abi) = node.abi() { | ||
27 | // Keyword `extern` is included in the string. | ||
28 | format_to!(buf, "{} ", abi); | ||
29 | } | ||
30 | if let Some(name) = node.name() { | ||
31 | format_to!(buf, "fn {}", name) | ||
32 | } | ||
33 | if let Some(type_params) = node.generic_param_list() { | ||
34 | format_to!(buf, "{}", type_params); | ||
35 | } | ||
36 | if let Some(param_list) = node.param_list() { | ||
37 | let params: Vec<String> = param_list | ||
38 | .self_param() | ||
39 | .into_iter() | ||
40 | .map(|self_param| self_param.to_string()) | ||
41 | .chain(param_list.params().map(|param| param.to_string())) | ||
42 | .collect(); | ||
43 | // Useful to inline parameters | ||
44 | format_to!(buf, "({})", params.join(", ")); | ||
45 | } | ||
46 | if let Some(ret_type) = node.ret_type() { | ||
47 | if ret_type.ty().is_some() { | ||
48 | format_to!(buf, " {}", ret_type); | ||
49 | } | ||
50 | } | ||
51 | if let Some(where_clause) = node.where_clause() { | ||
52 | format_to!(buf, "\n{}", where_clause); | ||
53 | } | ||
54 | buf | ||
55 | } | ||
56 | |||
57 | pub fn const_label(node: &ast::Const) -> String { | ||
58 | let label: String = node | ||
59 | .syntax() | ||
60 | .children_with_tokens() | ||
61 | .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR)) | ||
62 | .map(|node| node.to_string()) | ||
63 | .collect(); | ||
64 | |||
65 | label.trim().to_owned() | ||
66 | } | ||
67 | |||
68 | pub fn type_label(node: &ast::TypeAlias) -> String { | ||
69 | let label: String = node | ||
70 | .syntax() | ||
71 | .children_with_tokens() | ||
72 | .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR)) | ||
73 | .map(|node| node.to_string()) | ||
74 | .collect(); | ||
75 | |||
76 | label.trim().to_owned() | ||
77 | } | ||
78 | |||
79 | pub fn macro_label(node: &ast::MacroCall) -> String { | ||
80 | let name = node.name().map(|name| name.syntax().text().to_string()).unwrap_or_default(); | ||
81 | let vis = if node.has_atom_attr("macro_export") { "#[macro_export]\n" } else { "" }; | ||
82 | format!("{}macro_rules! {}", vis, name) | ||
83 | } | ||
diff --git a/crates/syntax/src/lib.rs b/crates/syntax/src/lib.rs index 7f8da66af..849a1cdd6 100644 --- a/crates/syntax/src/lib.rs +++ b/crates/syntax/src/lib.rs | |||
@@ -32,6 +32,7 @@ mod ptr; | |||
32 | #[cfg(test)] | 32 | #[cfg(test)] |
33 | mod tests; | 33 | mod tests; |
34 | 34 | ||
35 | pub mod display; | ||
35 | pub mod algo; | 36 | pub mod algo; |
36 | pub mod ast; | 37 | pub mod ast; |
37 | #[doc(hidden)] | 38 | #[doc(hidden)] |
diff --git a/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast new file mode 100644 index 000000000..c204f0e2d --- /dev/null +++ b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast | |||
@@ -0,0 +1,54 @@ | |||
1 | [email protected] | ||
2 | [email protected] | ||
3 | [email protected] "struct" | ||
4 | [email protected] " " | ||
5 | [email protected] | ||
6 | [email protected] "B" | ||
7 | [email protected] | ||
8 | [email protected] "(" | ||
9 | [email protected] | ||
10 | [email protected] | ||
11 | [email protected] "pub" | ||
12 | [email protected] " " | ||
13 | [email protected] | ||
14 | [email protected] "(" | ||
15 | [email protected] | ||
16 | [email protected] | ||
17 | [email protected] | ||
18 | [email protected] | ||
19 | [email protected] "super" | ||
20 | [email protected] "::" | ||
21 | [email protected] | ||
22 | [email protected] | ||
23 | [email protected] "A" | ||
24 | [email protected] ")" | ||
25 | [email protected] ")" | ||
26 | [email protected] ";" | ||
27 | [email protected] "\n" | ||
28 | [email protected] | ||
29 | [email protected] "struct" | ||
30 | [email protected] " " | ||
31 | [email protected] | ||
32 | [email protected] "B" | ||
33 | [email protected] | ||
34 | [email protected] "(" | ||
35 | [email protected] | ||
36 | [email protected] | ||
37 | [email protected] "pub" | ||
38 | [email protected] " " | ||
39 | [email protected] | ||
40 | [email protected] "(" | ||
41 | [email protected] | ||
42 | [email protected] | ||
43 | [email protected] | ||
44 | [email protected] | ||
45 | [email protected] "crate" | ||
46 | [email protected] "::" | ||
47 | [email protected] | ||
48 | [email protected] | ||
49 | [email protected] "A" | ||
50 | [email protected] "," | ||
51 | [email protected] ")" | ||
52 | [email protected] ")" | ||
53 | [email protected] ";" | ||
54 | [email protected] "\n" | ||
diff --git a/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs new file mode 100644 index 000000000..d4c163822 --- /dev/null +++ b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs | |||
@@ -0,0 +1,2 @@ | |||
1 | struct B(pub (super::A)); | ||
2 | struct B(pub (crate::A,)); | ||
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index ad586c882..a49be4602 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs | |||
@@ -43,12 +43,12 @@ macro_rules! assert_eq_text { | |||
43 | let right = $right; | 43 | let right = $right; |
44 | if left != right { | 44 | if left != right { |
45 | if left.trim() == right.trim() { | 45 | if left.trim() == right.trim() { |
46 | eprintln!("Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n", left, right); | 46 | std::eprintln!("Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n", left, right); |
47 | } else { | 47 | } else { |
48 | let changeset = $crate::__Changeset::new(left, right, "\n"); | 48 | let changeset = $crate::__Changeset::new(left, right, "\n"); |
49 | eprintln!("Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n", left, right, changeset); | 49 | std::eprintln!("Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n", left, right, changeset); |
50 | } | 50 | } |
51 | eprintln!($($tt)*); | 51 | std::eprintln!($($tt)*); |
52 | panic!("text differs"); | 52 | panic!("text differs"); |
53 | } | 53 | } |
54 | }}; | 54 | }}; |
diff --git a/docs/dev/debugging.md b/docs/dev/debugging.md index 59a83f7d7..8c48fd5a1 100644 --- a/docs/dev/debugging.md +++ b/docs/dev/debugging.md | |||
@@ -53,7 +53,7 @@ To apply changes to an already running debug process, press <kbd>Ctrl+Shift+P</k | |||
53 | 53 | ||
54 | - A list of running processes should appear. Select the `rust-analyzer` from this repo. | 54 | - A list of running processes should appear. Select the `rust-analyzer` from this repo. |
55 | 55 | ||
56 | - Navigate to `crates/rust-analyzer/src/main_loop.rs` and add a breakpoint to the `on_task` function. | 56 | - Navigate to `crates/rust-analyzer/src/main_loop.rs` and add a breakpoint to the `on_request` function. |
57 | 57 | ||
58 | - Go back to the `[Extension Development Host]` instance and hover over a Rust variable and your breakpoint should hit. | 58 | - Go back to the `[Extension Development Host]` instance and hover over a Rust variable and your breakpoint should hit. |
59 | 59 | ||
diff --git a/docs/user/generated_diagnostic.adoc b/docs/user/generated_diagnostic.adoc new file mode 100644 index 000000000..34c4f98a3 --- /dev/null +++ b/docs/user/generated_diagnostic.adoc | |||
@@ -0,0 +1,105 @@ | |||
1 | //Generated file, do not edit by hand, see `xtask/src/codegen` | ||
2 | === break-outside-of-loop | ||
3 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L219[diagnostics.rs] | ||
4 | |||
5 | This diagnostic is triggered if `break` keyword is used outside of a loop. | ||
6 | |||
7 | |||
8 | === inactive-code | ||
9 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_def/src/diagnostics.rs#L98[diagnostics.rs] | ||
10 | |||
11 | This diagnostic is shown for code with inactive `#[cfg]` attributes. | ||
12 | |||
13 | |||
14 | === incorrect-ident-case | ||
15 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L319[diagnostics.rs] | ||
16 | |||
17 | This diagnostic is triggered if item name doesn't follow https://doc.rust-lang.org/1.0.0/style/style/naming/README.html[Rust naming convention]. | ||
18 | |||
19 | |||
20 | === mismatched-arg-count | ||
21 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L267[diagnostics.rs] | ||
22 | |||
23 | This diagnostic is triggered if function is invoked with an incorrect amount of arguments. | ||
24 | |||
25 | |||
26 | === missing-match-arm | ||
27 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L162[diagnostics.rs] | ||
28 | |||
29 | This diagnostic is triggered if `match` block is missing one or more match arms. | ||
30 | |||
31 | |||
32 | === missing-ok-in-tail-expr | ||
33 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L187[diagnostics.rs] | ||
34 | |||
35 | This diagnostic is triggered if block that should return `Result` returns a value not wrapped in `Ok`. | ||
36 | |||
37 | Example: | ||
38 | |||
39 | ```rust | ||
40 | fn foo() -> Result<u8, ()> { | ||
41 | 10 | ||
42 | } | ||
43 | ``` | ||
44 | |||
45 | |||
46 | === missing-pat-fields | ||
47 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L113[diagnostics.rs] | ||
48 | |||
49 | This diagnostic is triggered if pattern lacks some fields that exist in the corresponding structure. | ||
50 | |||
51 | Example: | ||
52 | |||
53 | ```rust | ||
54 | struct A { a: u8, b: u8 } | ||
55 | |||
56 | let a = A { a: 10, b: 20 }; | ||
57 | |||
58 | if let A { a } = a { | ||
59 | // ... | ||
60 | } | ||
61 | ``` | ||
62 | |||
63 | |||
64 | === missing-structure-fields | ||
65 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L66[diagnostics.rs] | ||
66 | |||
67 | This diagnostic is triggered if record lacks some fields that exist in the corresponding structure. | ||
68 | |||
69 | Example: | ||
70 | |||
71 | ```rust | ||
72 | struct A { a: u8, b: u8 } | ||
73 | |||
74 | let a = A { a: 10 }; | ||
75 | ``` | ||
76 | |||
77 | |||
78 | === missing-unsafe | ||
79 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L243[diagnostics.rs] | ||
80 | |||
81 | This diagnostic is triggered if operation marked as `unsafe` is used outside of `unsafe` function or block. | ||
82 | |||
83 | |||
84 | === no-such-field | ||
85 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_ty/src/diagnostics.rs#L39[diagnostics.rs] | ||
86 | |||
87 | This diagnostic is triggered if created structure does not have field provided in record. | ||
88 | |||
89 | |||
90 | === unresolved-extern-crate | ||
91 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_def/src/diagnostics.rs#L43[diagnostics.rs] | ||
92 | |||
93 | This diagnostic is triggered if rust-analyzer is unable to discover referred extern crate. | ||
94 | |||
95 | |||
96 | === unresolved-import | ||
97 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_def/src/diagnostics.rs#L67[diagnostics.rs] | ||
98 | |||
99 | This diagnostic is triggered if rust-analyzer is unable to discover imported module. | ||
100 | |||
101 | |||
102 | === unresolved-module | ||
103 | **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/hir_def/src/diagnostics.rs#L18[diagnostics.rs] | ||
104 | |||
105 | This diagnostic is triggered if rust-analyzer is unable to discover referred module. | ||
diff --git a/docs/user/manual.adoc b/docs/user/manual.adoc index 8a3cc00df..b9d907a4a 100644 --- a/docs/user/manual.adoc +++ b/docs/user/manual.adoc | |||
@@ -116,6 +116,7 @@ Here are some useful self-diagnostic commands: | |||
116 | * **Rust Analyzer: Show RA Version** shows the version of `rust-analyzer` binary. | 116 | * **Rust Analyzer: Show RA Version** shows the version of `rust-analyzer` binary. |
117 | * **Rust Analyzer: Status** prints some statistics about the server, and dependency information for the current file. | 117 | * **Rust Analyzer: Status** prints some statistics about the server, and dependency information for the current file. |
118 | * To enable server-side logging, run with `env RA_LOG=info` and see `Output > Rust Analyzer Language Server` in VS Code's panel. | 118 | * To enable server-side logging, run with `env RA_LOG=info` and see `Output > Rust Analyzer Language Server` in VS Code's panel. |
119 | * To log project loading (sysroot & `cargo metadata`), set `RA_LOG=project_model=debug`. | ||
119 | * To log all LSP requests, add `"rust-analyzer.trace.server": "verbose"` to the settings and look for `Rust Analyzer Language Server Trace` in the panel. | 120 | * To log all LSP requests, add `"rust-analyzer.trace.server": "verbose"` to the settings and look for `Rust Analyzer Language Server Trace` in the panel. |
120 | * To enable client-side logging, add `"rust-analyzer.trace.extension": true` to the settings and open `Output > Rust Analyzer Client` in the panel. | 121 | * To enable client-side logging, add `"rust-analyzer.trace.extension": true` to the settings and open `Output > Rust Analyzer Client` in the panel. |
121 | 122 | ||
@@ -286,6 +287,9 @@ interface JsonProject { | |||
286 | } | 287 | } |
287 | 288 | ||
288 | interface Crate { | 289 | interface Crate { |
290 | /// Optional crate name used for display purposes, without affecting semantics. | ||
291 | /// See the `deps` key for semantically-significant crate names. | ||
292 | display_name?: string; | ||
289 | /// Path to the root module of the crate. | 293 | /// Path to the root module of the crate. |
290 | root_module: string; | 294 | root_module: string; |
291 | /// Edition of the crate. | 295 | /// Edition of the crate. |
@@ -362,6 +366,13 @@ Cursor position or selection is signified by `┃` character. | |||
362 | 366 | ||
363 | include::./generated_assists.adoc[] | 367 | include::./generated_assists.adoc[] |
364 | 368 | ||
369 | == Diagnostics | ||
370 | |||
371 | While most errors and warnings provided by rust-analyzer come from the `cargo check` integration, there's a growing number of diagnostics implemented using rust-analyzer's own analysis. | ||
372 | These diagnostics don't respect `#[allow]` or `#[deny]` attributes yet, but can be turned off using the `rust-analyzer.diagnostics.enable`, `rust-analyzer.diagnostics.enableExperimental` or `rust-analyzer.diagnostics.disabled` settings. | ||
373 | |||
374 | include::./generated_diagnostic.adoc[] | ||
375 | |||
365 | == Editor Features | 376 | == Editor Features |
366 | === VS Code | 377 | === VS Code |
367 | 378 | ||
diff --git a/editors/code/package-lock.json b/editors/code/package-lock.json index 33d60d4dd..83ef00058 100644 --- a/editors/code/package-lock.json +++ b/editors/code/package-lock.json | |||
@@ -2409,32 +2409,32 @@ | |||
2409 | } | 2409 | } |
2410 | }, | 2410 | }, |
2411 | "vscode-jsonrpc": { | 2411 | "vscode-jsonrpc": { |
2412 | "version": "6.0.0-next.5", | 2412 | "version": "6.0.0-next.7", |
2413 | "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-6.0.0-next.5.tgz", | 2413 | "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-6.0.0-next.7.tgz", |
2414 | "integrity": "sha512-IAgsltQPwg/pXOPsdXgbUTCaO9VSKZwirZN5SGtkdYQ/R3VjeC4v00WTVvoNayWMZpoC3O9u0ogqmsKzKhVasQ==" | 2414 | "integrity": "sha512-1nG+6cuTtpzmXe7yYfO9GCkYlyV6Ai+jDnwidHiT2T7zhc+bJM+VTtc0T/CdTlDyTNTqIcCj0V1nD4TcVjJ7Ug==" |
2415 | }, | 2415 | }, |
2416 | "vscode-languageclient": { | 2416 | "vscode-languageclient": { |
2417 | "version": "7.0.0-next.9", | 2417 | "version": "7.0.0-next.12", |
2418 | "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-7.0.0-next.9.tgz", | 2418 | "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-7.0.0-next.12.tgz", |
2419 | "integrity": "sha512-lFO+rN/i72CM2va6iKXq1lD7pJg8J93KEXf0w0boWVqU+DJhWzLrV3pXl8Xk1nCv//qOAyhlc/nx2KZCTeRF/A==", | 2419 | "integrity": "sha512-OrzvOvhS5o26C0KctTJC7hkwh3avCwkVhllzy42AqwpIUZ3p2aVqkSG2uVxaeodq8ThBb3TLgtg50vxyWs6FEg==", |
2420 | "requires": { | 2420 | "requires": { |
2421 | "semver": "^6.3.0", | 2421 | "semver": "^6.3.0", |
2422 | "vscode-languageserver-protocol": "3.16.0-next.7" | 2422 | "vscode-languageserver-protocol": "3.16.0-next.10" |
2423 | } | 2423 | } |
2424 | }, | 2424 | }, |
2425 | "vscode-languageserver-protocol": { | 2425 | "vscode-languageserver-protocol": { |
2426 | "version": "3.16.0-next.7", | 2426 | "version": "3.16.0-next.10", |
2427 | "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.16.0-next.7.tgz", | 2427 | "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.16.0-next.10.tgz", |
2428 | "integrity": "sha512-tOjrg+K3RddJ547zpC9/LAgTbzadkPuHlqJFFWIcKjVhiJOh73XyY+Ngcu9wukGaTsuSGjJ0W8rlmwanixa0FQ==", | 2428 | "integrity": "sha512-YRTctHUZvts0Z1xXKNYU0ha0o+Tlgtwr+6O8OmDquM086N8exiSKBMwMC+Ra1QtIE+1mfW43Wxsme2FnMkAS9A==", |
2429 | "requires": { | 2429 | "requires": { |
2430 | "vscode-jsonrpc": "6.0.0-next.5", | 2430 | "vscode-jsonrpc": "6.0.0-next.7", |
2431 | "vscode-languageserver-types": "3.16.0-next.3" | 2431 | "vscode-languageserver-types": "3.16.0-next.4" |
2432 | } | 2432 | } |
2433 | }, | 2433 | }, |
2434 | "vscode-languageserver-types": { | 2434 | "vscode-languageserver-types": { |
2435 | "version": "3.16.0-next.3", | 2435 | "version": "3.16.0-next.4", |
2436 | "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.16.0-next.3.tgz", | 2436 | "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.16.0-next.4.tgz", |
2437 | "integrity": "sha512-s/z5ZqSe7VpoXJ6JQcvwRiPPA3nG0nAcJ/HH03zoU6QaFfnkcgPK+HshC3WKPPnC2G08xA0iRB6h7kmyBB5Adg==" | 2437 | "integrity": "sha512-NlKJyGcET/ZBCCLBYIPaGo2c37R03bPYeWXozUtnjyye7+9dhlbMSODyoG2INcQf8zFmB4qhm2UOJjgYEgPCNA==" |
2438 | }, | 2438 | }, |
2439 | "vscode-test": { | 2439 | "vscode-test": { |
2440 | "version": "1.4.0", | 2440 | "version": "1.4.0", |
diff --git a/editors/code/package.json b/editors/code/package.json index 4bd3117fc..eccafccdd 100644 --- a/editors/code/package.json +++ b/editors/code/package.json | |||
@@ -36,7 +36,7 @@ | |||
36 | }, | 36 | }, |
37 | "dependencies": { | 37 | "dependencies": { |
38 | "node-fetch": "^2.6.1", | 38 | "node-fetch": "^2.6.1", |
39 | "vscode-languageclient": "7.0.0-next.9" | 39 | "vscode-languageclient": "7.0.0-next.12" |
40 | }, | 40 | }, |
41 | "devDependencies": { | 41 | "devDependencies": { |
42 | "@rollup/plugin-commonjs": "^13.0.2", | 42 | "@rollup/plugin-commonjs": "^13.0.2", |
@@ -929,6 +929,10 @@ | |||
929 | { | 929 | { |
930 | "id": "consuming", | 930 | "id": "consuming", |
931 | "description": "Style for non-Copy lvalues consumed by method/function call" | 931 | "description": "Style for non-Copy lvalues consumed by method/function call" |
932 | }, | ||
933 | { | ||
934 | "id": "callable", | ||
935 | "description": "Style for variables/parameters that can be used in call expressions" | ||
932 | } | 936 | } |
933 | ], | 937 | ], |
934 | "semanticTokenScopes": [ | 938 | "semanticTokenScopes": [ |
diff --git a/editors/code/rust.tmGrammar.json b/editors/code/rust.tmGrammar.json index 3ddd14f9c..1b8cc713a 100644 --- a/editors/code/rust.tmGrammar.json +++ b/editors/code/rust.tmGrammar.json | |||
@@ -25,6 +25,9 @@ | |||
25 | }, | 25 | }, |
26 | "patterns": [ | 26 | "patterns": [ |
27 | { | 27 | { |
28 | "include": "#block-comments" | ||
29 | }, | ||
30 | { | ||
28 | "include": "#comments" | 31 | "include": "#comments" |
29 | }, | 32 | }, |
30 | { | 33 | { |
@@ -155,7 +158,7 @@ | |||
155 | }, | 158 | }, |
156 | { | 159 | { |
157 | "comment": "modules", | 160 | "comment": "modules", |
158 | "match": "(mod)\\s+([a-z][A-Za-z0-9_]*)", | 161 | "match": "(mod)\\s+((?:r#(?!crate|[Ss]elf|super))?[a-z][A-Za-z0-9_]*)", |
159 | "captures": { | 162 | "captures": { |
160 | "1": { | 163 | "1": { |
161 | "name": "keyword.control.rust" | 164 | "name": "keyword.control.rust" |
@@ -185,6 +188,9 @@ | |||
185 | }, | 188 | }, |
186 | "patterns": [ | 189 | "patterns": [ |
187 | { | 190 | { |
191 | "include": "#block-comments" | ||
192 | }, | ||
193 | { | ||
188 | "include": "#comments" | 194 | "include": "#comments" |
189 | }, | 195 | }, |
190 | { | 196 | { |
@@ -212,6 +218,9 @@ | |||
212 | }, | 218 | }, |
213 | "patterns": [ | 219 | "patterns": [ |
214 | { | 220 | { |
221 | "include": "#block-comments" | ||
222 | }, | ||
223 | { | ||
215 | "include": "#comments" | 224 | "include": "#comments" |
216 | }, | 225 | }, |
217 | { | 226 | { |
@@ -232,6 +241,9 @@ | |||
232 | ] | 241 | ] |
233 | }, | 242 | }, |
234 | { | 243 | { |
244 | "include": "#block-comments" | ||
245 | }, | ||
246 | { | ||
235 | "include": "#comments" | 247 | "include": "#comments" |
236 | }, | 248 | }, |
237 | { | 249 | { |
@@ -277,23 +289,17 @@ | |||
277 | { | 289 | { |
278 | "comment": "documentation comments", | 290 | "comment": "documentation comments", |
279 | "name": "comment.line.documentation.rust", | 291 | "name": "comment.line.documentation.rust", |
280 | "match": "^\\s*///.*", | 292 | "match": "^\\s*///.*" |
281 | "patterns": [ | ||
282 | { | ||
283 | "include": "#comments" | ||
284 | } | ||
285 | ] | ||
286 | }, | 293 | }, |
287 | { | 294 | { |
288 | "comment": "line comments", | 295 | "comment": "line comments", |
289 | "name": "comment.line.double-slash.rust", | 296 | "name": "comment.line.double-slash.rust", |
290 | "match": "\\s*//.*", | 297 | "match": "\\s*//.*" |
291 | "patterns": [ | 298 | } |
292 | { | 299 | ] |
293 | "include": "#comments" | 300 | }, |
294 | } | 301 | "block-comments": { |
295 | ] | 302 | "patterns": [ |
296 | }, | ||
297 | { | 303 | { |
298 | "comment": "block comments", | 304 | "comment": "block comments", |
299 | "name": "comment.block.rust", | 305 | "name": "comment.block.rust", |
@@ -301,7 +307,7 @@ | |||
301 | "end": "\\*/", | 307 | "end": "\\*/", |
302 | "patterns": [ | 308 | "patterns": [ |
303 | { | 309 | { |
304 | "include": "#comments" | 310 | "include": "#block-comments" |
305 | } | 311 | } |
306 | ] | 312 | ] |
307 | }, | 313 | }, |
@@ -312,14 +318,9 @@ | |||
312 | "end": "\\*/", | 318 | "end": "\\*/", |
313 | "patterns": [ | 319 | "patterns": [ |
314 | { | 320 | { |
315 | "include": "#comments" | 321 | "include": "#block-comments" |
316 | } | 322 | } |
317 | ] | 323 | ] |
318 | }, | ||
319 | { | ||
320 | "comment": "inferred types, wildcard patterns, ignored params", | ||
321 | "name": "comment.char.underscore.rust", | ||
322 | "match": "\\b_\\w*\\b" | ||
323 | } | 324 | } |
324 | ] | 325 | ] |
325 | }, | 326 | }, |
@@ -426,9 +427,21 @@ | |||
426 | "functions": { | 427 | "functions": { |
427 | "patterns": [ | 428 | "patterns": [ |
428 | { | 429 | { |
430 | "comment": "pub as a function", | ||
431 | "match": "\\b(pub)(\\()", | ||
432 | "captures": { | ||
433 | "1": { | ||
434 | "name": "keyword.other.rust" | ||
435 | }, | ||
436 | "2": { | ||
437 | "name": "punctuation.brackets.round.rust" | ||
438 | } | ||
439 | } | ||
440 | }, | ||
441 | { | ||
429 | "comment": "function definition", | 442 | "comment": "function definition", |
430 | "name": "meta.function.definition.rust", | 443 | "name": "meta.function.definition.rust", |
431 | "begin": "\\b(fn)\\s+([A-Za-z0-9_]+)((\\()|(<))", | 444 | "begin": "\\b(fn)\\s+((?:r#(?!crate|[Ss]elf|super))?[A-Za-z0-9_]+)((\\()|(<))", |
432 | "beginCaptures": { | 445 | "beginCaptures": { |
433 | "1": { | 446 | "1": { |
434 | "name": "keyword.control.fn.rust" | 447 | "name": "keyword.control.fn.rust" |
@@ -451,6 +464,9 @@ | |||
451 | }, | 464 | }, |
452 | "patterns": [ | 465 | "patterns": [ |
453 | { | 466 | { |
467 | "include": "#block-comments" | ||
468 | }, | ||
469 | { | ||
454 | "include": "#comments" | 470 | "include": "#comments" |
455 | }, | 471 | }, |
456 | { | 472 | { |
@@ -494,18 +510,12 @@ | |||
494 | { | 510 | { |
495 | "comment": "function/method calls, chaining", | 511 | "comment": "function/method calls, chaining", |
496 | "name": "meta.function.call.rust", | 512 | "name": "meta.function.call.rust", |
497 | "begin": "(?:(pub)|(?:(\\.)?([A-Za-z0-9_]+)))(\\()", | 513 | "begin": "((?:r#(?!crate|[Ss]elf|super))?[A-Za-z0-9_]+)(\\()", |
498 | "beginCaptures": { | 514 | "beginCaptures": { |
499 | "1": { | 515 | "1": { |
500 | "name": "keyword.other.rust" | ||
501 | }, | ||
502 | "2": { | ||
503 | "name": "keyword.operator.access.dot.rust" | ||
504 | }, | ||
505 | "3": { | ||
506 | "name": "entity.name.function.rust" | 516 | "name": "entity.name.function.rust" |
507 | }, | 517 | }, |
508 | "4": { | 518 | "2": { |
509 | "name": "punctuation.brackets.round.rust" | 519 | "name": "punctuation.brackets.round.rust" |
510 | } | 520 | } |
511 | }, | 521 | }, |
@@ -517,6 +527,9 @@ | |||
517 | }, | 527 | }, |
518 | "patterns": [ | 528 | "patterns": [ |
519 | { | 529 | { |
530 | "include": "#block-comments" | ||
531 | }, | ||
532 | { | ||
520 | "include": "#comments" | 533 | "include": "#comments" |
521 | }, | 534 | }, |
522 | { | 535 | { |
@@ -628,10 +641,28 @@ | |||
628 | }, | 641 | }, |
629 | { | 642 | { |
630 | "comment": "less than, greater than (special case)", | 643 | "comment": "less than, greater than (special case)", |
631 | "match": "(^|\\s)(?<!=)([<>])\\s", | 644 | "match": "(?:\\b|(?:(\\))|(\\])|(\\})))[ \\t]+([<>])[ \\t]+(?:\\b|(?:(\\()|(\\[)|(\\{)))", |
632 | "captures": { | 645 | "captures": { |
646 | "1": { | ||
647 | "name": "punctuation.brackets.round.rust" | ||
648 | }, | ||
633 | "2": { | 649 | "2": { |
650 | "name": "punctuation.brackets.square.rust" | ||
651 | }, | ||
652 | "3": { | ||
653 | "name": "punctuation.brackets.curly.rust" | ||
654 | }, | ||
655 | "4": { | ||
634 | "name": "keyword.operator.comparison.rust" | 656 | "name": "keyword.operator.comparison.rust" |
657 | }, | ||
658 | "5": { | ||
659 | "name": "punctuation.brackets.round.rust" | ||
660 | }, | ||
661 | "6": { | ||
662 | "name": "punctuation.brackets.square.rust" | ||
663 | }, | ||
664 | "7": { | ||
665 | "name": "punctuation.brackets.curly.rust" | ||
635 | } | 666 | } |
636 | } | 667 | } |
637 | }, | 668 | }, |
@@ -694,23 +725,15 @@ | |||
694 | "interpolations": { | 725 | "interpolations": { |
695 | "comment": "curly brace interpolations", | 726 | "comment": "curly brace interpolations", |
696 | "name": "meta.interpolation.rust", | 727 | "name": "meta.interpolation.rust", |
697 | "begin": "{", | 728 | "match": "({)[^\"{}]*(})", |
698 | "beginCaptures": { | 729 | "captures": { |
699 | "0": { | 730 | "1": { |
700 | "name": "punctuation.definition.interpolation.rust" | 731 | "name": "punctuation.definition.interpolation.rust" |
701 | } | 732 | }, |
702 | }, | 733 | "2": { |
703 | "end": "}", | ||
704 | "endCaptures": { | ||
705 | "0": { | ||
706 | "name": "punctuation.definition.interpolation.rust" | 734 | "name": "punctuation.definition.interpolation.rust" |
707 | } | 735 | } |
708 | }, | 736 | } |
709 | "patterns": [ | ||
710 | { | ||
711 | "include": "#interpolations" | ||
712 | } | ||
713 | ] | ||
714 | }, | 737 | }, |
715 | "lifetimes": { | 738 | "lifetimes": { |
716 | "patterns": [ | 739 | "patterns": [ |
@@ -806,6 +829,9 @@ | |||
806 | }, | 829 | }, |
807 | "patterns": [ | 830 | "patterns": [ |
808 | { | 831 | { |
832 | "include": "#block-comments" | ||
833 | }, | ||
834 | { | ||
809 | "include": "#comments" | 835 | "include": "#comments" |
810 | }, | 836 | }, |
811 | { | 837 | { |
@@ -980,7 +1006,7 @@ | |||
980 | "name": "punctuation.definition.string.rust" | 1006 | "name": "punctuation.definition.string.rust" |
981 | } | 1007 | } |
982 | }, | 1008 | }, |
983 | "end": "(\")(#*)", | 1009 | "end": "(\")(\\2)", |
984 | "endCaptures": { | 1010 | "endCaptures": { |
985 | "1": { | 1011 | "1": { |
986 | "name": "punctuation.definition.string.rust" | 1012 | "name": "punctuation.definition.string.rust" |
@@ -1035,7 +1061,7 @@ | |||
1035 | { | 1061 | { |
1036 | "comment": "variables", | 1062 | "comment": "variables", |
1037 | "name": "variable.other.rust", | 1063 | "name": "variable.other.rust", |
1038 | "match": "\\b(?<!\\.)[a-z0-9_]+\\b" | 1064 | "match": "\\b(?<!\\.)(?:r#(?!(crate|[Ss]elf|super)))?[a-z0-9_]+\\b" |
1039 | } | 1065 | } |
1040 | ] | 1066 | ] |
1041 | } | 1067 | } |
diff --git a/editors/code/src/run.ts b/editors/code/src/run.ts index 459b7f250..17573cd82 100644 --- a/editors/code/src/run.ts +++ b/editors/code/src/run.ts | |||
@@ -129,7 +129,9 @@ export async function createTask(runnable: ra.Runnable, config: Config): Promise | |||
129 | } | 129 | } |
130 | 130 | ||
131 | const args = [...runnable.args.cargoArgs]; // should be a copy! | 131 | const args = [...runnable.args.cargoArgs]; // should be a copy! |
132 | args.push(...runnable.args.cargoExtraArgs); // Append user-specified cargo options. | 132 | if (runnable.args.cargoExtraArgs) { |
133 | args.push(...runnable.args.cargoExtraArgs); // Append user-specified cargo options. | ||
134 | } | ||
133 | if (runnable.args.executableArgs.length > 0) { | 135 | if (runnable.args.executableArgs.length > 0) { |
134 | args.push('--', ...runnable.args.executableArgs); | 136 | args.push('--', ...runnable.args.executableArgs); |
135 | } | 137 | } |
diff --git a/editors/code/src/util.ts b/editors/code/src/util.ts index 08159b43c..53492a445 100644 --- a/editors/code/src/util.ts +++ b/editors/code/src/util.ts | |||
@@ -75,12 +75,11 @@ export async function sendRequestWithRetry<TParam, TRet>( | |||
75 | log.warn("LSP request timed out", { method: reqType.method, param, error }); | 75 | log.warn("LSP request timed out", { method: reqType.method, param, error }); |
76 | throw error; | 76 | throw error; |
77 | } | 77 | } |
78 | 78 | if (error.code === lc.LSPErrorCodes.RequestCancelled) { | |
79 | if (error.code === lc.ErrorCodes.RequestCancelled) { | ||
80 | throw error; | 79 | throw error; |
81 | } | 80 | } |
82 | 81 | ||
83 | if (error.code !== lc.ErrorCodes.ContentModified) { | 82 | if (error.code !== lc.LSPErrorCodes.ContentModified) { |
84 | log.warn("LSP request failed", { method: reqType.method, param, error }); | 83 | log.warn("LSP request failed", { method: reqType.method, param, error }); |
85 | throw error; | 84 | throw error; |
86 | } | 85 | } |
diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 01a838825..2ef956485 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml | |||
@@ -18,5 +18,5 @@ quote = "1.0.2" | |||
18 | ungrammar = "1.1.3" | 18 | ungrammar = "1.1.3" |
19 | walkdir = "2.3.1" | 19 | walkdir = "2.3.1" |
20 | write-json = "0.1.0" | 20 | write-json = "0.1.0" |
21 | fs-err = "2.3" | 21 | xshell = "0.1" |
22 | # Avoid adding more dependencies to this crate | 22 | # Avoid adding more dependencies to this crate |
diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs index 1e7894617..adea053b6 100644 --- a/xtask/src/codegen.rs +++ b/xtask/src/codegen.rs | |||
@@ -9,23 +9,22 @@ mod gen_syntax; | |||
9 | mod gen_parser_tests; | 9 | mod gen_parser_tests; |
10 | mod gen_assists_docs; | 10 | mod gen_assists_docs; |
11 | mod gen_feature_docs; | 11 | mod gen_feature_docs; |
12 | mod gen_features; | 12 | mod gen_lint_completions; |
13 | mod gen_diagnostic_docs; | ||
13 | 14 | ||
14 | use std::{ | 15 | use std::{ |
15 | fmt, mem, | 16 | fmt, mem, |
16 | path::{Path, PathBuf}, | 17 | path::{Path, PathBuf}, |
17 | }; | 18 | }; |
19 | use xshell::{cmd, pushenv, read_file, write_file}; | ||
18 | 20 | ||
19 | use crate::{ | 21 | use crate::{ensure_rustfmt, project_root, Result}; |
20 | ensure_rustfmt, | ||
21 | not_bash::{fs2, pushenv, run}, | ||
22 | project_root, Result, | ||
23 | }; | ||
24 | 22 | ||
25 | pub use self::{ | 23 | pub use self::{ |
26 | gen_assists_docs::{generate_assists_docs, generate_assists_tests}, | 24 | gen_assists_docs::{generate_assists_docs, generate_assists_tests}, |
25 | gen_diagnostic_docs::generate_diagnostic_docs, | ||
27 | gen_feature_docs::generate_feature_docs, | 26 | gen_feature_docs::generate_feature_docs, |
28 | gen_features::generate_features, | 27 | gen_lint_completions::generate_lint_completions, |
29 | gen_parser_tests::generate_parser_tests, | 28 | gen_parser_tests::generate_parser_tests, |
30 | gen_syntax::generate_syntax, | 29 | gen_syntax::generate_syntax, |
31 | }; | 30 | }; |
@@ -43,13 +42,14 @@ pub struct CodegenCmd { | |||
43 | impl CodegenCmd { | 42 | impl CodegenCmd { |
44 | pub fn run(self) -> Result<()> { | 43 | pub fn run(self) -> Result<()> { |
45 | if self.features { | 44 | if self.features { |
46 | generate_features(Mode::Overwrite)?; | 45 | generate_lint_completions(Mode::Overwrite)?; |
47 | } | 46 | } |
48 | generate_syntax(Mode::Overwrite)?; | 47 | generate_syntax(Mode::Overwrite)?; |
49 | generate_parser_tests(Mode::Overwrite)?; | 48 | generate_parser_tests(Mode::Overwrite)?; |
50 | generate_assists_tests(Mode::Overwrite)?; | 49 | generate_assists_tests(Mode::Overwrite)?; |
51 | generate_assists_docs(Mode::Overwrite)?; | 50 | generate_assists_docs(Mode::Overwrite)?; |
52 | generate_feature_docs(Mode::Overwrite)?; | 51 | generate_feature_docs(Mode::Overwrite)?; |
52 | generate_diagnostic_docs(Mode::Overwrite)?; | ||
53 | Ok(()) | 53 | Ok(()) |
54 | } | 54 | } |
55 | } | 55 | } |
@@ -57,7 +57,7 @@ impl CodegenCmd { | |||
57 | /// A helper to update file on disk if it has changed. | 57 | /// A helper to update file on disk if it has changed. |
58 | /// With verify = false, | 58 | /// With verify = false, |
59 | fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { | 59 | fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { |
60 | match fs2::read_to_string(path) { | 60 | match read_file(path) { |
61 | Ok(old_contents) if normalize(&old_contents) == normalize(contents) => { | 61 | Ok(old_contents) if normalize(&old_contents) == normalize(contents) => { |
62 | return Ok(()); | 62 | return Ok(()); |
63 | } | 63 | } |
@@ -67,7 +67,7 @@ fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { | |||
67 | anyhow::bail!("`{}` is not up-to-date", path.display()); | 67 | anyhow::bail!("`{}` is not up-to-date", path.display()); |
68 | } | 68 | } |
69 | eprintln!("updating {}", path.display()); | 69 | eprintln!("updating {}", path.display()); |
70 | fs2::write(path, contents)?; | 70 | write_file(path, contents)?; |
71 | return Ok(()); | 71 | return Ok(()); |
72 | 72 | ||
73 | fn normalize(s: &str) -> String { | 73 | fn normalize(s: &str) -> String { |
@@ -80,10 +80,10 @@ const PREAMBLE: &str = "Generated file, do not edit by hand, see `xtask/src/code | |||
80 | fn reformat(text: &str) -> Result<String> { | 80 | fn reformat(text: &str) -> Result<String> { |
81 | let _e = pushenv("RUSTUP_TOOLCHAIN", "stable"); | 81 | let _e = pushenv("RUSTUP_TOOLCHAIN", "stable"); |
82 | ensure_rustfmt()?; | 82 | ensure_rustfmt()?; |
83 | let stdout = run!( | 83 | let rustfmt_toml = project_root().join("rustfmt.toml"); |
84 | "rustfmt --config-path {} --config fn_single_line=true", project_root().join("rustfmt.toml").display(); | 84 | let stdout = cmd!("rustfmt --config-path {rustfmt_toml} --config fn_single_line=true") |
85 | <text.as_bytes() | 85 | .stdin(text) |
86 | )?; | 86 | .read()?; |
87 | Ok(format!("//! {}\n\n{}\n", PREAMBLE, stdout)) | 87 | Ok(format!("//! {}\n\n{}\n", PREAMBLE, stdout)) |
88 | } | 88 | } |
89 | 89 | ||
diff --git a/xtask/src/codegen/gen_assists_docs.rs b/xtask/src/codegen/gen_assists_docs.rs index ff307e2aa..d7c85ebe9 100644 --- a/xtask/src/codegen/gen_assists_docs.rs +++ b/xtask/src/codegen/gen_assists_docs.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | //! Generates `assists.md` documentation. | 1 | //! Generates `assists.md` documentation. |
2 | 2 | ||
3 | use std::{fmt, fs, path::Path}; | 3 | use std::{fmt, path::Path}; |
4 | 4 | ||
5 | use crate::{ | 5 | use crate::{ |
6 | codegen::{self, extract_comment_blocks_with_empty_lines, reformat, Location, Mode, PREAMBLE}, | 6 | codegen::{self, extract_comment_blocks_with_empty_lines, reformat, Location, Mode, PREAMBLE}, |
@@ -39,7 +39,7 @@ impl Assist { | |||
39 | return Ok(res); | 39 | return Ok(res); |
40 | 40 | ||
41 | fn collect_file(acc: &mut Vec<Assist>, path: &Path) -> Result<()> { | 41 | fn collect_file(acc: &mut Vec<Assist>, path: &Path) -> Result<()> { |
42 | let text = fs::read_to_string(path)?; | 42 | let text = xshell::read_file(path)?; |
43 | let comment_blocks = extract_comment_blocks_with_empty_lines("Assist", &text); | 43 | let comment_blocks = extract_comment_blocks_with_empty_lines("Assist", &text); |
44 | 44 | ||
45 | for block in comment_blocks { | 45 | for block in comment_blocks { |
diff --git a/xtask/src/codegen/gen_diagnostic_docs.rs b/xtask/src/codegen/gen_diagnostic_docs.rs new file mode 100644 index 000000000..00aaea5b7 --- /dev/null +++ b/xtask/src/codegen/gen_diagnostic_docs.rs | |||
@@ -0,0 +1,74 @@ | |||
1 | //! Generates `assists.md` documentation. | ||
2 | |||
3 | use std::{fmt, path::PathBuf}; | ||
4 | |||
5 | use crate::{ | ||
6 | codegen::{self, extract_comment_blocks_with_empty_lines, Location, Mode, PREAMBLE}, | ||
7 | project_root, rust_files, Result, | ||
8 | }; | ||
9 | |||
10 | pub fn generate_diagnostic_docs(mode: Mode) -> Result<()> { | ||
11 | let diagnostics = Diagnostic::collect()?; | ||
12 | let contents = | ||
13 | diagnostics.into_iter().map(|it| it.to_string()).collect::<Vec<_>>().join("\n\n"); | ||
14 | let contents = format!("//{}\n{}\n", PREAMBLE, contents.trim()); | ||
15 | let dst = project_root().join("docs/user/generated_diagnostic.adoc"); | ||
16 | codegen::update(&dst, &contents, mode)?; | ||
17 | Ok(()) | ||
18 | } | ||
19 | |||
20 | #[derive(Debug)] | ||
21 | struct Diagnostic { | ||
22 | id: String, | ||
23 | location: Location, | ||
24 | doc: String, | ||
25 | } | ||
26 | |||
27 | impl Diagnostic { | ||
28 | fn collect() -> Result<Vec<Diagnostic>> { | ||
29 | let mut res = Vec::new(); | ||
30 | for path in rust_files(&project_root()) { | ||
31 | collect_file(&mut res, path)?; | ||
32 | } | ||
33 | res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id)); | ||
34 | return Ok(res); | ||
35 | |||
36 | fn collect_file(acc: &mut Vec<Diagnostic>, path: PathBuf) -> Result<()> { | ||
37 | let text = xshell::read_file(&path)?; | ||
38 | let comment_blocks = extract_comment_blocks_with_empty_lines("Diagnostic", &text); | ||
39 | |||
40 | for block in comment_blocks { | ||
41 | let id = block.id; | ||
42 | if let Err(msg) = is_valid_diagnostic_name(&id) { | ||
43 | panic!("invalid diagnostic name: {:?}:\n {}", id, msg) | ||
44 | } | ||
45 | let doc = block.contents.join("\n"); | ||
46 | let location = Location::new(path.clone(), block.line); | ||
47 | acc.push(Diagnostic { id, location, doc }) | ||
48 | } | ||
49 | |||
50 | Ok(()) | ||
51 | } | ||
52 | } | ||
53 | } | ||
54 | |||
55 | fn is_valid_diagnostic_name(diagnostic: &str) -> Result<(), String> { | ||
56 | let diagnostic = diagnostic.trim(); | ||
57 | if diagnostic.find(char::is_whitespace).is_some() { | ||
58 | return Err("Diagnostic names can't contain whitespace symbols".into()); | ||
59 | } | ||
60 | if diagnostic.chars().any(|c| c.is_ascii_uppercase()) { | ||
61 | return Err("Diagnostic names can't contain uppercase symbols".into()); | ||
62 | } | ||
63 | if diagnostic.chars().any(|c| !c.is_ascii()) { | ||
64 | return Err("Diagnostic can't contain non-ASCII symbols".into()); | ||
65 | } | ||
66 | |||
67 | Ok(()) | ||
68 | } | ||
69 | |||
70 | impl fmt::Display for Diagnostic { | ||
71 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
72 | writeln!(f, "=== {}\n**Source:** {}\n{}", self.id, self.location, self.doc) | ||
73 | } | ||
74 | } | ||
diff --git a/xtask/src/codegen/gen_feature_docs.rs b/xtask/src/codegen/gen_feature_docs.rs index 341e67c73..065dd33f1 100644 --- a/xtask/src/codegen/gen_feature_docs.rs +++ b/xtask/src/codegen/gen_feature_docs.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | //! Generates `assists.md` documentation. | 1 | //! Generates `assists.md` documentation. |
2 | 2 | ||
3 | use std::{fmt, fs, path::PathBuf}; | 3 | use std::{fmt, path::PathBuf}; |
4 | 4 | ||
5 | use crate::{ | 5 | use crate::{ |
6 | codegen::{self, extract_comment_blocks_with_empty_lines, Location, Mode, PREAMBLE}, | 6 | codegen::{self, extract_comment_blocks_with_empty_lines, Location, Mode, PREAMBLE}, |
@@ -33,7 +33,7 @@ impl Feature { | |||
33 | return Ok(res); | 33 | return Ok(res); |
34 | 34 | ||
35 | fn collect_file(acc: &mut Vec<Feature>, path: PathBuf) -> Result<()> { | 35 | fn collect_file(acc: &mut Vec<Feature>, path: PathBuf) -> Result<()> { |
36 | let text = fs::read_to_string(&path)?; | 36 | let text = xshell::read_file(&path)?; |
37 | let comment_blocks = extract_comment_blocks_with_empty_lines("Feature", &text); | 37 | let comment_blocks = extract_comment_blocks_with_empty_lines("Feature", &text); |
38 | 38 | ||
39 | for block in comment_blocks { | 39 | for block in comment_blocks { |
diff --git a/xtask/src/codegen/gen_features.rs b/xtask/src/codegen/gen_features.rs index b58c4a0c9..3cf15ce02 100644 --- a/xtask/src/codegen/gen_features.rs +++ b/xtask/src/codegen/gen_features.rs | |||
@@ -3,15 +3,13 @@ use std::path::{Path, PathBuf}; | |||
3 | 3 | ||
4 | use quote::quote; | 4 | use quote::quote; |
5 | use walkdir::WalkDir; | 5 | use walkdir::WalkDir; |
6 | use xshell::{cmd, read_file}; | ||
6 | 7 | ||
7 | use crate::{ | 8 | use crate::codegen::{project_root, reformat, update, Mode, Result}; |
8 | codegen::{project_root, reformat, update, Mode, Result}, | ||
9 | not_bash::{fs2, run}, | ||
10 | }; | ||
11 | 9 | ||
12 | pub fn generate_features(mode: Mode) -> Result<()> { | 10 | pub fn generate_features(mode: Mode) -> Result<()> { |
13 | if !Path::new("./target/rust").exists() { | 11 | if !Path::new("./target/rust").exists() { |
14 | run!("git clone https://github.com/rust-lang/rust ./target/rust")?; | 12 | cmd!("git clone https://github.com/rust-lang/rust ./target/rust").run()?; |
15 | } | 13 | } |
16 | 14 | ||
17 | let contents = generate_descriptor("./target/rust/src/doc/unstable-book/src".into())?; | 15 | let contents = generate_descriptor("./target/rust/src/doc/unstable-book/src".into())?; |
@@ -34,7 +32,7 @@ fn generate_descriptor(src_dir: PathBuf) -> Result<String> { | |||
34 | .map(|entry| { | 32 | .map(|entry| { |
35 | let path = entry.path(); | 33 | let path = entry.path(); |
36 | let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_"); | 34 | let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_"); |
37 | let doc = fs2::read_to_string(path).unwrap(); | 35 | let doc = read_file(path).unwrap(); |
38 | 36 | ||
39 | quote! { LintCompletion { label: #feature_ident, description: #doc } } | 37 | quote! { LintCompletion { label: #feature_ident, description: #doc } } |
40 | }); | 38 | }); |
diff --git a/xtask/src/codegen/gen_lint_completions.rs b/xtask/src/codegen/gen_lint_completions.rs new file mode 100644 index 000000000..b97421217 --- /dev/null +++ b/xtask/src/codegen/gen_lint_completions.rs | |||
@@ -0,0 +1,113 @@ | |||
1 | //! Generates descriptors structure for unstable feature from Unstable Book | ||
2 | use std::path::{Path, PathBuf}; | ||
3 | |||
4 | use quote::quote; | ||
5 | use walkdir::WalkDir; | ||
6 | use xshell::{cmd, read_file}; | ||
7 | |||
8 | use crate::{ | ||
9 | codegen::{project_root, reformat, update, Mode, Result}, | ||
10 | run_rustfmt, | ||
11 | }; | ||
12 | |||
13 | pub fn generate_lint_completions(mode: Mode) -> Result<()> { | ||
14 | if !Path::new("./target/rust").exists() { | ||
15 | cmd!("git clone --depth=1 https://github.com/rust-lang/rust ./target/rust").run()?; | ||
16 | } | ||
17 | |||
18 | let ts_features = generate_descriptor("./target/rust/src/doc/unstable-book/src".into())?; | ||
19 | cmd!("curl http://rust-lang.github.io/rust-clippy/master/lints.json --output ./target/clippy_lints.json").run()?; | ||
20 | |||
21 | let ts_clippy = generate_descriptor_clippy(&Path::new("./target/clippy_lints.json"))?; | ||
22 | let ts = quote! { | ||
23 | use crate::completions::attribute::LintCompletion; | ||
24 | #ts_features | ||
25 | #ts_clippy | ||
26 | }; | ||
27 | let contents = reformat(ts.to_string().as_str())?; | ||
28 | |||
29 | let destination = project_root().join("crates/completion/src/generated_lint_completions.rs"); | ||
30 | update(destination.as_path(), &contents, mode)?; | ||
31 | run_rustfmt(mode)?; | ||
32 | |||
33 | Ok(()) | ||
34 | } | ||
35 | |||
36 | fn generate_descriptor(src_dir: PathBuf) -> Result<proc_macro2::TokenStream> { | ||
37 | let definitions = ["language-features", "library-features"] | ||
38 | .iter() | ||
39 | .flat_map(|it| WalkDir::new(src_dir.join(it))) | ||
40 | .filter_map(|e| e.ok()) | ||
41 | .filter(|entry| { | ||
42 | // Get all `.md ` files | ||
43 | entry.file_type().is_file() && entry.path().extension().unwrap_or_default() == "md" | ||
44 | }) | ||
45 | .map(|entry| { | ||
46 | let path = entry.path(); | ||
47 | let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_"); | ||
48 | let doc = read_file(path).unwrap(); | ||
49 | |||
50 | quote! { LintCompletion { label: #feature_ident, description: #doc } } | ||
51 | }); | ||
52 | |||
53 | let ts = quote! { | ||
54 | pub(super) const FEATURES: &[LintCompletion] = &[ | ||
55 | #(#definitions),* | ||
56 | ]; | ||
57 | }; | ||
58 | |||
59 | Ok(ts) | ||
60 | } | ||
61 | |||
62 | #[derive(Default)] | ||
63 | struct ClippyLint { | ||
64 | help: String, | ||
65 | id: String, | ||
66 | } | ||
67 | |||
68 | fn generate_descriptor_clippy(path: &Path) -> Result<proc_macro2::TokenStream> { | ||
69 | let file_content = read_file(path)?; | ||
70 | let mut clippy_lints: Vec<ClippyLint> = vec![]; | ||
71 | |||
72 | for line in file_content.lines().map(|line| line.trim()) { | ||
73 | if line.starts_with(r#""id":"#) { | ||
74 | let clippy_lint = ClippyLint { | ||
75 | id: line | ||
76 | .strip_prefix(r#""id": ""#) | ||
77 | .expect("should be prefixed by id") | ||
78 | .strip_suffix(r#"","#) | ||
79 | .expect("should be suffixed by comma") | ||
80 | .into(), | ||
81 | help: String::new(), | ||
82 | }; | ||
83 | clippy_lints.push(clippy_lint) | ||
84 | } else if line.starts_with(r#""What it does":"#) { | ||
85 | // Typical line to strip: "What is doest": "Here is my useful content", | ||
86 | let prefix_to_strip = r#""What it does": ""#; | ||
87 | let suffix_to_strip = r#"","#; | ||
88 | |||
89 | let clippy_lint = clippy_lints.last_mut().expect("clippy lint must already exist"); | ||
90 | clippy_lint.help = line | ||
91 | .strip_prefix(prefix_to_strip) | ||
92 | .expect("should be prefixed by what it does") | ||
93 | .strip_suffix(suffix_to_strip) | ||
94 | .expect("should be suffixed by comma") | ||
95 | .into(); | ||
96 | } | ||
97 | } | ||
98 | |||
99 | let definitions = clippy_lints.into_iter().map(|clippy_lint| { | ||
100 | let lint_ident = format!("clippy::{}", clippy_lint.id); | ||
101 | let doc = clippy_lint.help; | ||
102 | |||
103 | quote! { LintCompletion { label: #lint_ident, description: #doc } } | ||
104 | }); | ||
105 | |||
106 | let ts = quote! { | ||
107 | pub(super) const CLIPPY_LINTS: &[LintCompletion] = &[ | ||
108 | #(#definitions),* | ||
109 | ]; | ||
110 | }; | ||
111 | |||
112 | Ok(ts) | ||
113 | } | ||
diff --git a/xtask/src/codegen/gen_parser_tests.rs b/xtask/src/codegen/gen_parser_tests.rs index 96fdd9216..19ae949d4 100644 --- a/xtask/src/codegen/gen_parser_tests.rs +++ b/xtask/src/codegen/gen_parser_tests.rs | |||
@@ -124,7 +124,7 @@ fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test | |||
124 | let file_name = path.file_name().unwrap().to_str().unwrap(); | 124 | let file_name = path.file_name().unwrap().to_str().unwrap(); |
125 | file_name[5..file_name.len() - 3].to_string() | 125 | file_name[5..file_name.len() - 3].to_string() |
126 | }; | 126 | }; |
127 | let text = fs::read_to_string(&path)?; | 127 | let text = xshell::read_file(&path)?; |
128 | let test = Test { name: name.clone(), text, ok }; | 128 | let test = Test { name: name.clone(), text, ok }; |
129 | if let Some(old) = res.insert(name, (path, test)) { | 129 | if let Some(old) = res.insert(name, (path, test)) { |
130 | println!("Duplicate test: {:?}", old); | 130 | println!("Duplicate test: {:?}", old); |
diff --git a/xtask/src/dist.rs b/xtask/src/dist.rs index aa7d94967..9e15a5a4c 100644 --- a/xtask/src/dist.rs +++ b/xtask/src/dist.rs | |||
@@ -1,4 +1,3 @@ | |||
1 | use flate2::{write::GzEncoder, Compression}; | ||
2 | use std::{ | 1 | use std::{ |
3 | env, | 2 | env, |
4 | fs::File, | 3 | fs::File, |
@@ -7,11 +6,10 @@ use std::{ | |||
7 | }; | 6 | }; |
8 | 7 | ||
9 | use anyhow::Result; | 8 | use anyhow::Result; |
9 | use flate2::{write::GzEncoder, Compression}; | ||
10 | use xshell::{cmd, cp, mkdir_p, pushd, read_file, rm_rf, write_file}; | ||
10 | 11 | ||
11 | use crate::{ | 12 | use crate::{date_iso, project_root}; |
12 | not_bash::{date_iso, fs2, pushd, rm_rf, run}, | ||
13 | project_root, | ||
14 | }; | ||
15 | 13 | ||
16 | pub struct DistCmd { | 14 | pub struct DistCmd { |
17 | pub nightly: bool, | 15 | pub nightly: bool, |
@@ -22,7 +20,7 @@ impl DistCmd { | |||
22 | pub fn run(self) -> Result<()> { | 20 | pub fn run(self) -> Result<()> { |
23 | let dist = project_root().join("dist"); | 21 | let dist = project_root().join("dist"); |
24 | rm_rf(&dist)?; | 22 | rm_rf(&dist)?; |
25 | fs2::create_dir_all(&dist)?; | 23 | mkdir_p(&dist)?; |
26 | 24 | ||
27 | if let Some(version) = self.client_version { | 25 | if let Some(version) = self.client_version { |
28 | let release_tag = if self.nightly { "nightly".to_string() } else { date_iso()? }; | 26 | let release_tag = if self.nightly { "nightly".to_string() } else { date_iso()? }; |
@@ -34,7 +32,7 @@ impl DistCmd { | |||
34 | } | 32 | } |
35 | 33 | ||
36 | fn dist_client(version: &str, release_tag: &str) -> Result<()> { | 34 | fn dist_client(version: &str, release_tag: &str) -> Result<()> { |
37 | let _d = pushd("./editors/code"); | 35 | let _d = pushd("./editors/code")?; |
38 | let nightly = release_tag == "nightly"; | 36 | let nightly = release_tag == "nightly"; |
39 | 37 | ||
40 | let mut patch = Patch::new("./package.json")?; | 38 | let mut patch = Patch::new("./package.json")?; |
@@ -54,20 +52,16 @@ fn dist_client(version: &str, release_tag: &str) -> Result<()> { | |||
54 | } | 52 | } |
55 | patch.commit()?; | 53 | patch.commit()?; |
56 | 54 | ||
57 | run!("npm ci")?; | 55 | cmd!("npm ci").run()?; |
58 | run!("npx vsce package -o ../../dist/rust-analyzer.vsix")?; | 56 | cmd!("npx vsce package -o ../../dist/rust-analyzer.vsix").run()?; |
59 | Ok(()) | 57 | Ok(()) |
60 | } | 58 | } |
61 | 59 | ||
62 | fn dist_server() -> Result<()> { | 60 | fn dist_server() -> Result<()> { |
63 | if cfg!(target_os = "linux") { | 61 | if cfg!(target_os = "linux") { |
64 | env::set_var("CC", "clang"); | 62 | env::set_var("CC", "clang"); |
65 | run!( | ||
66 | "cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --release" | ||
67 | )?; | ||
68 | } else { | ||
69 | run!("cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --release")?; | ||
70 | } | 63 | } |
64 | cmd!("cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --release").run()?; | ||
71 | 65 | ||
72 | let (src, dst) = if cfg!(target_os = "linux") { | 66 | let (src, dst) = if cfg!(target_os = "linux") { |
73 | ("./target/release/rust-analyzer", "./dist/rust-analyzer-linux") | 67 | ("./target/release/rust-analyzer", "./dist/rust-analyzer-linux") |
@@ -82,7 +76,7 @@ fn dist_server() -> Result<()> { | |||
82 | let src = Path::new(src); | 76 | let src = Path::new(src); |
83 | let dst = Path::new(dst); | 77 | let dst = Path::new(dst); |
84 | 78 | ||
85 | fs2::copy(&src, &dst)?; | 79 | cp(&src, &dst)?; |
86 | gzip(&src, &dst.with_extension("gz"))?; | 80 | gzip(&src, &dst.with_extension("gz"))?; |
87 | 81 | ||
88 | Ok(()) | 82 | Ok(()) |
@@ -105,7 +99,7 @@ struct Patch { | |||
105 | impl Patch { | 99 | impl Patch { |
106 | fn new(path: impl Into<PathBuf>) -> Result<Patch> { | 100 | fn new(path: impl Into<PathBuf>) -> Result<Patch> { |
107 | let path = path.into(); | 101 | let path = path.into(); |
108 | let contents = fs2::read_to_string(&path)?; | 102 | let contents = read_file(&path)?; |
109 | Ok(Patch { path, original_contents: contents.clone(), contents }) | 103 | Ok(Patch { path, original_contents: contents.clone(), contents }) |
110 | } | 104 | } |
111 | 105 | ||
@@ -115,13 +109,14 @@ impl Patch { | |||
115 | self | 109 | self |
116 | } | 110 | } |
117 | 111 | ||
118 | fn commit(&self) -> io::Result<()> { | 112 | fn commit(&self) -> Result<()> { |
119 | fs2::write(&self.path, &self.contents) | 113 | write_file(&self.path, &self.contents)?; |
114 | Ok(()) | ||
120 | } | 115 | } |
121 | } | 116 | } |
122 | 117 | ||
123 | impl Drop for Patch { | 118 | impl Drop for Patch { |
124 | fn drop(&mut self) { | 119 | fn drop(&mut self) { |
125 | fs2::write(&self.path, &self.original_contents).unwrap(); | 120 | write_file(&self.path, &self.original_contents).unwrap(); |
126 | } | 121 | } |
127 | } | 122 | } |
diff --git a/xtask/src/install.rs b/xtask/src/install.rs index fcc4f05e4..78a8af797 100644 --- a/xtask/src/install.rs +++ b/xtask/src/install.rs | |||
@@ -3,8 +3,7 @@ | |||
3 | use std::{env, path::PathBuf, str}; | 3 | use std::{env, path::PathBuf, str}; |
4 | 4 | ||
5 | use anyhow::{bail, format_err, Context, Result}; | 5 | use anyhow::{bail, format_err, Context, Result}; |
6 | 6 | use xshell::{cmd, pushd}; | |
7 | use crate::not_bash::{pushd, run}; | ||
8 | 7 | ||
9 | // Latest stable, feel free to send a PR if this lags behind. | 8 | // Latest stable, feel free to send a PR if this lags behind. |
10 | const REQUIRED_RUST_VERSION: u32 = 47; | 9 | const REQUIRED_RUST_VERSION: u32 = 47; |
@@ -14,8 +13,43 @@ pub struct InstallCmd { | |||
14 | pub server: Option<ServerOpt>, | 13 | pub server: Option<ServerOpt>, |
15 | } | 14 | } |
16 | 15 | ||
16 | #[derive(Clone, Copy)] | ||
17 | pub enum ClientOpt { | 17 | pub enum ClientOpt { |
18 | VsCode, | 18 | VsCode, |
19 | VsCodeInsiders, | ||
20 | VsCodium, | ||
21 | VsCodeOss, | ||
22 | Any, | ||
23 | } | ||
24 | |||
25 | impl ClientOpt { | ||
26 | pub const fn as_cmds(&self) -> &'static [&'static str] { | ||
27 | match self { | ||
28 | ClientOpt::VsCode => &["code"], | ||
29 | ClientOpt::VsCodeInsiders => &["code-insiders"], | ||
30 | ClientOpt::VsCodium => &["codium"], | ||
31 | ClientOpt::VsCodeOss => &["code-oss"], | ||
32 | ClientOpt::Any => &["code", "code-insiders", "codium", "code-oss"], | ||
33 | } | ||
34 | } | ||
35 | } | ||
36 | |||
37 | impl Default for ClientOpt { | ||
38 | fn default() -> Self { | ||
39 | ClientOpt::Any | ||
40 | } | ||
41 | } | ||
42 | |||
43 | impl std::str::FromStr for ClientOpt { | ||
44 | type Err = anyhow::Error; | ||
45 | |||
46 | fn from_str(s: &str) -> Result<Self, Self::Err> { | ||
47 | [ClientOpt::VsCode, ClientOpt::VsCodeInsiders, ClientOpt::VsCodium, ClientOpt::VsCodeOss] | ||
48 | .iter() | ||
49 | .copied() | ||
50 | .find(|c| [s] == c.as_cmds()) | ||
51 | .ok_or_else(|| anyhow::format_err!("no such client")) | ||
52 | } | ||
19 | } | 53 | } |
20 | 54 | ||
21 | pub struct ServerOpt { | 55 | pub struct ServerOpt { |
@@ -75,38 +109,35 @@ fn fix_path_for_mac() -> Result<()> { | |||
75 | Ok(()) | 109 | Ok(()) |
76 | } | 110 | } |
77 | 111 | ||
78 | fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { | 112 | fn install_client(client_opt: ClientOpt) -> Result<()> { |
79 | let _dir = pushd("./editors/code"); | 113 | let _dir = pushd("./editors/code"); |
80 | 114 | ||
81 | let find_code = |f: fn(&str) -> bool| -> Result<&'static str> { | 115 | let find_code = |f: fn(&str) -> bool| -> Result<&'static str> { |
82 | ["code", "code-insiders", "codium", "code-oss"] | 116 | client_opt.as_cmds().iter().copied().find(|bin| f(bin)).ok_or_else(|| { |
83 | .iter() | 117 | format_err!("Can't execute `code --version`. Perhaps it is not in $PATH?") |
84 | .copied() | 118 | }) |
85 | .find(|bin| f(bin)) | ||
86 | .ok_or_else(|| { | ||
87 | format_err!("Can't execute `code --version`. Perhaps it is not in $PATH?") | ||
88 | }) | ||
89 | }; | 119 | }; |
90 | 120 | ||
91 | let installed_extensions = if cfg!(unix) { | 121 | let installed_extensions = if cfg!(unix) { |
92 | run!("npm --version").context("`npm` is required to build the VS Code plugin")?; | 122 | cmd!("npm --version").run().context("`npm` is required to build the VS Code plugin")?; |
93 | run!("npm install")?; | 123 | cmd!("npm install").run()?; |
94 | 124 | ||
95 | run!("npm run package --scripts-prepend-node-path")?; | 125 | cmd!("npm run package --scripts-prepend-node-path").run()?; |
96 | 126 | ||
97 | let code = find_code(|bin| run!("{} --version", bin).is_ok())?; | 127 | let code = find_code(|bin| cmd!("{bin} --version").read().is_ok())?; |
98 | run!("{} --install-extension rust-analyzer.vsix --force", code)?; | 128 | cmd!("{code} --install-extension rust-analyzer.vsix --force").run()?; |
99 | run!("{} --list-extensions", code; echo = false)? | 129 | cmd!("{code} --list-extensions").read()? |
100 | } else { | 130 | } else { |
101 | run!("cmd.exe /c npm --version") | 131 | cmd!("cmd.exe /c npm --version") |
132 | .run() | ||
102 | .context("`npm` is required to build the VS Code plugin")?; | 133 | .context("`npm` is required to build the VS Code plugin")?; |
103 | run!("cmd.exe /c npm install")?; | 134 | cmd!("cmd.exe /c npm install").run()?; |
104 | 135 | ||
105 | run!("cmd.exe /c npm run package")?; | 136 | cmd!("cmd.exe /c npm run package").run()?; |
106 | 137 | ||
107 | let code = find_code(|bin| run!("cmd.exe /c {}.cmd --version", bin).is_ok())?; | 138 | let code = find_code(|bin| cmd!("cmd.exe /c {bin}.cmd --version").read().is_ok())?; |
108 | run!(r"cmd.exe /c {}.cmd --install-extension rust-analyzer.vsix --force", code)?; | 139 | cmd!("cmd.exe /c {code}.cmd --install-extension rust-analyzer.vsix --force").run()?; |
109 | run!("cmd.exe /c {}.cmd --list-extensions", code; echo = false)? | 140 | cmd!("cmd.exe /c {code}.cmd --list-extensions").read()? |
110 | }; | 141 | }; |
111 | 142 | ||
112 | if !installed_extensions.contains("rust-analyzer") { | 143 | if !installed_extensions.contains("rust-analyzer") { |
@@ -122,7 +153,7 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { | |||
122 | 153 | ||
123 | fn install_server(opts: ServerOpt) -> Result<()> { | 154 | fn install_server(opts: ServerOpt) -> Result<()> { |
124 | let mut old_rust = false; | 155 | let mut old_rust = false; |
125 | if let Ok(stdout) = run!("cargo --version") { | 156 | if let Ok(stdout) = cmd!("cargo --version").read() { |
126 | if !check_version(&stdout, REQUIRED_RUST_VERSION) { | 157 | if !check_version(&stdout, REQUIRED_RUST_VERSION) { |
127 | old_rust = true; | 158 | old_rust = true; |
128 | } | 159 | } |
@@ -134,12 +165,13 @@ fn install_server(opts: ServerOpt) -> Result<()> { | |||
134 | REQUIRED_RUST_VERSION, | 165 | REQUIRED_RUST_VERSION, |
135 | ) | 166 | ) |
136 | } | 167 | } |
137 | 168 | let features = match opts.malloc { | |
138 | let malloc_feature = match opts.malloc { | 169 | Malloc::System => &[][..], |
139 | Malloc::System => "", | 170 | Malloc::Mimalloc => &["--features", "mimalloc"], |
140 | Malloc::Mimalloc => "--features mimalloc", | ||
141 | }; | 171 | }; |
142 | let res = run!("cargo install --path crates/rust-analyzer --locked --force {}", malloc_feature); | 172 | |
173 | let cmd = cmd!("cargo install --path crates/rust-analyzer --locked --force {features...}"); | ||
174 | let res = cmd.run(); | ||
143 | 175 | ||
144 | if res.is_err() && old_rust { | 176 | if res.is_err() && old_rust { |
145 | eprintln!( | 177 | eprintln!( |
@@ -148,7 +180,8 @@ fn install_server(opts: ServerOpt) -> Result<()> { | |||
148 | ); | 180 | ); |
149 | } | 181 | } |
150 | 182 | ||
151 | res.map(drop) | 183 | res?; |
184 | Ok(()) | ||
152 | } | 185 | } |
153 | 186 | ||
154 | fn check_version(version_output: &str, min_minor_version: u32) -> bool { | 187 | fn check_version(version_output: &str, min_minor_version: u32) -> bool { |
diff --git a/xtask/src/lib.rs b/xtask/src/lib.rs index e790d995f..babec2dbd 100644 --- a/xtask/src/lib.rs +++ b/xtask/src/lib.rs | |||
@@ -2,7 +2,6 @@ | |||
2 | //! | 2 | //! |
3 | //! See https://github.com/matklad/cargo-xtask/ | 3 | //! See https://github.com/matklad/cargo-xtask/ |
4 | 4 | ||
5 | pub mod not_bash; | ||
6 | pub mod codegen; | 5 | pub mod codegen; |
7 | mod ast_src; | 6 | mod ast_src; |
8 | 7 | ||
@@ -19,11 +18,9 @@ use std::{ | |||
19 | }; | 18 | }; |
20 | 19 | ||
21 | use walkdir::{DirEntry, WalkDir}; | 20 | use walkdir::{DirEntry, WalkDir}; |
21 | use xshell::{cmd, pushd, pushenv}; | ||
22 | 22 | ||
23 | use crate::{ | 23 | use crate::codegen::Mode; |
24 | codegen::Mode, | ||
25 | not_bash::{pushd, pushenv}, | ||
26 | }; | ||
27 | 24 | ||
28 | pub use anyhow::{bail, Context as _, Result}; | 25 | pub use anyhow::{bail, Context as _, Result}; |
29 | 26 | ||
@@ -53,18 +50,19 @@ pub fn rust_files(path: &Path) -> impl Iterator<Item = PathBuf> { | |||
53 | } | 50 | } |
54 | 51 | ||
55 | pub fn run_rustfmt(mode: Mode) -> Result<()> { | 52 | pub fn run_rustfmt(mode: Mode) -> Result<()> { |
56 | let _dir = pushd(project_root()); | 53 | let _dir = pushd(project_root())?; |
57 | let _e = pushenv("RUSTUP_TOOLCHAIN", "stable"); | 54 | let _e = pushenv("RUSTUP_TOOLCHAIN", "stable"); |
58 | ensure_rustfmt()?; | 55 | ensure_rustfmt()?; |
59 | match mode { | 56 | let check = match mode { |
60 | Mode::Overwrite => run!("cargo fmt"), | 57 | Mode::Overwrite => &[][..], |
61 | Mode::Verify => run!("cargo fmt -- --check"), | 58 | Mode::Verify => &["--", "--check"], |
62 | }?; | 59 | }; |
60 | cmd!("cargo fmt {check...}").run()?; | ||
63 | Ok(()) | 61 | Ok(()) |
64 | } | 62 | } |
65 | 63 | ||
66 | fn ensure_rustfmt() -> Result<()> { | 64 | fn ensure_rustfmt() -> Result<()> { |
67 | let out = run!("rustfmt --version")?; | 65 | let out = cmd!("rustfmt --version").read()?; |
68 | if !out.contains("stable") { | 66 | if !out.contains("stable") { |
69 | bail!( | 67 | bail!( |
70 | "Failed to run rustfmt from toolchain 'stable'. \ | 68 | "Failed to run rustfmt from toolchain 'stable'. \ |
@@ -75,40 +73,46 @@ fn ensure_rustfmt() -> Result<()> { | |||
75 | } | 73 | } |
76 | 74 | ||
77 | pub fn run_clippy() -> Result<()> { | 75 | pub fn run_clippy() -> Result<()> { |
78 | if run!("cargo clippy --version").is_err() { | 76 | if cmd!("cargo clippy --version").read().is_err() { |
79 | bail!( | 77 | bail!( |
80 | "Failed run cargo clippy. \ | 78 | "Failed run cargo clippy. \ |
81 | Please run `rustup component add clippy` to install it.", | 79 | Please run `rustup component add clippy` to install it.", |
82 | ) | 80 | ) |
83 | } | 81 | } |
84 | 82 | ||
85 | let allowed_lints = [ | 83 | let allowed_lints = " |
86 | "clippy::collapsible_if", | 84 | -A clippy::collapsible_if |
87 | "clippy::needless_pass_by_value", | 85 | -A clippy::needless_pass_by_value |
88 | "clippy::nonminimal_bool", | 86 | -A clippy::nonminimal_bool |
89 | "clippy::redundant_pattern_matching", | 87 | -A clippy::redundant_pattern_matching |
90 | ]; | 88 | " |
91 | run!("cargo clippy --all-features --all-targets -- -A {}", allowed_lints.join(" -A "))?; | 89 | .split_ascii_whitespace(); |
90 | cmd!("cargo clippy --all-features --all-targets -- {allowed_lints...}").run()?; | ||
92 | Ok(()) | 91 | Ok(()) |
93 | } | 92 | } |
94 | 93 | ||
95 | pub fn run_fuzzer() -> Result<()> { | 94 | pub fn run_fuzzer() -> Result<()> { |
96 | let _d = pushd("./crates/syntax"); | 95 | let _d = pushd("./crates/syntax")?; |
97 | let _e = pushenv("RUSTUP_TOOLCHAIN", "nightly"); | 96 | let _e = pushenv("RUSTUP_TOOLCHAIN", "nightly"); |
98 | if run!("cargo fuzz --help").is_err() { | 97 | if cmd!("cargo fuzz --help").read().is_err() { |
99 | run!("cargo install cargo-fuzz")?; | 98 | cmd!("cargo install cargo-fuzz").run()?; |
100 | }; | 99 | }; |
101 | 100 | ||
102 | // Expecting nightly rustc | 101 | // Expecting nightly rustc |
103 | let out = run!("rustc --version")?; | 102 | let out = cmd!("rustc --version").read()?; |
104 | if !out.contains("nightly") { | 103 | if !out.contains("nightly") { |
105 | bail!("fuzz tests require nightly rustc") | 104 | bail!("fuzz tests require nightly rustc") |
106 | } | 105 | } |
107 | 106 | ||
108 | run!("cargo fuzz run parser")?; | 107 | cmd!("cargo fuzz run parser").run()?; |
109 | Ok(()) | 108 | Ok(()) |
110 | } | 109 | } |
111 | 110 | ||
111 | fn date_iso() -> Result<String> { | ||
112 | let res = cmd!("date --iso --utc").read()?; | ||
113 | Ok(res) | ||
114 | } | ||
115 | |||
112 | fn is_release_tag(tag: &str) -> bool { | 116 | fn is_release_tag(tag: &str) -> bool { |
113 | tag.len() == "2020-02-24".len() && tag.starts_with(|c: char| c.is_ascii_digit()) | 117 | tag.len() == "2020-02-24".len() && tag.starts_with(|c: char| c.is_ascii_digit()) |
114 | } | 118 | } |
diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3f4aa5497..536a67047 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs | |||
@@ -12,12 +12,12 @@ use std::env; | |||
12 | 12 | ||
13 | use codegen::CodegenCmd; | 13 | use codegen::CodegenCmd; |
14 | use pico_args::Arguments; | 14 | use pico_args::Arguments; |
15 | use xshell::pushd; | ||
15 | use xtask::{ | 16 | use xtask::{ |
16 | codegen::{self, Mode}, | 17 | codegen::{self, Mode}, |
17 | dist::DistCmd, | 18 | dist::DistCmd, |
18 | install::{ClientOpt, InstallCmd, Malloc, ServerOpt}, | 19 | install::{InstallCmd, Malloc, ServerOpt}, |
19 | metrics::MetricsCmd, | 20 | metrics::MetricsCmd, |
20 | not_bash::pushd, | ||
21 | pre_cache::PreCacheCmd, | 21 | pre_cache::PreCacheCmd, |
22 | pre_commit, project_root, | 22 | pre_commit, project_root, |
23 | release::{PromoteCmd, ReleaseCmd}, | 23 | release::{PromoteCmd, ReleaseCmd}, |
@@ -29,7 +29,7 @@ fn main() -> Result<()> { | |||
29 | return pre_commit::run_hook(); | 29 | return pre_commit::run_hook(); |
30 | } | 30 | } |
31 | 31 | ||
32 | let _d = pushd(project_root()); | 32 | let _d = pushd(project_root())?; |
33 | 33 | ||
34 | let mut args = Arguments::from_env(); | 34 | let mut args = Arguments::from_env(); |
35 | let subcommand = args.subcommand()?.unwrap_or_default(); | 35 | let subcommand = args.subcommand()?.unwrap_or_default(); |
@@ -46,19 +46,20 @@ USAGE: | |||
46 | cargo xtask install [FLAGS] | 46 | cargo xtask install [FLAGS] |
47 | 47 | ||
48 | FLAGS: | 48 | FLAGS: |
49 | --client-code Install only VS Code plugin | 49 | --client[=CLIENT] Install only VS Code plugin. |
50 | --server Install only the language server | 50 | CLIENT is one of 'code', 'code-insiders', 'codium', or 'code-oss' |
51 | --mimalloc Use mimalloc for server | 51 | --server Install only the language server |
52 | -h, --help Prints help information | 52 | --mimalloc Use mimalloc for server |
53 | -h, --help Prints help information | ||
53 | " | 54 | " |
54 | ); | 55 | ); |
55 | return Ok(()); | 56 | return Ok(()); |
56 | } | 57 | } |
57 | let server = args.contains("--server"); | 58 | let server = args.contains("--server"); |
58 | let client_code = args.contains("--client-code"); | 59 | let client_code = args.contains("--client"); |
59 | if server && client_code { | 60 | if server && client_code { |
60 | eprintln!( | 61 | eprintln!( |
61 | "error: The argument `--server` cannot be used with `--client-code`\n\n\ | 62 | "error: The argument `--server` cannot be used with `--client`\n\n\ |
62 | For more information try --help" | 63 | For more information try --help" |
63 | ); | 64 | ); |
64 | return Ok(()); | 65 | return Ok(()); |
@@ -67,10 +68,12 @@ FLAGS: | |||
67 | let malloc = | 68 | let malloc = |
68 | if args.contains("--mimalloc") { Malloc::Mimalloc } else { Malloc::System }; | 69 | if args.contains("--mimalloc") { Malloc::Mimalloc } else { Malloc::System }; |
69 | 70 | ||
71 | let client_opt = args.opt_value_from_str("--client")?; | ||
72 | |||
70 | args.finish()?; | 73 | args.finish()?; |
71 | 74 | ||
72 | InstallCmd { | 75 | InstallCmd { |
73 | client: if server { None } else { Some(ClientOpt::VsCode) }, | 76 | client: if server { None } else { Some(client_opt.unwrap_or_default()) }, |
74 | server: if client_code { None } else { Some(ServerOpt { malloc }) }, | 77 | server: if client_code { None } else { Some(ServerOpt { malloc }) }, |
75 | } | 78 | } |
76 | .run() | 79 | .run() |
diff --git a/xtask/src/metrics.rs b/xtask/src/metrics.rs index 4bade2c7e..e0d1aaf97 100644 --- a/xtask/src/metrics.rs +++ b/xtask/src/metrics.rs | |||
@@ -7,8 +7,7 @@ use std::{ | |||
7 | }; | 7 | }; |
8 | 8 | ||
9 | use anyhow::{bail, format_err, Result}; | 9 | use anyhow::{bail, format_err, Result}; |
10 | 10 | use xshell::{cmd, mkdir_p, pushd, pushenv, read_file, rm_rf}; | |
11 | use crate::not_bash::{fs2, pushd, pushenv, rm_rf, run}; | ||
12 | 11 | ||
13 | type Unit = String; | 12 | type Unit = String; |
14 | 13 | ||
@@ -23,12 +22,13 @@ impl MetricsCmd { | |||
23 | rm_rf("./target/release")?; | 22 | rm_rf("./target/release")?; |
24 | } | 23 | } |
25 | if !Path::new("./target/rustc-perf").exists() { | 24 | if !Path::new("./target/rustc-perf").exists() { |
26 | fs2::create_dir_all("./target/rustc-perf")?; | 25 | mkdir_p("./target/rustc-perf")?; |
27 | run!("git clone https://github.com/rust-lang/rustc-perf.git ./target/rustc-perf")?; | 26 | cmd!("git clone https://github.com/rust-lang/rustc-perf.git ./target/rustc-perf") |
27 | .run()?; | ||
28 | } | 28 | } |
29 | { | 29 | { |
30 | let _d = pushd("./target/rustc-perf"); | 30 | let _d = pushd("./target/rustc-perf")?; |
31 | run!("git reset --hard 1d9288b0da7febf2599917da1b57dc241a1af033")?; | 31 | cmd!("git reset --hard 1d9288b0da7febf2599917da1b57dc241a1af033").run()?; |
32 | } | 32 | } |
33 | 33 | ||
34 | let _env = pushenv("RA_METRICS", "1"); | 34 | let _env = pushenv("RA_METRICS", "1"); |
@@ -39,17 +39,20 @@ impl MetricsCmd { | |||
39 | metrics.measure_analysis_stats("webrender")?; | 39 | metrics.measure_analysis_stats("webrender")?; |
40 | 40 | ||
41 | if !self.dry_run { | 41 | if !self.dry_run { |
42 | let _d = pushd("target"); | 42 | let _d = pushd("target")?; |
43 | let metrics_token = env::var("METRICS_TOKEN").unwrap(); | 43 | let metrics_token = env::var("METRICS_TOKEN").unwrap(); |
44 | let repo = format!("https://{}@github.com/rust-analyzer/metrics.git", metrics_token); | 44 | cmd!( |
45 | run!("git clone --depth 1 {}", repo)?; | 45 | "git clone --depth 1 https://{metrics_token}@github.com/rust-analyzer/metrics.git" |
46 | let _d = pushd("metrics"); | 46 | ) |
47 | .run()?; | ||
48 | let _d = pushd("metrics")?; | ||
47 | 49 | ||
48 | let mut file = std::fs::OpenOptions::new().append(true).open("metrics.json")?; | 50 | let mut file = std::fs::OpenOptions::new().append(true).open("metrics.json")?; |
49 | writeln!(file, "{}", metrics.json())?; | 51 | writeln!(file, "{}", metrics.json())?; |
50 | run!("git add .")?; | 52 | cmd!("git add .").run()?; |
51 | run!("git -c user.name=Bot -c [email protected] commit --message 📈")?; | 53 | cmd!("git -c user.name=Bot -c [email protected] commit --message 📈") |
52 | run!("git push origin master")?; | 54 | .run()?; |
55 | cmd!("git push origin master").run()?; | ||
53 | } | 56 | } |
54 | eprintln!("{:#?}", metrics); | 57 | eprintln!("{:#?}", metrics); |
55 | Ok(()) | 58 | Ok(()) |
@@ -59,10 +62,10 @@ impl MetricsCmd { | |||
59 | impl Metrics { | 62 | impl Metrics { |
60 | fn measure_build(&mut self) -> Result<()> { | 63 | fn measure_build(&mut self) -> Result<()> { |
61 | eprintln!("\nMeasuring build"); | 64 | eprintln!("\nMeasuring build"); |
62 | run!("cargo fetch")?; | 65 | cmd!("cargo fetch").run()?; |
63 | 66 | ||
64 | let time = Instant::now(); | 67 | let time = Instant::now(); |
65 | run!("cargo build --release --package rust-analyzer --bin rust-analyzer")?; | 68 | cmd!("cargo build --release --package rust-analyzer --bin rust-analyzer").run()?; |
66 | let time = time.elapsed(); | 69 | let time = time.elapsed(); |
67 | self.report("build", time.as_millis() as u64, "ms".into()); | 70 | self.report("build", time.as_millis() as u64, "ms".into()); |
68 | Ok(()) | 71 | Ok(()) |
@@ -78,7 +81,7 @@ impl Metrics { | |||
78 | } | 81 | } |
79 | fn measure_analysis_stats_path(&mut self, name: &str, path: &str) -> Result<()> { | 82 | fn measure_analysis_stats_path(&mut self, name: &str, path: &str) -> Result<()> { |
80 | eprintln!("\nMeasuring analysis-stats/{}", name); | 83 | eprintln!("\nMeasuring analysis-stats/{}", name); |
81 | let output = run!("./target/release/rust-analyzer analysis-stats --quiet {}", path)?; | 84 | let output = cmd!("./target/release/rust-analyzer analysis-stats --quiet {path}").read()?; |
82 | for (metric, value, unit) in parse_metrics(&output) { | 85 | for (metric, value, unit) in parse_metrics(&output) { |
83 | self.report(&format!("analysis-stats/{}/{}", name, metric), value, unit.into()); | 86 | self.report(&format!("analysis-stats/{}/{}", name, metric), value, unit.into()); |
84 | } | 87 | } |
@@ -118,7 +121,7 @@ impl Metrics { | |||
118 | fn new() -> Result<Metrics> { | 121 | fn new() -> Result<Metrics> { |
119 | let host = Host::new()?; | 122 | let host = Host::new()?; |
120 | let timestamp = SystemTime::now(); | 123 | let timestamp = SystemTime::now(); |
121 | let revision = run!("git rev-parse HEAD")?; | 124 | let revision = cmd!("git rev-parse HEAD").read()?; |
122 | Ok(Metrics { host, timestamp, revision, metrics: BTreeMap::new() }) | 125 | Ok(Metrics { host, timestamp, revision, metrics: BTreeMap::new() }) |
123 | } | 126 | } |
124 | 127 | ||
@@ -160,7 +163,7 @@ impl Host { | |||
160 | return Ok(Host { os, cpu, mem }); | 163 | return Ok(Host { os, cpu, mem }); |
161 | 164 | ||
162 | fn read_field<'a>(path: &str, field: &str) -> Result<String> { | 165 | fn read_field<'a>(path: &str, field: &str) -> Result<String> { |
163 | let text = fs2::read_to_string(path)?; | 166 | let text = read_file(path)?; |
164 | 167 | ||
165 | let line = text | 168 | let line = text |
166 | .lines() | 169 | .lines() |
diff --git a/xtask/src/not_bash.rs b/xtask/src/not_bash.rs deleted file mode 100644 index 038898993..000000000 --- a/xtask/src/not_bash.rs +++ /dev/null | |||
@@ -1,169 +0,0 @@ | |||
1 | //! A bad shell -- small cross platform module for writing glue code | ||
2 | |||
3 | use std::{ | ||
4 | cell::RefCell, | ||
5 | env, | ||
6 | ffi::OsString, | ||
7 | io::{self, Write}, | ||
8 | path::{Path, PathBuf}, | ||
9 | process::{Command, Stdio}, | ||
10 | }; | ||
11 | |||
12 | use anyhow::{bail, Context, Result}; | ||
13 | |||
14 | pub use fs_err as fs2; | ||
15 | |||
16 | #[macro_export] | ||
17 | macro_rules! run { | ||
18 | ($($expr:expr),*) => { | ||
19 | run!($($expr),*; echo = true) | ||
20 | }; | ||
21 | ($($expr:expr),* ; echo = $echo:expr) => { | ||
22 | $crate::not_bash::run_process(format!($($expr),*), $echo, None) | ||
23 | }; | ||
24 | ($($expr:expr),* ; <$stdin:expr) => { | ||
25 | $crate::not_bash::run_process(format!($($expr),*), false, Some($stdin)) | ||
26 | }; | ||
27 | } | ||
28 | pub use crate::run; | ||
29 | |||
30 | pub struct Pushd { | ||
31 | _p: (), | ||
32 | } | ||
33 | |||
34 | pub fn pushd(path: impl Into<PathBuf>) -> Pushd { | ||
35 | Env::with(|env| env.pushd(path.into())); | ||
36 | Pushd { _p: () } | ||
37 | } | ||
38 | |||
39 | impl Drop for Pushd { | ||
40 | fn drop(&mut self) { | ||
41 | Env::with(|env| env.popd()) | ||
42 | } | ||
43 | } | ||
44 | |||
45 | pub struct Pushenv { | ||
46 | _p: (), | ||
47 | } | ||
48 | |||
49 | pub fn pushenv(var: &str, value: &str) -> Pushenv { | ||
50 | Env::with(|env| env.pushenv(var.into(), value.into())); | ||
51 | Pushenv { _p: () } | ||
52 | } | ||
53 | |||
54 | impl Drop for Pushenv { | ||
55 | fn drop(&mut self) { | ||
56 | Env::with(|env| env.popenv()) | ||
57 | } | ||
58 | } | ||
59 | |||
60 | pub fn rm_rf(path: impl AsRef<Path>) -> io::Result<()> { | ||
61 | let path = path.as_ref(); | ||
62 | if !path.exists() { | ||
63 | return Ok(()); | ||
64 | } | ||
65 | if path.is_file() { | ||
66 | fs2::remove_file(path) | ||
67 | } else { | ||
68 | fs2::remove_dir_all(path) | ||
69 | } | ||
70 | } | ||
71 | |||
72 | #[doc(hidden)] | ||
73 | pub fn run_process(cmd: String, echo: bool, stdin: Option<&[u8]>) -> Result<String> { | ||
74 | run_process_inner(&cmd, echo, stdin).with_context(|| format!("process `{}` failed", cmd)) | ||
75 | } | ||
76 | |||
77 | pub fn date_iso() -> Result<String> { | ||
78 | run!("date --iso --utc") | ||
79 | } | ||
80 | |||
81 | fn run_process_inner(cmd: &str, echo: bool, stdin: Option<&[u8]>) -> Result<String> { | ||
82 | let mut args = shelx(cmd); | ||
83 | let binary = args.remove(0); | ||
84 | let current_dir = Env::with(|it| it.cwd().to_path_buf()); | ||
85 | |||
86 | if echo { | ||
87 | println!("> {}", cmd) | ||
88 | } | ||
89 | |||
90 | let mut command = Command::new(binary); | ||
91 | command.args(args).current_dir(current_dir).stderr(Stdio::inherit()); | ||
92 | let output = match stdin { | ||
93 | None => command.stdin(Stdio::null()).output(), | ||
94 | Some(stdin) => { | ||
95 | command.stdin(Stdio::piped()).stdout(Stdio::piped()); | ||
96 | let mut process = command.spawn()?; | ||
97 | process.stdin.take().unwrap().write_all(stdin)?; | ||
98 | process.wait_with_output() | ||
99 | } | ||
100 | }?; | ||
101 | let stdout = String::from_utf8(output.stdout)?; | ||
102 | |||
103 | if echo { | ||
104 | print!("{}", stdout) | ||
105 | } | ||
106 | |||
107 | if !output.status.success() { | ||
108 | bail!("{}", output.status) | ||
109 | } | ||
110 | |||
111 | Ok(stdout.trim().to_string()) | ||
112 | } | ||
113 | |||
114 | // FIXME: some real shell lexing here | ||
115 | fn shelx(cmd: &str) -> Vec<String> { | ||
116 | let mut res = Vec::new(); | ||
117 | for (string_piece, in_quotes) in cmd.split('\'').zip([false, true].iter().copied().cycle()) { | ||
118 | if in_quotes { | ||
119 | res.push(string_piece.to_string()) | ||
120 | } else { | ||
121 | if !string_piece.is_empty() { | ||
122 | res.extend(string_piece.split_ascii_whitespace().map(|it| it.to_string())) | ||
123 | } | ||
124 | } | ||
125 | } | ||
126 | res | ||
127 | } | ||
128 | |||
129 | struct Env { | ||
130 | pushd_stack: Vec<PathBuf>, | ||
131 | pushenv_stack: Vec<(OsString, Option<OsString>)>, | ||
132 | } | ||
133 | |||
134 | impl Env { | ||
135 | fn with<F: FnOnce(&mut Env) -> T, T>(f: F) -> T { | ||
136 | thread_local! { | ||
137 | static ENV: RefCell<Env> = RefCell::new(Env { | ||
138 | pushd_stack: vec![env::current_dir().unwrap()], | ||
139 | pushenv_stack: vec![], | ||
140 | }); | ||
141 | } | ||
142 | ENV.with(|it| f(&mut *it.borrow_mut())) | ||
143 | } | ||
144 | |||
145 | fn pushd(&mut self, dir: PathBuf) { | ||
146 | let dir = self.cwd().join(dir); | ||
147 | self.pushd_stack.push(dir); | ||
148 | env::set_current_dir(self.cwd()) | ||
149 | .unwrap_or_else(|err| panic!("Failed to set cwd to {}: {}", self.cwd().display(), err)); | ||
150 | } | ||
151 | fn popd(&mut self) { | ||
152 | self.pushd_stack.pop().unwrap(); | ||
153 | env::set_current_dir(self.cwd()).unwrap(); | ||
154 | } | ||
155 | fn pushenv(&mut self, var: OsString, value: OsString) { | ||
156 | self.pushenv_stack.push((var.clone(), env::var_os(&var))); | ||
157 | env::set_var(var, value) | ||
158 | } | ||
159 | fn popenv(&mut self) { | ||
160 | let (var, value) = self.pushenv_stack.pop().unwrap(); | ||
161 | match value { | ||
162 | None => env::remove_var(var), | ||
163 | Some(value) => env::set_var(var, value), | ||
164 | } | ||
165 | } | ||
166 | fn cwd(&self) -> &Path { | ||
167 | self.pushd_stack.last().unwrap() | ||
168 | } | ||
169 | } | ||
diff --git a/xtask/src/pre_cache.rs b/xtask/src/pre_cache.rs index 47ba6ba24..569f88f68 100644 --- a/xtask/src/pre_cache.rs +++ b/xtask/src/pre_cache.rs | |||
@@ -4,8 +4,7 @@ use std::{ | |||
4 | }; | 4 | }; |
5 | 5 | ||
6 | use anyhow::Result; | 6 | use anyhow::Result; |
7 | 7 | use xshell::rm_rf; | |
8 | use crate::not_bash::{fs2, rm_rf}; | ||
9 | 8 | ||
10 | pub struct PreCacheCmd; | 9 | pub struct PreCacheCmd; |
11 | 10 | ||
@@ -26,7 +25,7 @@ impl PreCacheCmd { | |||
26 | } | 25 | } |
27 | } | 26 | } |
28 | 27 | ||
29 | fs2::remove_file("./target/.rustc_info.json")?; | 28 | rm_rf("./target/.rustc_info.json")?; |
30 | 29 | ||
31 | let to_delete = read_dir("./crates", FileType::is_dir)? | 30 | let to_delete = read_dir("./crates", FileType::is_dir)? |
32 | .into_iter() | 31 | .into_iter() |
diff --git a/xtask/src/pre_commit.rs b/xtask/src/pre_commit.rs index 056f34acf..8f2dbea19 100644 --- a/xtask/src/pre_commit.rs +++ b/xtask/src/pre_commit.rs | |||
@@ -3,19 +3,21 @@ | |||
3 | use std::{fs, path::PathBuf}; | 3 | use std::{fs, path::PathBuf}; |
4 | 4 | ||
5 | use anyhow::{bail, Result}; | 5 | use anyhow::{bail, Result}; |
6 | use xshell::cmd; | ||
6 | 7 | ||
7 | use crate::{not_bash::run, project_root, run_rustfmt, Mode}; | 8 | use crate::{project_root, run_rustfmt, Mode}; |
8 | 9 | ||
9 | // FIXME: if there are changed `.ts` files, also reformat TypeScript (by | 10 | // FIXME: if there are changed `.ts` files, also reformat TypeScript (by |
10 | // shelling out to `npm fmt`). | 11 | // shelling out to `npm fmt`). |
11 | pub fn run_hook() -> Result<()> { | 12 | pub fn run_hook() -> Result<()> { |
12 | run_rustfmt(Mode::Overwrite)?; | 13 | run_rustfmt(Mode::Overwrite)?; |
13 | 14 | ||
14 | let diff = run!("git diff --diff-filter=MAR --name-only --cached")?; | 15 | let diff = cmd!("git diff --diff-filter=MAR --name-only --cached").read()?; |
15 | 16 | ||
16 | let root = project_root(); | 17 | let root = project_root(); |
17 | for line in diff.lines() { | 18 | for line in diff.lines() { |
18 | run!("git update-index --add {}", root.join(line).display())?; | 19 | let file = root.join(line); |
20 | cmd!("git update-index --add {file}").run()?; | ||
19 | } | 21 | } |
20 | 22 | ||
21 | Ok(()) | 23 | Ok(()) |
diff --git a/xtask/src/release.rs b/xtask/src/release.rs index 3aab29801..3cf0d849f 100644 --- a/xtask/src/release.rs +++ b/xtask/src/release.rs | |||
@@ -1,8 +1,6 @@ | |||
1 | use crate::{ | 1 | use xshell::{cmd, cp, pushd, read_dir, write_file}; |
2 | codegen, is_release_tag, | 2 | |
3 | not_bash::{date_iso, fs2, pushd, run}, | 3 | use crate::{codegen, date_iso, is_release_tag, project_root, Mode, Result}; |
4 | project_root, Mode, Result, | ||
5 | }; | ||
6 | 4 | ||
7 | pub struct ReleaseCmd { | 5 | pub struct ReleaseCmd { |
8 | pub dry_run: bool, | 6 | pub dry_run: bool, |
@@ -11,10 +9,10 @@ pub struct ReleaseCmd { | |||
11 | impl ReleaseCmd { | 9 | impl ReleaseCmd { |
12 | pub fn run(self) -> Result<()> { | 10 | pub fn run(self) -> Result<()> { |
13 | if !self.dry_run { | 11 | if !self.dry_run { |
14 | run!("git switch release")?; | 12 | cmd!("git switch release").run()?; |
15 | run!("git fetch upstream --tags --force")?; | 13 | cmd!("git fetch upstream --tags --force").run()?; |
16 | run!("git reset --hard tags/nightly")?; | 14 | cmd!("git reset --hard tags/nightly").run()?; |
17 | run!("git push")?; | 15 | cmd!("git push").run()?; |
18 | } | 16 | } |
19 | codegen::generate_assists_docs(Mode::Overwrite)?; | 17 | codegen::generate_assists_docs(Mode::Overwrite)?; |
20 | codegen::generate_feature_docs(Mode::Overwrite)?; | 18 | codegen::generate_feature_docs(Mode::Overwrite)?; |
@@ -23,8 +21,8 @@ impl ReleaseCmd { | |||
23 | let changelog_dir = website_root.join("./thisweek/_posts"); | 21 | let changelog_dir = website_root.join("./thisweek/_posts"); |
24 | 22 | ||
25 | let today = date_iso()?; | 23 | let today = date_iso()?; |
26 | let commit = run!("git rev-parse HEAD")?; | 24 | let commit = cmd!("git rev-parse HEAD").read()?; |
27 | let changelog_n = fs2::read_dir(changelog_dir.as_path())?.count(); | 25 | let changelog_n = read_dir(changelog_dir.as_path())?.len(); |
28 | 26 | ||
29 | let contents = format!( | 27 | let contents = format!( |
30 | "\ | 28 | "\ |
@@ -52,20 +50,27 @@ https://github.com/sponsors/rust-analyzer[GitHub Sponsors]. | |||
52 | ); | 50 | ); |
53 | 51 | ||
54 | let path = changelog_dir.join(format!("{}-changelog-{}.adoc", today, changelog_n)); | 52 | let path = changelog_dir.join(format!("{}-changelog-{}.adoc", today, changelog_n)); |
55 | fs2::write(&path, &contents)?; | 53 | write_file(&path, &contents)?; |
56 | 54 | ||
57 | for &adoc in ["manual.adoc", "generated_features.adoc", "generated_assists.adoc"].iter() { | 55 | for &adoc in [ |
56 | "manual.adoc", | ||
57 | "generated_features.adoc", | ||
58 | "generated_assists.adoc", | ||
59 | "generated_diagnostic.adoc", | ||
60 | ] | ||
61 | .iter() | ||
62 | { | ||
58 | let src = project_root().join("./docs/user/").join(adoc); | 63 | let src = project_root().join("./docs/user/").join(adoc); |
59 | let dst = website_root.join(adoc); | 64 | let dst = website_root.join(adoc); |
60 | fs2::copy(src, dst)?; | 65 | cp(src, dst)?; |
61 | } | 66 | } |
62 | 67 | ||
63 | let tags = run!("git tag --list"; echo = false)?; | 68 | let tags = cmd!("git tag --list").read()?; |
64 | let prev_tag = tags.lines().filter(|line| is_release_tag(line)).last().unwrap(); | 69 | let prev_tag = tags.lines().filter(|line| is_release_tag(line)).last().unwrap(); |
65 | 70 | ||
66 | let git_log = run!("git log {}..HEAD --merges --reverse", prev_tag; echo = false)?; | 71 | let git_log = cmd!("git log {prev_tag}..HEAD --merges --reverse").read()?; |
67 | let git_log_dst = website_root.join("git.log"); | 72 | let git_log_dst = website_root.join("git.log"); |
68 | fs2::write(git_log_dst, &git_log)?; | 73 | write_file(git_log_dst, &git_log)?; |
69 | 74 | ||
70 | Ok(()) | 75 | Ok(()) |
71 | } | 76 | } |
@@ -77,27 +82,25 @@ pub struct PromoteCmd { | |||
77 | 82 | ||
78 | impl PromoteCmd { | 83 | impl PromoteCmd { |
79 | pub fn run(self) -> Result<()> { | 84 | pub fn run(self) -> Result<()> { |
80 | let _dir = pushd("../rust-rust-analyzer"); | 85 | let _dir = pushd("../rust-rust-analyzer")?; |
81 | run!("git switch master")?; | 86 | cmd!("git switch master").run()?; |
82 | run!("git fetch upstream")?; | 87 | cmd!("git fetch upstream").run()?; |
83 | run!("git reset --hard upstream/master")?; | 88 | cmd!("git reset --hard upstream/master").run()?; |
84 | run!("git submodule update --recursive")?; | 89 | cmd!("git submodule update --recursive").run()?; |
85 | 90 | ||
86 | let branch = format!("rust-analyzer-{}", date_iso()?); | 91 | let branch = format!("rust-analyzer-{}", date_iso()?); |
87 | run!("git switch -c {}", branch)?; | 92 | cmd!("git switch -c {branch}").run()?; |
88 | { | 93 | { |
89 | let _dir = pushd("src/tools/rust-analyzer"); | 94 | let _dir = pushd("src/tools/rust-analyzer")?; |
90 | run!("git fetch origin")?; | 95 | cmd!("git fetch origin").run()?; |
91 | run!("git reset --hard origin/release")?; | 96 | cmd!("git reset --hard origin/release").run()?; |
92 | } | 97 | } |
93 | run!("git add src/tools/rust-analyzer")?; | 98 | cmd!("git add src/tools/rust-analyzer").run()?; |
94 | run!("git commit -m':arrow_up: rust-analyzer'")?; | 99 | cmd!("git commit -m':arrow_up: rust-analyzer'").run()?; |
95 | if !self.dry_run { | 100 | if !self.dry_run { |
96 | run!("git push")?; | 101 | cmd!("git push").run()?; |
97 | run!( | 102 | cmd!("xdg-open https://github.com/matklad/rust/pull/new/{branch}?body=r%3F%20%40ghost") |
98 | "xdg-open https://github.com/matklad/rust/pull/new/{}?body=r%3F%20%40ghost", | 103 | .run()?; |
99 | branch | ||
100 | )?; | ||
101 | } | 104 | } |
102 | Ok(()) | 105 | Ok(()) |
103 | } | 106 | } |
diff --git a/xtask/tests/tidy.rs b/xtask/tests/tidy.rs index b3bb9d543..9de60c76c 100644 --- a/xtask/tests/tidy.rs +++ b/xtask/tests/tidy.rs | |||
@@ -3,9 +3,9 @@ use std::{ | |||
3 | path::{Path, PathBuf}, | 3 | path::{Path, PathBuf}, |
4 | }; | 4 | }; |
5 | 5 | ||
6 | use xshell::{cmd, read_file}; | ||
6 | use xtask::{ | 7 | use xtask::{ |
7 | codegen::{self, Mode}, | 8 | codegen::{self, Mode}, |
8 | not_bash::{fs2, run}, | ||
9 | project_root, run_rustfmt, rust_files, | 9 | project_root, run_rustfmt, rust_files, |
10 | }; | 10 | }; |
11 | 11 | ||
@@ -42,20 +42,20 @@ fn smoke_test_docs_generation() { | |||
42 | // We don't commit docs to the repo, so we can just overwrite in tests. | 42 | // We don't commit docs to the repo, so we can just overwrite in tests. |
43 | codegen::generate_assists_docs(Mode::Overwrite).unwrap(); | 43 | codegen::generate_assists_docs(Mode::Overwrite).unwrap(); |
44 | codegen::generate_feature_docs(Mode::Overwrite).unwrap(); | 44 | codegen::generate_feature_docs(Mode::Overwrite).unwrap(); |
45 | codegen::generate_diagnostic_docs(Mode::Overwrite).unwrap(); | ||
45 | } | 46 | } |
46 | 47 | ||
47 | #[test] | 48 | #[test] |
48 | fn check_lsp_extensions_docs() { | 49 | fn check_lsp_extensions_docs() { |
49 | let expected_hash = { | 50 | let expected_hash = { |
50 | let lsp_ext_rs = | 51 | let lsp_ext_rs = |
51 | fs2::read_to_string(project_root().join("crates/rust-analyzer/src/lsp_ext.rs")) | 52 | read_file(project_root().join("crates/rust-analyzer/src/lsp_ext.rs")).unwrap(); |
52 | .unwrap(); | ||
53 | stable_hash(lsp_ext_rs.as_str()) | 53 | stable_hash(lsp_ext_rs.as_str()) |
54 | }; | 54 | }; |
55 | 55 | ||
56 | let actual_hash = { | 56 | let actual_hash = { |
57 | let lsp_extensions_md = | 57 | let lsp_extensions_md = |
58 | fs2::read_to_string(project_root().join("docs/dev/lsp-extensions.md")).unwrap(); | 58 | read_file(project_root().join("docs/dev/lsp-extensions.md")).unwrap(); |
59 | let text = lsp_extensions_md | 59 | let text = lsp_extensions_md |
60 | .lines() | 60 | .lines() |
61 | .find_map(|line| line.strip_prefix("lsp_ext.rs hash:")) | 61 | .find_map(|line| line.strip_prefix("lsp_ext.rs hash:")) |
@@ -83,7 +83,7 @@ Please adjust docs/dev/lsp-extensions.md. | |||
83 | fn rust_files_are_tidy() { | 83 | fn rust_files_are_tidy() { |
84 | let mut tidy_docs = TidyDocs::default(); | 84 | let mut tidy_docs = TidyDocs::default(); |
85 | for path in rust_files(&project_root().join("crates")) { | 85 | for path in rust_files(&project_root().join("crates")) { |
86 | let text = fs2::read_to_string(&path).unwrap(); | 86 | let text = read_file(&path).unwrap(); |
87 | check_todo(&path, &text); | 87 | check_todo(&path, &text); |
88 | check_trailing_ws(&path, &text); | 88 | check_trailing_ws(&path, &text); |
89 | deny_clippy(&path, &text); | 89 | deny_clippy(&path, &text); |
@@ -94,8 +94,10 @@ fn rust_files_are_tidy() { | |||
94 | 94 | ||
95 | #[test] | 95 | #[test] |
96 | fn check_merge_commits() { | 96 | fn check_merge_commits() { |
97 | let stdout = run!("git rev-list --merges --invert-grep --author 'bors\\[bot\\]' HEAD~19.."; echo = false) | 97 | let stdout = |
98 | .unwrap(); | 98 | dbg!(cmd!("git rev-list --merges --invert-grep --author 'bors\\[bot\\]' HEAD~19..")) |
99 | .read() | ||
100 | .unwrap(); | ||
99 | if !stdout.is_empty() { | 101 | if !stdout.is_empty() { |
100 | panic!( | 102 | panic!( |
101 | " | 103 | " |
@@ -129,6 +131,14 @@ https://github.blog/2015-06-08-how-to-undo-almost-anything-with-git/#redo-after- | |||
129 | } | 131 | } |
130 | 132 | ||
131 | fn deny_clippy(path: &PathBuf, text: &String) { | 133 | fn deny_clippy(path: &PathBuf, text: &String) { |
134 | let ignore = &[ | ||
135 | // The documentation in string literals may contain anything for its own purposes | ||
136 | "completion/src/generated_lint_completions.rs", | ||
137 | ]; | ||
138 | if ignore.iter().any(|p| path.ends_with(p)) { | ||
139 | return; | ||
140 | } | ||
141 | |||
132 | if text.contains("[\u{61}llow(clippy") { | 142 | if text.contains("[\u{61}llow(clippy") { |
133 | panic!( | 143 | panic!( |
134 | "\n\nallowing lints is forbidden: {}. | 144 | "\n\nallowing lints is forbidden: {}. |
@@ -168,7 +178,7 @@ Zlib OR Apache-2.0 OR MIT | |||
168 | .filter(|it| !it.is_empty()) | 178 | .filter(|it| !it.is_empty()) |
169 | .collect::<Vec<_>>(); | 179 | .collect::<Vec<_>>(); |
170 | 180 | ||
171 | let meta = run!("cargo metadata --format-version 1"; echo = false).unwrap(); | 181 | let meta = cmd!("cargo metadata --format-version 1").read().unwrap(); |
172 | let mut licenses = meta | 182 | let mut licenses = meta |
173 | .split(|c| c == ',' || c == '{' || c == '}') | 183 | .split(|c| c == ',' || c == '{' || c == '}') |
174 | .filter(|it| it.contains(r#""license""#)) | 184 | .filter(|it| it.contains(r#""license""#)) |
@@ -177,6 +187,25 @@ Zlib OR Apache-2.0 OR MIT | |||
177 | .collect::<Vec<_>>(); | 187 | .collect::<Vec<_>>(); |
178 | licenses.sort(); | 188 | licenses.sort(); |
179 | licenses.dedup(); | 189 | licenses.dedup(); |
190 | if licenses != expected { | ||
191 | let mut diff = String::new(); | ||
192 | |||
193 | diff += &format!("New Licenses:\n"); | ||
194 | for &l in licenses.iter() { | ||
195 | if !expected.contains(&l) { | ||
196 | diff += &format!(" {}\n", l) | ||
197 | } | ||
198 | } | ||
199 | |||
200 | diff += &format!("\nMissing Licenses:\n"); | ||
201 | for &l in expected.iter() { | ||
202 | if !licenses.contains(&l) { | ||
203 | diff += &format!(" {}\n", l) | ||
204 | } | ||
205 | } | ||
206 | |||
207 | panic!("different set of licenses!\n{}", diff); | ||
208 | } | ||
180 | assert_eq!(licenses, expected); | 209 | assert_eq!(licenses, expected); |
181 | } | 210 | } |
182 | 211 | ||
@@ -193,7 +222,7 @@ fn check_todo(path: &Path, text: &str) { | |||
193 | // `ast::make`. | 222 | // `ast::make`. |
194 | "ast/make.rs", | 223 | "ast/make.rs", |
195 | // The documentation in string literals may contain anything for its own purposes | 224 | // The documentation in string literals may contain anything for its own purposes |
196 | "completion/generated_features.rs", | 225 | "completion/src/generated_lint_completions.rs", |
197 | ]; | 226 | ]; |
198 | if need_todo.iter().any(|p| path.ends_with(p)) { | 227 | if need_todo.iter().any(|p| path.ends_with(p)) { |
199 | return; | 228 | return; |