aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/ISSUE_TEMPLATE/bug_report.md5
-rw-r--r--.github/ISSUE_TEMPLATE/critical_nightly_regression.md17
-rw-r--r--.github/workflows/ci.yaml2
-rw-r--r--.github/workflows/release.yaml9
-rw-r--r--Cargo.lock114
-rw-r--r--crates/base_db/src/fixture.rs8
-rw-r--r--crates/base_db/src/input.rs1
-rw-r--r--crates/flycheck/Cargo.toml1
-rw-r--r--crates/flycheck/src/lib.rs68
-rw-r--r--crates/hir/src/display.rs2
-rw-r--r--crates/hir/src/lib.rs48
-rw-r--r--crates/hir/src/semantics.rs7
-rw-r--r--crates/hir/src/source_analyzer.rs9
-rw-r--r--crates/hir_def/src/attr.rs45
-rw-r--r--crates/hir_def/src/body.rs26
-rw-r--r--crates/hir_def/src/body/lower.rs76
-rw-r--r--crates/hir_def/src/body/tests.rs10
-rw-r--r--crates/hir_def/src/body/tests/block.rs24
-rw-r--r--crates/hir_def/src/child_by_source.rs4
-rw-r--r--crates/hir_def/src/diagnostics.rs5
-rw-r--r--crates/hir_def/src/find_path.rs695
-rw-r--r--crates/hir_def/src/item_tree.rs17
-rw-r--r--crates/hir_def/src/item_tree/lower.rs2
-rw-r--r--crates/hir_def/src/lib.rs53
-rw-r--r--crates/hir_def/src/nameres.rs55
-rw-r--r--crates/hir_def/src/nameres/collector.rs34
-rw-r--r--crates/hir_def/src/nameres/path_resolution.rs59
-rw-r--r--crates/hir_def/src/nameres/tests/diagnostics.rs4
-rw-r--r--crates/hir_def/src/path.rs7
-rw-r--r--crates/hir_def/src/path/lower.rs17
-rw-r--r--crates/hir_def/src/test_db.rs51
-rw-r--r--crates/hir_def/src/type_ref.rs18
-rw-r--r--crates/hir_def/src/visibility.rs10
-rw-r--r--crates/hir_expand/src/builtin_derive.rs10
-rw-r--r--crates/hir_expand/src/builtin_macro.rs17
-rw-r--r--crates/hir_expand/src/db.rs2
-rw-r--r--crates/hir_expand/src/eager.rs24
-rw-r--r--crates/hir_expand/src/lib.rs21
-rw-r--r--crates/hir_expand/src/name.rs1
-rw-r--r--crates/hir_ty/Cargo.toml6
-rw-r--r--crates/hir_ty/src/autoderef.rs46
-rw-r--r--crates/hir_ty/src/chalk_cast.rs16
-rw-r--r--crates/hir_ty/src/chalk_db.rs (renamed from crates/hir_ty/src/traits/chalk.rs)152
-rw-r--r--crates/hir_ty/src/chalk_ext.rs2
-rw-r--r--crates/hir_ty/src/db.rs72
-rw-r--r--crates/hir_ty/src/diagnostics.rs2
-rw-r--r--crates/hir_ty/src/diagnostics/decl_check.rs169
-rw-r--r--crates/hir_ty/src/display.rs49
-rw-r--r--crates/hir_ty/src/infer/expr.rs9
-rw-r--r--crates/hir_ty/src/infer/pat.rs4
-rw-r--r--crates/hir_ty/src/infer/path.rs2
-rw-r--r--crates/hir_ty/src/infer/unify.rs4
-rw-r--r--crates/hir_ty/src/interner.rs (renamed from crates/hir_ty/src/traits/chalk/interner.rs)127
-rw-r--r--crates/hir_ty/src/lib.rs113
-rw-r--r--crates/hir_ty/src/lower.rs110
-rw-r--r--crates/hir_ty/src/mapping.rs154
-rw-r--r--crates/hir_ty/src/method_resolution.rs117
-rw-r--r--crates/hir_ty/src/op.rs58
-rw-r--r--crates/hir_ty/src/primitive.rs5
-rw-r--r--crates/hir_ty/src/tests/macros.rs201
-rw-r--r--crates/hir_ty/src/tests/method_resolution.rs37
-rw-r--r--crates/hir_ty/src/tests/patterns.rs28
-rw-r--r--crates/hir_ty/src/tests/regression.rs76
-rw-r--r--crates/hir_ty/src/tests/simple.rs54
-rw-r--r--crates/hir_ty/src/tests/traits.rs1467
-rw-r--r--crates/hir_ty/src/tls.rs (renamed from crates/hir_ty/src/traits/chalk/tls.rs)14
-rw-r--r--crates/hir_ty/src/traits.rs18
-rw-r--r--crates/hir_ty/src/traits/chalk/mapping.rs131
-rw-r--r--crates/hir_ty/src/utils.rs54
-rw-r--r--crates/ide/src/diagnostics.rs157
-rw-r--r--crates/ide/src/diagnostics/field_shorthand.rs8
-rw-r--r--crates/ide/src/diagnostics/fixes.rs60
-rw-r--r--crates/ide/src/diagnostics/unlinked_file.rs14
-rw-r--r--crates/ide/src/display/navigation_target.rs8
-rw-r--r--crates/ide/src/doc_links.rs58
-rw-r--r--crates/ide/src/expand_macro.rs23
-rw-r--r--crates/ide/src/goto_definition.rs44
-rw-r--r--crates/ide/src/lib.rs42
-rw-r--r--crates/ide/src/move_item.rs100
-rw-r--r--crates/ide/src/prime_caches.rs4
-rw-r--r--crates/ide/src/references/rename.rs103
-rw-r--r--crates/ide/src/runnables.rs6
-rw-r--r--crates/ide/src/syntax_highlighting/highlight.rs196
-rw-r--r--crates/ide/src/syntax_highlighting/inject.rs16
-rw-r--r--crates/ide/src/syntax_highlighting/tags.rs75
-rw-r--r--crates/ide/src/syntax_highlighting/test_data/highlight_assoc_functions.html12
-rw-r--r--crates/ide/src/syntax_highlighting/test_data/highlight_doctest.html14
-rw-r--r--crates/ide/src/syntax_highlighting/test_data/highlight_injection.html2
-rw-r--r--crates/ide/src/syntax_highlighting/test_data/highlight_unsafe.html6
-rw-r--r--crates/ide/src/syntax_highlighting/test_data/highlighting.html34
-rw-r--r--crates/ide/src/syntax_highlighting/tests.rs36
-rw-r--r--crates/ide/src/typing.rs200
-rw-r--r--crates/ide/src/typing/on_enter.rs230
-rw-r--r--crates/ide_assists/src/ast_transform.rs33
-rw-r--r--crates/ide_assists/src/handlers/auto_import.rs43
-rw-r--r--crates/ide_assists/src/handlers/convert_tuple_struct_to_named_struct.rs516
-rw-r--r--crates/ide_assists/src/handlers/extract_function.rs278
-rw-r--r--crates/ide_assists/src/handlers/extract_struct_from_enum_variant.rs208
-rw-r--r--crates/ide_assists/src/handlers/fill_match_arms.rs370
-rw-r--r--crates/ide_assists/src/handlers/flip_comma.rs18
-rw-r--r--crates/ide_assists/src/handlers/generate_deref.rs227
-rw-r--r--crates/ide_assists/src/handlers/generate_from_impl_for_enum.rs2
-rw-r--r--crates/ide_assists/src/handlers/inline_local_variable.rs223
-rw-r--r--crates/ide_assists/src/handlers/introduce_named_lifetime.rs112
-rw-r--r--crates/ide_assists/src/handlers/merge_imports.rs2
-rw-r--r--crates/ide_assists/src/handlers/remove_dbg.rs2
-rw-r--r--crates/ide_assists/src/handlers/reorder_fields.rs8
-rw-r--r--crates/ide_assists/src/handlers/reorder_impl.rs20
-rw-r--r--crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs108
-rw-r--r--crates/ide_assists/src/handlers/replace_qualified_name_with_use.rs34
-rw-r--r--crates/ide_assists/src/lib.rs6
-rw-r--r--crates/ide_assists/src/tests.rs12
-rw-r--r--crates/ide_assists/src/tests/generated.rs68
-rw-r--r--crates/ide_assists/src/utils.rs3
-rw-r--r--crates/ide_assists/src/utils/suggest_name.rs2
-rw-r--r--crates/ide_completion/src/completions/flyimport.rs75
-rw-r--r--crates/ide_completion/src/completions/postfix/format_like.rs2
-rw-r--r--crates/ide_completion/src/context.rs4
-rw-r--r--crates/ide_completion/src/item.rs10
-rw-r--r--crates/ide_completion/src/lib.rs2
-rw-r--r--crates/ide_completion/src/render/enum_variant.rs2
-rw-r--r--crates/ide_completion/src/test_utils.rs5
-rw-r--r--crates/ide_db/src/apply_change.rs2
-rw-r--r--crates/ide_db/src/call_info.rs10
-rw-r--r--crates/ide_db/src/call_info/tests.rs27
-rw-r--r--crates/ide_db/src/helpers.rs8
-rw-r--r--crates/ide_db/src/helpers/famous_defs_fixture.rs8
-rw-r--r--crates/ide_db/src/helpers/import_assets.rs22
-rw-r--r--crates/ide_db/src/helpers/insert_use.rs587
-rw-r--r--crates/ide_db/src/helpers/insert_use/tests.rs42
-rw-r--r--crates/ide_db/src/helpers/merge_imports.rs309
-rw-r--r--crates/ide_db/src/helpers/rust_doc.rs34
-rw-r--r--crates/ide_db/src/search.rs58
-rw-r--r--crates/mbe/src/syntax_bridge.rs2
-rw-r--r--crates/mbe/src/tests/expand.rs42
-rw-r--r--crates/parser/src/grammar.rs37
-rw-r--r--crates/parser/src/grammar/attributes.rs28
-rw-r--r--crates/parser/src/grammar/patterns.rs6
-rw-r--r--crates/parser/src/grammar/type_args.rs41
-rw-r--r--crates/parser/src/grammar/type_params.rs10
-rw-r--r--crates/parser/src/grammar/types.rs10
-rw-r--r--crates/proc_macro_api/Cargo.toml7
-rw-r--r--crates/proc_macro_api/src/lib.rs1
-rw-r--r--crates/project_model/src/build_data.rs256
-rw-r--r--crates/rust-analyzer/Cargo.toml2
-rw-r--r--crates/rust-analyzer/build.rs61
-rw-r--r--crates/rust-analyzer/src/benchmarks.rs7
-rw-r--r--crates/rust-analyzer/src/bin/main.rs15
-rw-r--r--crates/rust-analyzer/src/bin/rustc_wrapper.rs46
-rw-r--r--crates/rust-analyzer/src/cli/analysis_stats.rs1
-rw-r--r--crates/rust-analyzer/src/cli/diagnostics.rs6
-rw-r--r--crates/rust-analyzer/src/cli/load_cargo.rs10
-rw-r--r--crates/rust-analyzer/src/cli/ssr.rs9
-rw-r--r--crates/rust-analyzer/src/config.rs47
-rw-r--r--crates/rust-analyzer/src/diagnostics.rs1
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt1
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt1
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt1
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt1
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt1
-rw-r--r--crates/rust-analyzer/src/diagnostics/to_proto.rs57
-rw-r--r--crates/rust-analyzer/src/from_proto.rs30
-rw-r--r--crates/rust-analyzer/src/global_state.rs2
-rw-r--r--crates/rust-analyzer/src/handlers.rs114
-rw-r--r--crates/rust-analyzer/src/lsp_ext.rs8
-rw-r--r--crates/rust-analyzer/src/lsp_utils.rs24
-rw-r--r--crates/rust-analyzer/src/main_loop.rs45
-rw-r--r--crates/rust-analyzer/src/markdown.rs22
-rw-r--r--crates/rust-analyzer/src/reload.rs16
-rw-r--r--crates/rust-analyzer/src/semantic_tokens.rs5
-rw-r--r--crates/rust-analyzer/src/to_proto.rs182
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/main.rs2
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/support.rs21
-rw-r--r--crates/stdx/Cargo.toml5
-rw-r--r--crates/stdx/src/lib.rs42
-rw-r--r--crates/stdx/src/process.rs238
-rw-r--r--crates/syntax/Cargo.toml4
-rw-r--r--crates/syntax/src/algo.rs19
-rw-r--r--crates/syntax/src/ast/edit_in_place.rs153
-rw-r--r--crates/syntax/src/ast/make.rs53
-rw-r--r--crates/syntax/src/ast/node_ext.rs34
-rw-r--r--crates/syntax/src/ted.rs24
-rw-r--r--crates/syntax/src/validation/block.rs2
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0117_macro_call_type.rast48
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0145_record_pat_field.rast58
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0145_record_pat_field.rs1
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0164_const_generic_negated_literal.rast30
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0164_const_generic_negated_literal.rs1
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0165_const_param_defaults.rast96
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0165_const_param_defaults.rs3
-rw-r--r--crates/syntax/test_data/parser/ok/0045_block_attrs.rast218
-rw-r--r--crates/syntax/test_data/parser/ok/0045_block_attrs.rs (renamed from crates/syntax/test_data/parser/ok/0045_block_inner_attrs.rs)6
-rw-r--r--crates/syntax/test_data/parser/ok/0045_block_inner_attrs.rast178
-rw-r--r--crates/test_utils/src/assert_linear.rs112
-rw-r--r--crates/test_utils/src/bench_fixture.rs3
-rw-r--r--crates/test_utils/src/lib.rs3
-rw-r--r--docs/dev/README.md33
-rw-r--r--docs/dev/lsp-extensions.md20
-rw-r--r--docs/dev/style.md21
-rw-r--r--docs/user/generated_config.adoc12
-rw-r--r--docs/user/manual.adoc76
-rw-r--r--editors/code/language-configuration.json3
-rw-r--r--editors/code/package-lock.json891
-rw-r--r--editors/code/package.json20
-rw-r--r--editors/code/src/commands.ts26
-rw-r--r--editors/code/src/config.ts9
-rw-r--r--editors/code/src/debug.ts14
-rw-r--r--editors/code/src/inlay_hints.ts52
-rw-r--r--editors/code/src/lsp_ext.ts2
-rw-r--r--editors/code/src/toolchain.ts20
-rw-r--r--editors/code/src/util.ts21
-rw-r--r--xtask/src/dist.rs34
-rw-r--r--xtask/src/flags.rs9
-rw-r--r--xtask/src/main.rs8
-rw-r--r--xtask/src/release.rs50
-rw-r--r--xtask/src/release/changelog.rs159
-rw-r--r--xtask/src/tidy.rs2
217 files changed, 9466 insertions, 4350 deletions
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index b5160eaa3..060a05d41 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -14,8 +14,9 @@ Forum for questions: https://users.rust-lang.org/c/ide/14
14Before submitting, please make sure that you're not running into one of these known issues: 14Before submitting, please make sure that you're not running into one of these known issues:
15 15
16 1. on-the-fly diagnostics are mostly unimplemented (`cargo check` diagnostics will be shown when saving a file) 16 1. on-the-fly diagnostics are mostly unimplemented (`cargo check` diagnostics will be shown when saving a file)
17 2. some settings are required for procedural macro and build script support (`rust-analyzer.cargo.loadOutDirsFromCheck`, `rust-analyzer.procMacro.enable`): #6448 17 2. some platform-specific imports are not resolved: #6038
18 3. some platform-specific imports are not resolved: #6038 18 3. attribute proc macros are not supported: #6029
19 4. the version string is misleading (includes the previous week): #8571
19 20
20Otherwise please try to provide information which will help us to fix the issue faster. Minimal reproducible examples with few dependencies are especially lovely <3. 21Otherwise please try to provide information which will help us to fix the issue faster. Minimal reproducible examples with few dependencies are especially lovely <3.
21--> 22-->
diff --git a/.github/ISSUE_TEMPLATE/critical_nightly_regression.md b/.github/ISSUE_TEMPLATE/critical_nightly_regression.md
new file mode 100644
index 000000000..a0b1627d7
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/critical_nightly_regression.md
@@ -0,0 +1,17 @@
1---
2name: Critical Nightly Regression
3about: You are using nightly rust-analyzer and the latest version is unusable.
4title: ''
5labels: ''
6assignees: 'matklad'
7
8---
9
10<!--
11Troubleshooting guide: https://rust-analyzer.github.io/manual.html#troubleshooting
12
13Please try to provide information which will help us to fix the issue faster. Minimal reproducible examples with few dependencies are especially lovely <3.
14-->
15
16This is a serious regression in nightly and it's important to fix it before the next release.
17@matklad, please take a look.
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 1145fcfab..63518e67f 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -57,7 +57,7 @@ jobs:
57 run: cargo test --no-run --locked 57 run: cargo test --no-run --locked
58 58
59 - name: Test 59 - name: Test
60 run: cargo test 60 run: cargo test -- --nocapture
61 61
62 # Weird targets to catch non-portable code 62 # Weird targets to catch non-portable code
63 rust-cross: 63 rust-cross:
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index 307096ef3..d5c93f69b 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -109,12 +109,7 @@ jobs:
109 node-version: 12.x 109 node-version: 12.x
110 110
111 - name: Dist 111 - name: Dist
112 if: github.ref == 'refs/heads/release' 112 run: cargo xtask dist --client-patch-version $GITHUB_RUN_NUMBER
113 run: cargo xtask dist --client 0.2.$GITHUB_RUN_NUMBER
114
115 - name: Dist
116 if: github.ref != 'refs/heads/release'
117 run: cargo xtask dist --nightly --client 0.3.$GITHUB_RUN_NUMBER-nightly
118 113
119 - name: Run analysis-stats on rust-analyzer 114 - name: Run analysis-stats on rust-analyzer
120 run: target/${{ env.RA_TARGET }}/release/rust-analyzer analysis-stats . 115 run: target/${{ env.RA_TARGET }}/release/rust-analyzer analysis-stats .
@@ -266,7 +261,7 @@ jobs:
266 with: 261 with:
267 node-version: 12.x 262 node-version: 12.x
268 263
269 - run: echo "TAG=$(date --iso --utc)" >> $GITHUB_ENV 264 - run: echo "TAG=$(date --iso -u)" >> $GITHUB_ENV
270 if: github.ref == 'refs/heads/release' 265 if: github.ref == 'refs/heads/release'
271 - run: echo "TAG=nightly" >> $GITHUB_ENV 266 - run: echo "TAG=nightly" >> $GITHUB_ENV
272 if: github.ref != 'refs/heads/release' 267 if: github.ref != 'refs/heads/release'
diff --git a/Cargo.lock b/Cargo.lock
index d7e6d3ac8..1cfd704f6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -72,11 +72,12 @@ checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
72 72
73[[package]] 73[[package]]
74name = "backtrace" 74name = "backtrace"
75version = "0.3.56" 75version = "0.3.58"
76source = "registry+https://github.com/rust-lang/crates.io-index" 76source = "registry+https://github.com/rust-lang/crates.io-index"
77checksum = "9d117600f438b1707d4e4ae15d3595657288f8235a0eb593e80ecc98ab34e1bc" 77checksum = "88fb5a785d6b44fd9d6700935608639af1b8356de1e55d5f7c2740f4faa15d82"
78dependencies = [ 78dependencies = [
79 "addr2line", 79 "addr2line",
80 "cc",
80 "cfg-if", 81 "cfg-if",
81 "libc", 82 "libc",
82 "miniz_oxide", 83 "miniz_oxide",
@@ -168,9 +169,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
168 169
169[[package]] 170[[package]]
170name = "chalk-derive" 171name = "chalk-derive"
171version = "0.60.0" 172version = "0.64.0"
172source = "registry+https://github.com/rust-lang/crates.io-index" 173source = "registry+https://github.com/rust-lang/crates.io-index"
173checksum = "ab0f74445d4fbeaf0217bc1d23978cc73b95b28e8a738b81894580dd646822d2" 174checksum = "d9acf2a9eab79ae7d44cd77ad86a8b1569d7a5e6d9a7db4a0a57a7344dd82c24"
174dependencies = [ 175dependencies = [
175 "proc-macro2", 176 "proc-macro2",
176 "quote", 177 "quote",
@@ -180,9 +181,9 @@ dependencies = [
180 181
181[[package]] 182[[package]]
182name = "chalk-ir" 183name = "chalk-ir"
183version = "0.60.0" 184version = "0.64.0"
184source = "registry+https://github.com/rust-lang/crates.io-index" 185source = "registry+https://github.com/rust-lang/crates.io-index"
185checksum = "294b1fc6210a5b3bd06c1d01dda48a581e2cafec80b8d659139ce45456644be2" 186checksum = "877661627f54ba3666a72943c43b326cb170d60899e50a8426111e7a657ff032"
186dependencies = [ 187dependencies = [
187 "bitflags", 188 "bitflags",
188 "chalk-derive", 189 "chalk-derive",
@@ -191,9 +192,9 @@ dependencies = [
191 192
192[[package]] 193[[package]]
193name = "chalk-recursive" 194name = "chalk-recursive"
194version = "0.60.0" 195version = "0.64.0"
195source = "registry+https://github.com/rust-lang/crates.io-index" 196source = "registry+https://github.com/rust-lang/crates.io-index"
196checksum = "1b9386936070be4545bfa22b094b7065af79aa2aeaccc945438f1c5ffe74c30a" 197checksum = "072ffcf17243c2aa3e4b9ea6de3d29e7ef64cfdb0ceccaa431965070a1dc1475"
197dependencies = [ 198dependencies = [
198 "chalk-derive", 199 "chalk-derive",
199 "chalk-ir", 200 "chalk-ir",
@@ -204,9 +205,9 @@ dependencies = [
204 205
205[[package]] 206[[package]]
206name = "chalk-solve" 207name = "chalk-solve"
207version = "0.60.0" 208version = "0.64.0"
208source = "registry+https://github.com/rust-lang/crates.io-index" 209source = "registry+https://github.com/rust-lang/crates.io-index"
209checksum = "7c12a1ec7e850b50a049f27ef9cf5df3056bbd1acbb3eeb44d024e501a641f3a" 210checksum = "97d4920c9ef2b26dd0b98ffdf070e27fa31e0b6f637463132083cee597e3d326"
210dependencies = [ 211dependencies = [
211 "chalk-derive", 212 "chalk-derive",
212 "chalk-ir", 213 "chalk-ir",
@@ -259,9 +260,9 @@ dependencies = [
259 260
260[[package]] 261[[package]]
261name = "crossbeam-channel" 262name = "crossbeam-channel"
262version = "0.5.0" 263version = "0.5.1"
263source = "registry+https://github.com/rust-lang/crates.io-index" 264source = "registry+https://github.com/rust-lang/crates.io-index"
264checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" 265checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"
265dependencies = [ 266dependencies = [
266 "cfg-if", 267 "cfg-if",
267 "crossbeam-utils", 268 "crossbeam-utils",
@@ -280,9 +281,9 @@ dependencies = [
280 281
281[[package]] 282[[package]]
282name = "crossbeam-epoch" 283name = "crossbeam-epoch"
283version = "0.9.3" 284version = "0.9.4"
284source = "registry+https://github.com/rust-lang/crates.io-index" 285source = "registry+https://github.com/rust-lang/crates.io-index"
285checksum = "2584f639eb95fea8c798496315b297cf81b9b58b6d30ab066a75455333cf4b12" 286checksum = "52fb27eab85b17fbb9f6fd667089e07d6a2eb8743d02639ee7f6a7a7729c9c94"
286dependencies = [ 287dependencies = [
287 "cfg-if", 288 "cfg-if",
288 "crossbeam-utils", 289 "crossbeam-utils",
@@ -293,9 +294,9 @@ dependencies = [
293 294
294[[package]] 295[[package]]
295name = "crossbeam-utils" 296name = "crossbeam-utils"
296version = "0.8.3" 297version = "0.8.4"
297source = "registry+https://github.com/rust-lang/crates.io-index" 298source = "registry+https://github.com/rust-lang/crates.io-index"
298checksum = "e7e9d99fa91428effe99c5c6d4634cdeba32b8cf784fc428a2a687f61a952c49" 299checksum = "4feb231f0d4d6af81aed15928e58ecf5816aa62a2393e2c82f46973e92a9a278"
299dependencies = [ 300dependencies = [
300 "autocfg", 301 "autocfg",
301 "cfg-if", 302 "cfg-if",
@@ -396,6 +397,7 @@ dependencies = [
396 "crossbeam-channel", 397 "crossbeam-channel",
397 "jod-thread", 398 "jod-thread",
398 "log", 399 "log",
400 "serde",
399 "serde_json", 401 "serde_json",
400 "stdx", 402 "stdx",
401 "toolchain", 403 "toolchain",
@@ -684,9 +686,9 @@ dependencies = [
684 686
685[[package]] 687[[package]]
686name = "idna" 688name = "idna"
687version = "0.2.2" 689version = "0.2.3"
688source = "registry+https://github.com/rust-lang/crates.io-index" 690source = "registry+https://github.com/rust-lang/crates.io-index"
689checksum = "89829a5d69c23d348314a7ac337fe39173b61149a9864deabd260983aed48c21" 691checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8"
690dependencies = [ 692dependencies = [
691 "matches", 693 "matches",
692 "unicode-bidi", 694 "unicode-bidi",
@@ -797,9 +799,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
797 799
798[[package]] 800[[package]]
799name = "libc" 801name = "libc"
800version = "0.2.93" 802version = "0.2.94"
801source = "registry+https://github.com/rust-lang/crates.io-index" 803source = "registry+https://github.com/rust-lang/crates.io-index"
802checksum = "9385f66bf6105b241aa65a61cb923ef20efc665cb9f9bb50ac2f0c4b7f378d41" 804checksum = "18794a8ad5b29321f790b55d93dfba91e125cb1a9edbd4f8e3150acc771c1a5e"
803 805
804[[package]] 806[[package]]
805name = "libloading" 807name = "libloading"
@@ -822,9 +824,9 @@ dependencies = [
822 824
823[[package]] 825[[package]]
824name = "lock_api" 826name = "lock_api"
825version = "0.4.3" 827version = "0.4.4"
826source = "registry+https://github.com/rust-lang/crates.io-index" 828source = "registry+https://github.com/rust-lang/crates.io-index"
827checksum = "5a3c91c24eae6777794bb1997ad98bbb87daf92890acab859f7eaa4320333176" 829checksum = "0382880606dff6d15c9476c416d18690b72742aa7b605bb6dd6ec9030fbf07eb"
828dependencies = [ 830dependencies = [
829 "scopeguard", 831 "scopeguard",
830] 832]
@@ -840,9 +842,9 @@ dependencies = [
840 842
841[[package]] 843[[package]]
842name = "lsp-server" 844name = "lsp-server"
843version = "0.5.0" 845version = "0.5.1"
844source = "registry+https://github.com/rust-lang/crates.io-index" 846source = "registry+https://github.com/rust-lang/crates.io-index"
845checksum = "69b18dfe0e4a380b872aa79d8e0ee6c3d7a9682466e84b83ad807c88b3545f79" 847checksum = "6825d7042d5ca1825a366c40c9446928ec7b30e2be97243a13b164aee6583992"
846dependencies = [ 848dependencies = [
847 "crossbeam-channel", 849 "crossbeam-channel",
848 "log", 850 "log",
@@ -896,9 +898,9 @@ dependencies = [
896 898
897[[package]] 899[[package]]
898name = "memchr" 900name = "memchr"
899version = "2.3.4" 901version = "2.4.0"
900source = "registry+https://github.com/rust-lang/crates.io-index" 902source = "registry+https://github.com/rust-lang/crates.io-index"
901checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" 903checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc"
902 904
903[[package]] 905[[package]]
904name = "memmap" 906name = "memmap"
@@ -971,9 +973,9 @@ dependencies = [
971 973
972[[package]] 974[[package]]
973name = "notify" 975name = "notify"
974version = "5.0.0-pre.6" 976version = "5.0.0-pre.7"
975source = "registry+https://github.com/rust-lang/crates.io-index" 977source = "registry+https://github.com/rust-lang/crates.io-index"
976checksum = "e5fd82b93434edb9c00ae65ee741e0e081cdc8c63346ab9f687935a629aaf4c3" 978checksum = "1ebe7699a0f8c5759450716ee03d231685c22b4fe8f406c42c22e0ad94d40ce7"
977dependencies = [ 979dependencies = [
978 "anymap", 980 "anymap",
979 "bitflags", 981 "bitflags",
@@ -1107,9 +1109,9 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
1107 1109
1108[[package]] 1110[[package]]
1109name = "perf-event" 1111name = "perf-event"
1110version = "0.4.6" 1112version = "0.4.7"
1111source = "registry+https://github.com/rust-lang/crates.io-index" 1113source = "registry+https://github.com/rust-lang/crates.io-index"
1112checksum = "b7a1c2678a77d65edf773bd900f5b87f0944ac3421949842a2c6a4efe42d6c66" 1114checksum = "5396562cd2eaa828445d6d34258ae21ee1eb9d40fe626ca7f51c8dccb4af9d66"
1113dependencies = [ 1115dependencies = [
1114 "libc", 1116 "libc",
1115 "perf-event-open-sys", 1117 "perf-event-open-sys",
@@ -1174,6 +1176,7 @@ dependencies = [
1174 "log", 1176 "log",
1175 "memmap", 1177 "memmap",
1176 "object", 1178 "object",
1179 "profile",
1177 "serde", 1180 "serde",
1178 "serde_json", 1181 "serde_json",
1179 "snap", 1182 "snap",
@@ -1292,18 +1295,18 @@ dependencies = [
1292 1295
1293[[package]] 1296[[package]]
1294name = "redox_syscall" 1297name = "redox_syscall"
1295version = "0.2.5" 1298version = "0.2.7"
1296source = "registry+https://github.com/rust-lang/crates.io-index" 1299source = "registry+https://github.com/rust-lang/crates.io-index"
1297checksum = "94341e4e44e24f6b591b59e47a8a027df12e008d73fd5672dbea9cc22f4507d9" 1300checksum = "85dd92e586f7355c633911e11f77f3d12f04b1b1bd76a198bd34ae3af8341ef2"
1298dependencies = [ 1301dependencies = [
1299 "bitflags", 1302 "bitflags",
1300] 1303]
1301 1304
1302[[package]] 1305[[package]]
1303name = "regex" 1306name = "regex"
1304version = "1.4.5" 1307version = "1.5.3"
1305source = "registry+https://github.com/rust-lang/crates.io-index" 1308source = "registry+https://github.com/rust-lang/crates.io-index"
1306checksum = "957056ecddbeba1b26965114e191d2e8589ce74db242b6ea25fc4062427a5c19" 1309checksum = "ce5f1ceb7f74abbce32601642fcf8e8508a8a8991e0621c7d750295b9095702b"
1307dependencies = [ 1310dependencies = [
1308 "regex-syntax", 1311 "regex-syntax",
1309] 1312]
@@ -1320,9 +1323,9 @@ dependencies = [
1320 1323
1321[[package]] 1324[[package]]
1322name = "regex-syntax" 1325name = "regex-syntax"
1323version = "0.6.23" 1326version = "0.6.25"
1324source = "registry+https://github.com/rust-lang/crates.io-index" 1327source = "registry+https://github.com/rust-lang/crates.io-index"
1325checksum = "24d5f089152e60f62d28b835fbff2cd2e8dc0baf1ac13343bef92ab7eed84548" 1328checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
1326 1329
1327[[package]] 1330[[package]]
1328name = "rowan" 1331name = "rowan"
@@ -1391,9 +1394,9 @@ dependencies = [
1391 1394
1392[[package]] 1395[[package]]
1393name = "rustc-ap-rustc_lexer" 1396name = "rustc-ap-rustc_lexer"
1394version = "714.0.0" 1397version = "716.0.0"
1395source = "registry+https://github.com/rust-lang/crates.io-index" 1398source = "registry+https://github.com/rust-lang/crates.io-index"
1396checksum = "a35856f140bed0dc7c7d6ba2134099d337377a3a4e11bfc79bccabf1fd4c9d42" 1399checksum = "12eac7554c1d3f49f105f14d53c0f3402220e875983113562701d8e597a0995c"
1397dependencies = [ 1400dependencies = [
1398 "unicode-xid", 1401 "unicode-xid",
1399] 1402]
@@ -1563,9 +1566,9 @@ dependencies = [
1563 1566
1564[[package]] 1567[[package]]
1565name = "snap" 1568name = "snap"
1566version = "1.0.4" 1569version = "1.0.5"
1567source = "registry+https://github.com/rust-lang/crates.io-index" 1570source = "registry+https://github.com/rust-lang/crates.io-index"
1568checksum = "dc725476a1398f0480d56cd0ad381f6f32acf2642704456f8f59a35df464b59a" 1571checksum = "45456094d1983e2ee2a18fdfebce3189fa451699d0502cb8e3b49dba5ba41451"
1569 1572
1570[[package]] 1573[[package]]
1571name = "stdx" 1574name = "stdx"
@@ -1573,13 +1576,16 @@ version = "0.0.0"
1573dependencies = [ 1576dependencies = [
1574 "always-assert", 1577 "always-assert",
1575 "backtrace", 1578 "backtrace",
1579 "libc",
1580 "miow",
1581 "winapi",
1576] 1582]
1577 1583
1578[[package]] 1584[[package]]
1579name = "syn" 1585name = "syn"
1580version = "1.0.69" 1586version = "1.0.71"
1581source = "registry+https://github.com/rust-lang/crates.io-index" 1587source = "registry+https://github.com/rust-lang/crates.io-index"
1582checksum = "48fe99c6bd8b1cc636890bcc071842de909d902c81ac7dab53ba33c421ab8ffb" 1588checksum = "ad184cc9470f9117b2ac6817bfe297307418819ba40552f9b3846f05c33d5373"
1583dependencies = [ 1589dependencies = [
1584 "proc-macro2", 1590 "proc-macro2",
1585 "quote", 1591 "quote",
@@ -1697,9 +1703,9 @@ dependencies = [
1697 1703
1698[[package]] 1704[[package]]
1699name = "tracing" 1705name = "tracing"
1700version = "0.1.25" 1706version = "0.1.26"
1701source = "registry+https://github.com/rust-lang/crates.io-index" 1707source = "registry+https://github.com/rust-lang/crates.io-index"
1702checksum = "01ebdc2bb4498ab1ab5f5b73c5803825e60199229ccba0698170e3be0e7f959f" 1708checksum = "09adeb8c97449311ccd28a427f96fb563e7fd31aabf994189879d9da2394b89d"
1703dependencies = [ 1709dependencies = [
1704 "cfg-if", 1710 "cfg-if",
1705 "pin-project-lite", 1711 "pin-project-lite",
@@ -1720,9 +1726,9 @@ dependencies = [
1720 1726
1721[[package]] 1727[[package]]
1722name = "tracing-core" 1728name = "tracing-core"
1723version = "0.1.17" 1729version = "0.1.18"
1724source = "registry+https://github.com/rust-lang/crates.io-index" 1730source = "registry+https://github.com/rust-lang/crates.io-index"
1725checksum = "f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f" 1731checksum = "a9ff14f98b1a4b289c6248a023c1c2fa1491062964e9fed67ab29c4e4da4a052"
1726dependencies = [ 1732dependencies = [
1727 "lazy_static", 1733 "lazy_static",
1728] 1734]
@@ -1750,9 +1756,9 @@ dependencies = [
1750 1756
1751[[package]] 1757[[package]]
1752name = "tracing-subscriber" 1758name = "tracing-subscriber"
1753version = "0.2.17" 1759version = "0.2.18"
1754source = "registry+https://github.com/rust-lang/crates.io-index" 1760source = "registry+https://github.com/rust-lang/crates.io-index"
1755checksum = "705096c6f83bf68ea5d357a6aa01829ddbdac531b357b45abeca842938085baa" 1761checksum = "aa5553bf0883ba7c9cbe493b085c29926bd41b66afc31ff72cf17ff4fb60dcd5"
1756dependencies = [ 1762dependencies = [
1757 "ansi_term", 1763 "ansi_term",
1758 "chrono", 1764 "chrono",
@@ -1839,9 +1845,9 @@ checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796"
1839 1845
1840[[package]] 1846[[package]]
1841name = "unicode-xid" 1847name = "unicode-xid"
1842version = "0.2.1" 1848version = "0.2.2"
1843source = "registry+https://github.com/rust-lang/crates.io-index" 1849source = "registry+https://github.com/rust-lang/crates.io-index"
1844checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" 1850checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
1845 1851
1846[[package]] 1852[[package]]
1847name = "url" 1853name = "url"
@@ -1954,18 +1960,18 @@ dependencies = [
1954 1960
1955[[package]] 1961[[package]]
1956name = "xshell" 1962name = "xshell"
1957version = "0.1.9" 1963version = "0.1.10"
1958source = "registry+https://github.com/rust-lang/crates.io-index" 1964source = "registry+https://github.com/rust-lang/crates.io-index"
1959checksum = "6f18102278453c8f70ea5c514ac78cb4c73a0ef72a8273d17094b52f9584c0c1" 1965checksum = "aa25217c682f9f991d7889238a99e65eb8431c266d36e0f4e850a73773415473"
1960dependencies = [ 1966dependencies = [
1961 "xshell-macros", 1967 "xshell-macros",
1962] 1968]
1963 1969
1964[[package]] 1970[[package]]
1965name = "xshell-macros" 1971name = "xshell-macros"
1966version = "0.1.9" 1972version = "0.1.10"
1967source = "registry+https://github.com/rust-lang/crates.io-index" 1973source = "registry+https://github.com/rust-lang/crates.io-index"
1968checksum = "6093c460064572007f885facc70bb0ca5e40a83ea7ff8b16c1abbee56fd2e767" 1974checksum = "4404d53d2113af4fa31c58326eb7b37d6d7bf11ba87520787cddeaff45385c72"
1969 1975
1970[[package]] 1976[[package]]
1971name = "xtask" 1977name = "xtask"
diff --git a/crates/base_db/src/fixture.rs b/crates/base_db/src/fixture.rs
index 04e2be390..0132565e4 100644
--- a/crates/base_db/src/fixture.rs
+++ b/crates/base_db/src/fixture.rs
@@ -35,7 +35,7 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
35 fn with_position(ra_fixture: &str) -> (Self, FilePosition) { 35 fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
36 let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture); 36 let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
37 let offset = match range_or_offset { 37 let offset = match range_or_offset {
38 RangeOrOffset::Range(_) => panic!(), 38 RangeOrOffset::Range(_) => panic!("Expected a cursor position, got a range instead"),
39 RangeOrOffset::Offset(it) => it, 39 RangeOrOffset::Offset(it) => it,
40 }; 40 };
41 (db, FilePosition { file_id, offset }) 41 (db, FilePosition { file_id, offset })
@@ -45,7 +45,7 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
45 let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture); 45 let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
46 let range = match range_or_offset { 46 let range = match range_or_offset {
47 RangeOrOffset::Range(it) => it, 47 RangeOrOffset::Range(it) => it,
48 RangeOrOffset::Offset(_) => panic!(), 48 RangeOrOffset::Offset(_) => panic!("Expected a cursor range, got a position instead"),
49 }; 49 };
50 (db, FileRange { file_id, range }) 50 (db, FileRange { file_id, range })
51 } 51 }
@@ -54,7 +54,9 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
54 let fixture = ChangeFixture::parse(ra_fixture); 54 let fixture = ChangeFixture::parse(ra_fixture);
55 let mut db = Self::default(); 55 let mut db = Self::default();
56 fixture.change.apply(&mut db); 56 fixture.change.apply(&mut db);
57 let (file_id, range_or_offset) = fixture.file_position.unwrap(); 57 let (file_id, range_or_offset) = fixture
58 .file_position
59 .expect("Could not find file position in fixture. Did you forget to add an `$0`?");
58 (db, file_id, range_or_offset) 60 (db, file_id, range_or_offset)
59 } 61 }
60 62
diff --git a/crates/base_db/src/input.rs b/crates/base_db/src/input.rs
index 07628935f..0ef77ef5d 100644
--- a/crates/base_db/src/input.rs
+++ b/crates/base_db/src/input.rs
@@ -239,6 +239,7 @@ impl CrateGraph {
239 name: CrateName, 239 name: CrateName,
240 to: CrateId, 240 to: CrateId,
241 ) -> Result<(), CyclicDependenciesError> { 241 ) -> Result<(), CyclicDependenciesError> {
242 let _p = profile::span("add_dep");
242 if self.dfs_find(from, to, &mut FxHashSet::default()) { 243 if self.dfs_find(from, to, &mut FxHashSet::default()) {
243 return Err(CyclicDependenciesError { 244 return Err(CyclicDependenciesError {
244 from: (from, self[from].display_name.clone()), 245 from: (from, self[from].display_name.clone()),
diff --git a/crates/flycheck/Cargo.toml b/crates/flycheck/Cargo.toml
index 2a1a21b28..18b9ce7df 100644
--- a/crates/flycheck/Cargo.toml
+++ b/crates/flycheck/Cargo.toml
@@ -13,6 +13,7 @@ doctest = false
13crossbeam-channel = "0.5.0" 13crossbeam-channel = "0.5.0"
14log = "0.4.8" 14log = "0.4.8"
15cargo_metadata = "0.13" 15cargo_metadata = "0.13"
16serde = { version = "1.0.106", features = ["derive"] }
16serde_json = "1.0.48" 17serde_json = "1.0.48"
17jod-thread = "0.1.1" 18jod-thread = "0.1.1"
18 19
diff --git a/crates/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs
index e2a59497a..1682d8bde 100644
--- a/crates/flycheck/src/lib.rs
+++ b/crates/flycheck/src/lib.rs
@@ -4,13 +4,14 @@
4 4
5use std::{ 5use std::{
6 fmt, 6 fmt,
7 io::{self, BufReader}, 7 io::{self, BufRead, BufReader},
8 path::PathBuf, 8 path::PathBuf,
9 process::{self, Command, Stdio}, 9 process::{self, Command, Stdio},
10 time::Duration, 10 time::Duration,
11}; 11};
12 12
13use crossbeam_channel::{never, select, unbounded, Receiver, Sender}; 13use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
14use serde::Deserialize;
14use stdx::JodChild; 15use stdx::JodChild;
15 16
16pub use cargo_metadata::diagnostic::{ 17pub use cargo_metadata::diagnostic::{
@@ -128,7 +129,7 @@ struct FlycheckActor {
128 129
129enum Event { 130enum Event {
130 Restart(Restart), 131 Restart(Restart),
131 CheckEvent(Option<cargo_metadata::Message>), 132 CheckEvent(Option<CargoMessage>),
132} 133}
133 134
134impl FlycheckActor { 135impl FlycheckActor {
@@ -180,21 +181,16 @@ impl FlycheckActor {
180 self.progress(Progress::DidFinish(res)); 181 self.progress(Progress::DidFinish(res));
181 } 182 }
182 Event::CheckEvent(Some(message)) => match message { 183 Event::CheckEvent(Some(message)) => match message {
183 cargo_metadata::Message::CompilerArtifact(msg) => { 184 CargoMessage::CompilerArtifact(msg) => {
184 self.progress(Progress::DidCheckCrate(msg.target.name)); 185 self.progress(Progress::DidCheckCrate(msg.target.name));
185 } 186 }
186 187
187 cargo_metadata::Message::CompilerMessage(msg) => { 188 CargoMessage::Diagnostic(msg) => {
188 self.send(Message::AddDiagnostic { 189 self.send(Message::AddDiagnostic {
189 workspace_root: self.workspace_root.clone(), 190 workspace_root: self.workspace_root.clone(),
190 diagnostic: msg.message, 191 diagnostic: msg,
191 }); 192 });
192 } 193 }
193
194 cargo_metadata::Message::BuildScriptExecuted(_)
195 | cargo_metadata::Message::BuildFinished(_)
196 | cargo_metadata::Message::TextLine(_)
197 | _ => {}
198 }, 194 },
199 } 195 }
200 } 196 }
@@ -261,7 +257,7 @@ struct CargoHandle {
261 child: JodChild, 257 child: JodChild,
262 #[allow(unused)] 258 #[allow(unused)]
263 thread: jod_thread::JoinHandle<io::Result<bool>>, 259 thread: jod_thread::JoinHandle<io::Result<bool>>,
264 receiver: Receiver<cargo_metadata::Message>, 260 receiver: Receiver<CargoMessage>,
265} 261}
266 262
267impl CargoHandle { 263impl CargoHandle {
@@ -294,14 +290,11 @@ impl CargoHandle {
294 290
295struct CargoActor { 291struct CargoActor {
296 child_stdout: process::ChildStdout, 292 child_stdout: process::ChildStdout,
297 sender: Sender<cargo_metadata::Message>, 293 sender: Sender<CargoMessage>,
298} 294}
299 295
300impl CargoActor { 296impl CargoActor {
301 fn new( 297 fn new(child_stdout: process::ChildStdout, sender: Sender<CargoMessage>) -> CargoActor {
302 child_stdout: process::ChildStdout,
303 sender: Sender<cargo_metadata::Message>,
304 ) -> CargoActor {
305 CargoActor { child_stdout, sender } 298 CargoActor { child_stdout, sender }
306 } 299 }
307 fn run(self) -> io::Result<bool> { 300 fn run(self) -> io::Result<bool> {
@@ -315,7 +308,7 @@ impl CargoActor {
315 // erroneus output. 308 // erroneus output.
316 let stdout = BufReader::new(self.child_stdout); 309 let stdout = BufReader::new(self.child_stdout);
317 let mut read_at_least_one_message = false; 310 let mut read_at_least_one_message = false;
318 for message in cargo_metadata::Message::parse_stream(stdout) { 311 for message in stdout.lines() {
319 let message = match message { 312 let message = match message {
320 Ok(message) => message, 313 Ok(message) => message,
321 Err(err) => { 314 Err(err) => {
@@ -326,13 +319,44 @@ impl CargoActor {
326 319
327 read_at_least_one_message = true; 320 read_at_least_one_message = true;
328 321
329 // Skip certain kinds of messages to only spend time on what's useful 322 // Try to deserialize a message from Cargo or Rustc.
330 match &message { 323 let mut deserializer = serde_json::Deserializer::from_str(&message);
331 cargo_metadata::Message::CompilerArtifact(artifact) if artifact.fresh => (), 324 deserializer.disable_recursion_limit();
332 cargo_metadata::Message::BuildScriptExecuted(_) => (), 325 if let Ok(message) = JsonMessage::deserialize(&mut deserializer) {
333 _ => self.sender.send(message).unwrap(), 326 match message {
327 // Skip certain kinds of messages to only spend time on what's useful
328 JsonMessage::Cargo(message) => match message {
329 cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => {
330 self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap()
331 }
332 cargo_metadata::Message::CompilerMessage(msg) => {
333 self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap()
334 }
335
336 cargo_metadata::Message::CompilerArtifact(_)
337 | cargo_metadata::Message::BuildScriptExecuted(_)
338 | cargo_metadata::Message::BuildFinished(_)
339 | cargo_metadata::Message::TextLine(_)
340 | _ => (),
341 },
342 JsonMessage::Rustc(message) => {
343 self.sender.send(CargoMessage::Diagnostic(message)).unwrap()
344 }
345 }
334 } 346 }
335 } 347 }
336 Ok(read_at_least_one_message) 348 Ok(read_at_least_one_message)
337 } 349 }
338} 350}
351
352enum CargoMessage {
353 CompilerArtifact(cargo_metadata::Artifact),
354 Diagnostic(Diagnostic),
355}
356
357#[derive(Deserialize)]
358#[serde(untagged)]
359enum JsonMessage {
360 Cargo(cargo_metadata::Message),
361 Rustc(Diagnostic),
362}
diff --git a/crates/hir/src/display.rs b/crates/hir/src/display.rs
index 01a4d205f..508ac37c2 100644
--- a/crates/hir/src/display.rs
+++ b/crates/hir/src/display.rs
@@ -170,7 +170,7 @@ impl HirDisplay for Field {
170 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { 170 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
171 write_visibility(self.parent.module(f.db).id, self.visibility(f.db), f)?; 171 write_visibility(self.parent.module(f.db).id, self.visibility(f.db), f)?;
172 write!(f, "{}: ", self.name(f.db))?; 172 write!(f, "{}: ", self.name(f.db))?;
173 self.signature_ty(f.db).hir_fmt(f) 173 self.ty(f.db).hir_fmt(f)
174 } 174 }
175} 175}
176 176
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 817a01db1..d8ccfde0c 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -509,7 +509,7 @@ impl Field {
509 /// placeholder types for type parameters). This is good for showing 509 /// placeholder types for type parameters). This is good for showing
510 /// signature help, but not so good to actually get the type of the field 510 /// signature help, but not so good to actually get the type of the field
511 /// when you actually have a variable of the struct. 511 /// when you actually have a variable of the struct.
512 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type { 512 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
513 let var_id = self.parent.into(); 513 let var_id = self.parent.into();
514 let generic_def_id: GenericDefId = match self.parent { 514 let generic_def_id: GenericDefId = match self.parent {
515 VariantDef::Struct(it) => it.id.into(), 515 VariantDef::Struct(it) => it.id.into(),
@@ -1580,11 +1580,24 @@ impl Impl {
1580 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty)) 1580 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
1581 }; 1581 };
1582 1582
1583 let fp = TyFingerprint::for_inherent_impl(&ty);
1584 let fp = if let Some(fp) = fp {
1585 fp
1586 } else {
1587 return Vec::new();
1588 };
1589
1583 let mut all = Vec::new(); 1590 let mut all = Vec::new();
1584 def_crates.iter().for_each(|&id| { 1591 def_crates.iter().for_each(|&id| {
1585 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter)) 1592 all.extend(
1593 db.inherent_impls_in_crate(id)
1594 .for_self_ty(&ty)
1595 .into_iter()
1596 .cloned()
1597 .map(Self::from)
1598 .filter(filter),
1599 )
1586 }); 1600 });
1587 let fp = TyFingerprint::for_impl(&ty);
1588 for id in def_crates 1601 for id in def_crates
1589 .iter() 1602 .iter()
1590 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db)) 1603 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
@@ -1592,13 +1605,12 @@ impl Impl {
1592 .chain(def_crates.iter().copied()) 1605 .chain(def_crates.iter().copied())
1593 .unique() 1606 .unique()
1594 { 1607 {
1595 match fp { 1608 all.extend(
1596 Some(fp) => all.extend( 1609 db.trait_impls_in_crate(id)
1597 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter), 1610 .for_self_ty_without_blanket_impls(fp)
1598 ), 1611 .map(Self::from)
1599 None => all 1612 .filter(filter),
1600 .extend(db.trait_impls_in_crate(id).all_impls().map(Self::from).filter(filter)), 1613 );
1601 }
1602 } 1614 }
1603 all 1615 all
1604 } 1616 }
@@ -1825,7 +1837,7 @@ impl Type {
1825 Solution::Unique(s) => s 1837 Solution::Unique(s) => s
1826 .value 1838 .value
1827 .subst 1839 .subst
1828 .interned() 1840 .as_slice(&Interner)
1829 .first() 1841 .first()
1830 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone())), 1842 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone())),
1831 Solution::Ambig(_) => None, 1843 Solution::Ambig(_) => None,
@@ -1972,7 +1984,7 @@ impl Type {
1972 None 1984 None
1973 } 1985 }
1974 1986
1975 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ { 1987 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
1976 self.ty 1988 self.ty
1977 .strip_references() 1989 .strip_references()
1978 .as_adt() 1990 .as_adt()
@@ -2054,6 +2066,18 @@ impl Type {
2054 self.ty.dyn_trait().map(Into::into) 2066 self.ty.dyn_trait().map(Into::into)
2055 } 2067 }
2056 2068
2069 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2070 /// or an empty iterator otherwise.
2071 pub fn applicable_inherent_traits<'a>(
2072 &'a self,
2073 db: &'a dyn HirDatabase,
2074 ) -> impl Iterator<Item = Trait> + 'a {
2075 self.autoderef(db)
2076 .filter_map(|derefed_type| derefed_type.ty.dyn_trait())
2077 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2078 .map(Trait::from)
2079 }
2080
2057 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> { 2081 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2058 self.ty.impl_trait_bounds(db).map(|it| { 2082 self.ty.impl_trait_bounds(db).map(|it| {
2059 it.into_iter() 2083 it.into_iter()
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index 7955bf0b5..62500602a 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -6,10 +6,11 @@ use std::{cell::RefCell, fmt, iter::successors};
6 6
7use base_db::{FileId, FileRange}; 7use base_db::{FileId, FileRange};
8use hir_def::{ 8use hir_def::{
9 body,
9 resolver::{self, HasResolver, Resolver, TypeNs}, 10 resolver::{self, HasResolver, Resolver, TypeNs},
10 AsMacroCall, FunctionId, TraitId, VariantId, 11 AsMacroCall, FunctionId, TraitId, VariantId,
11}; 12};
12use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo}; 13use hir_expand::{name::AsName, ExpansionInfo};
13use hir_ty::associated_type_shorthand_candidates; 14use hir_ty::associated_type_shorthand_candidates;
14use itertools::Itertools; 15use itertools::Itertools;
15use rustc_hash::{FxHashMap, FxHashSet}; 16use rustc_hash::{FxHashMap, FxHashSet};
@@ -853,8 +854,8 @@ impl<'a> SemanticsScope<'a> {
853 /// Resolve a path as-if it was written at the given scope. This is 854 /// Resolve a path as-if it was written at the given scope. This is
854 /// necessary a heuristic, as it doesn't take hygiene into account. 855 /// necessary a heuristic, as it doesn't take hygiene into account.
855 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> { 856 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
856 let hygiene = Hygiene::new(self.db.upcast(), self.file_id); 857 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
857 let path = Path::from_src(path.clone(), &hygiene)?; 858 let path = Path::from_src(path.clone(), &ctx)?;
858 resolve_hir_path(self.db, &self.resolver, &path) 859 resolve_hir_path(self.db, &self.resolver, &path)
859 } 860 }
860} 861}
diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs
index 847d2537d..0895bd6f1 100644
--- a/crates/hir/src/source_analyzer.rs
+++ b/crates/hir/src/source_analyzer.rs
@@ -9,6 +9,7 @@ use std::{iter::once, sync::Arc};
9 9
10use hir_def::{ 10use hir_def::{
11 body::{ 11 body::{
12 self,
12 scope::{ExprScopes, ScopeId}, 13 scope::{ExprScopes, ScopeId},
13 Body, BodySourceMap, 14 Body, BodySourceMap,
14 }, 15 },
@@ -202,8 +203,8 @@ impl SourceAnalyzer {
202 db: &dyn HirDatabase, 203 db: &dyn HirDatabase,
203 macro_call: InFile<&ast::MacroCall>, 204 macro_call: InFile<&ast::MacroCall>,
204 ) -> Option<MacroDef> { 205 ) -> Option<MacroDef> {
205 let hygiene = Hygiene::new(db.upcast(), macro_call.file_id); 206 let ctx = body::LowerCtx::new(db.upcast(), macro_call.file_id);
206 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?; 207 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &ctx))?;
207 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into()) 208 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
208 } 209 }
209 210
@@ -281,7 +282,9 @@ impl SourceAnalyzer {
281 } 282 }
282 283
283 // This must be a normal source file rather than macro file. 284 // This must be a normal source file rather than macro file.
284 let hir_path = Path::from_src(path.clone(), &Hygiene::new(db.upcast(), self.file_id))?; 285 let hygiene = Hygiene::new(db.upcast(), self.file_id);
286 let ctx = body::LowerCtx::with_hygiene(&hygiene);
287 let hir_path = Path::from_src(path.clone(), &ctx)?;
285 288
286 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we 289 // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we
287 // trying to resolve foo::bar. 290 // trying to resolve foo::bar.
diff --git a/crates/hir_def/src/attr.rs b/crates/hir_def/src/attr.rs
index d9df7564d..d9294d93a 100644
--- a/crates/hir_def/src/attr.rs
+++ b/crates/hir_def/src/attr.rs
@@ -9,7 +9,7 @@ use std::{
9use base_db::CrateId; 9use base_db::CrateId;
10use cfg::{CfgExpr, CfgOptions}; 10use cfg::{CfgExpr, CfgOptions};
11use either::Either; 11use either::Either;
12use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile}; 12use hir_expand::{hygiene::Hygiene, name::AsName, AstId, AttrId, InFile};
13use itertools::Itertools; 13use itertools::Itertools;
14use la_arena::ArenaMap; 14use la_arena::ArenaMap;
15use mbe::ast_to_token_tree; 15use mbe::ast_to_token_tree;
@@ -98,13 +98,16 @@ impl RawAttrs {
98 pub(crate) fn new(owner: &dyn ast::AttrsOwner, hygiene: &Hygiene) -> Self { 98 pub(crate) fn new(owner: &dyn ast::AttrsOwner, hygiene: &Hygiene) -> Self {
99 let entries = collect_attrs(owner) 99 let entries = collect_attrs(owner)
100 .enumerate() 100 .enumerate()
101 .flat_map(|(i, attr)| match attr { 101 .flat_map(|(i, attr)| {
102 Either::Left(attr) => Attr::from_src(attr, hygiene, i as u32), 102 let index = AttrId(i as u32);
103 Either::Right(comment) => comment.doc_comment().map(|doc| Attr { 103 match attr {
104 index: i as u32, 104 Either::Left(attr) => Attr::from_src(attr, hygiene, index),
105 input: Some(AttrInput::Literal(SmolStr::new(doc))), 105 Either::Right(comment) => comment.doc_comment().map(|doc| Attr {
106 path: Interned::new(ModPath::from(hir_expand::name!(doc))), 106 id: index,
107 }), 107 input: Some(AttrInput::Literal(SmolStr::new(doc))),
108 path: Interned::new(ModPath::from(hir_expand::name!(doc))),
109 }),
110 }
108 }) 111 })
109 .collect::<Arc<_>>(); 112 .collect::<Arc<_>>();
110 113
@@ -161,7 +164,7 @@ impl RawAttrs {
161 let cfg = parts.next().unwrap(); 164 let cfg = parts.next().unwrap();
162 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() }; 165 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
163 let cfg = CfgExpr::parse(&cfg); 166 let cfg = CfgExpr::parse(&cfg);
164 let index = attr.index; 167 let index = attr.id;
165 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| { 168 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
166 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() }; 169 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
167 let attr = ast::Attr::parse(&format!("#[{}]", tree)).ok()?; 170 let attr = ast::Attr::parse(&format!("#[{}]", tree)).ok()?;
@@ -468,7 +471,7 @@ impl AttrsWithOwner {
468 ) -> Option<(Documentation, DocsRangeMap)> { 471 ) -> Option<(Documentation, DocsRangeMap)> {
469 // FIXME: code duplication in `docs` above 472 // FIXME: code duplication in `docs` above
470 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_ref()? { 473 let docs = self.by_key("doc").attrs().flat_map(|attr| match attr.input.as_ref()? {
471 AttrInput::Literal(s) => Some((s, attr.index)), 474 AttrInput::Literal(s) => Some((s, attr.id)),
472 AttrInput::TokenTree(_) => None, 475 AttrInput::TokenTree(_) => None,
473 }); 476 });
474 let indent = docs 477 let indent = docs
@@ -542,7 +545,7 @@ fn inner_attributes(
542 _ => return None, 545 _ => return None,
543 } 546 }
544 }; 547 };
545 let attrs = attrs.filter(|attr| attr.excl_token().is_some()); 548 let attrs = attrs.filter(|attr| attr.kind().is_inner());
546 let docs = docs.filter(|doc| doc.is_inner()); 549 let docs = docs.filter(|doc| doc.is_inner());
547 Some((attrs, docs)) 550 Some((attrs, docs))
548} 551}
@@ -560,8 +563,8 @@ impl AttrSourceMap {
560 /// the attribute represented by `Attr`. 563 /// the attribute represented by `Attr`.
561 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> { 564 pub fn source_of(&self, attr: &Attr) -> InFile<&Either<ast::Attr, ast::Comment>> {
562 self.attrs 565 self.attrs
563 .get(attr.index as usize) 566 .get(attr.id.0 as usize)
564 .unwrap_or_else(|| panic!("cannot find `Attr` at index {}", attr.index)) 567 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", attr.id))
565 .as_ref() 568 .as_ref()
566 } 569 }
567} 570}
@@ -572,7 +575,7 @@ pub struct DocsRangeMap {
572 // (docstring-line-range, attr_index, attr-string-range) 575 // (docstring-line-range, attr_index, attr-string-range)
573 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and 576 // a mapping from the text range of a line of the [`Documentation`] to the attribute index and
574 // the original (untrimmed) syntax doc line 577 // the original (untrimmed) syntax doc line
575 mapping: Vec<(TextRange, u32, TextRange)>, 578 mapping: Vec<(TextRange, AttrId, TextRange)>,
576} 579}
577 580
578impl DocsRangeMap { 581impl DocsRangeMap {
@@ -585,7 +588,7 @@ impl DocsRangeMap {
585 588
586 let relative_range = range - line_docs_range.start(); 589 let relative_range = range - line_docs_range.start();
587 590
588 let &InFile { file_id, value: ref source } = &self.source[idx as usize]; 591 let &InFile { file_id, value: ref source } = &self.source[idx.0 as usize];
589 match source { 592 match source {
590 Either::Left(_) => None, // FIXME, figure out a nice way to handle doc attributes here 593 Either::Left(_) => None, // FIXME, figure out a nice way to handle doc attributes here
591 // as well as for whats done in syntax highlight doc injection 594 // as well as for whats done in syntax highlight doc injection
@@ -606,7 +609,7 @@ impl DocsRangeMap {
606 609
607#[derive(Debug, Clone, PartialEq, Eq)] 610#[derive(Debug, Clone, PartialEq, Eq)]
608pub struct Attr { 611pub struct Attr {
609 index: u32, 612 pub(crate) id: AttrId,
610 pub(crate) path: Interned<ModPath>, 613 pub(crate) path: Interned<ModPath>,
611 pub(crate) input: Option<AttrInput>, 614 pub(crate) input: Option<AttrInput>,
612} 615}
@@ -620,7 +623,7 @@ pub enum AttrInput {
620} 623}
621 624
622impl Attr { 625impl Attr {
623 fn from_src(ast: ast::Attr, hygiene: &Hygiene, index: u32) -> Option<Attr> { 626 fn from_src(ast: ast::Attr, hygiene: &Hygiene, id: AttrId) -> Option<Attr> {
624 let path = Interned::new(ModPath::from_src(ast.path()?, hygiene)?); 627 let path = Interned::new(ModPath::from_src(ast.path()?, hygiene)?);
625 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() { 628 let input = if let Some(ast::Expr::Literal(lit)) = ast.expr() {
626 let value = match lit.kind() { 629 let value = match lit.kind() {
@@ -633,7 +636,7 @@ impl Attr {
633 } else { 636 } else {
634 None 637 None
635 }; 638 };
636 Some(Attr { index, path, input }) 639 Some(Attr { id, path, input })
637 } 640 }
638 641
639 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths 642 /// Parses this attribute as a `#[derive]`, returns an iterator that yields all contained paths
@@ -737,7 +740,7 @@ fn collect_attrs(
737 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax()) 740 let (inner_attrs, inner_docs) = inner_attributes(owner.syntax())
738 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs))); 741 .map_or((None, None), |(attrs, docs)| (Some(attrs), Some(docs)));
739 742
740 let outer_attrs = owner.attrs().filter(|attr| attr.excl_token().is_none()); 743 let outer_attrs = owner.attrs().filter(|attr| attr.kind().is_outer());
741 let attrs = outer_attrs 744 let attrs = outer_attrs
742 .chain(inner_attrs.into_iter().flatten()) 745 .chain(inner_attrs.into_iter().flatten())
743 .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr))); 746 .map(|attr| (attr.syntax().text_range().start(), Either::Left(attr)));
@@ -748,9 +751,7 @@ fn collect_attrs(
748 .chain(inner_docs.into_iter().flatten()) 751 .chain(inner_docs.into_iter().flatten())
749 .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text))); 752 .map(|docs_text| (docs_text.syntax().text_range().start(), Either::Right(docs_text)));
750 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved 753 // sort here by syntax node offset because the source can have doc attributes and doc strings be interleaved
751 let attrs: Vec<_> = docs.chain(attrs).sorted_by_key(|&(offset, _)| offset).collect(); 754 docs.chain(attrs).sorted_by_key(|&(offset, _)| offset).map(|(_, attr)| attr)
752
753 attrs.into_iter().map(|(_, attr)| attr)
754} 755}
755 756
756pub(crate) fn variants_attrs_source_map( 757pub(crate) fn variants_attrs_source_map(
diff --git a/crates/hir_def/src/body.rs b/crates/hir_def/src/body.rs
index 96b959967..131f424cc 100644
--- a/crates/hir_def/src/body.rs
+++ b/crates/hir_def/src/body.rs
@@ -21,7 +21,7 @@ use profile::Count;
21use rustc_hash::FxHashMap; 21use rustc_hash::FxHashMap;
22use syntax::{ast, AstNode, AstPtr}; 22use syntax::{ast, AstNode, AstPtr};
23 23
24pub(crate) use lower::LowerCtx; 24pub use lower::LowerCtx;
25 25
26use crate::{ 26use crate::{
27 attr::{Attrs, RawAttrs}, 27 attr::{Attrs, RawAttrs},
@@ -37,13 +37,15 @@ use crate::{
37 37
38/// A subset of Expander that only deals with cfg attributes. We only need it to 38/// A subset of Expander that only deals with cfg attributes. We only need it to
39/// avoid cyclic queries in crate def map during enum processing. 39/// avoid cyclic queries in crate def map during enum processing.
40#[derive(Debug)]
40pub(crate) struct CfgExpander { 41pub(crate) struct CfgExpander {
41 cfg_options: CfgOptions, 42 cfg_options: CfgOptions,
42 hygiene: Hygiene, 43 hygiene: Hygiene,
43 krate: CrateId, 44 krate: CrateId,
44} 45}
45 46
46pub(crate) struct Expander { 47#[derive(Debug)]
48pub struct Expander {
47 cfg_expander: CfgExpander, 49 cfg_expander: CfgExpander,
48 def_map: Arc<DefMap>, 50 def_map: Arc<DefMap>,
49 current_file_id: HirFileId, 51 current_file_id: HirFileId,
@@ -80,11 +82,7 @@ impl CfgExpander {
80} 82}
81 83
82impl Expander { 84impl Expander {
83 pub(crate) fn new( 85 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
84 db: &dyn DefDatabase,
85 current_file_id: HirFileId,
86 module: ModuleId,
87 ) -> Expander {
88 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate); 86 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
89 let def_map = module.def_map(db); 87 let def_map = module.def_map(db);
90 let ast_id_map = db.ast_id_map(current_file_id); 88 let ast_id_map = db.ast_id_map(current_file_id);
@@ -98,7 +96,7 @@ impl Expander {
98 } 96 }
99 } 97 }
100 98
101 pub(crate) fn enter_expand<T: ast::AstNode>( 99 pub fn enter_expand<T: ast::AstNode>(
102 &mut self, 100 &mut self,
103 db: &dyn DefDatabase, 101 db: &dyn DefDatabase,
104 macro_call: ast::MacroCall, 102 macro_call: ast::MacroCall,
@@ -170,7 +168,7 @@ impl Expander {
170 Ok(ExpandResult { value: Some((mark, node)), err }) 168 Ok(ExpandResult { value: Some((mark, node)), err })
171 } 169 }
172 170
173 pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) { 171 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
174 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id); 172 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
175 self.current_file_id = mark.file_id; 173 self.current_file_id = mark.file_id;
176 self.ast_id_map = mem::take(&mut mark.ast_id_map); 174 self.ast_id_map = mem::take(&mut mark.ast_id_map);
@@ -190,8 +188,13 @@ impl Expander {
190 &self.cfg_expander.cfg_options 188 &self.cfg_expander.cfg_options
191 } 189 }
192 190
191 pub fn current_file_id(&self) -> HirFileId {
192 self.current_file_id
193 }
194
193 fn parse_path(&mut self, path: ast::Path) -> Option<Path> { 195 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
194 Path::from_src(path, &self.cfg_expander.hygiene) 196 let ctx = LowerCtx::with_hygiene(&self.cfg_expander.hygiene);
197 Path::from_src(path, &ctx)
195 } 198 }
196 199
197 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> { 200 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
@@ -204,7 +207,8 @@ impl Expander {
204 } 207 }
205} 208}
206 209
207pub(crate) struct Mark { 210#[derive(Debug)]
211pub struct Mark {
208 file_id: HirFileId, 212 file_id: HirFileId,
209 ast_id_map: Arc<AstIdMap>, 213 ast_id_map: Arc<AstIdMap>,
210 bomb: DropBomb, 214 bomb: DropBomb,
diff --git a/crates/hir_def/src/body/lower.rs b/crates/hir_def/src/body/lower.rs
index bfb75a8a5..c11da30d2 100644
--- a/crates/hir_def/src/body/lower.rs
+++ b/crates/hir_def/src/body/lower.rs
@@ -1,10 +1,11 @@
1//! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr` 1//! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
2//! representation. 2//! representation.
3 3
4use std::mem; 4use std::{mem, sync::Arc};
5 5
6use either::Either; 6use either::Either;
7use hir_expand::{ 7use hir_expand::{
8 ast_id_map::{AstIdMap, FileAstId},
8 hygiene::Hygiene, 9 hygiene::Hygiene,
9 name::{name, AsName, Name}, 10 name::{name, AsName, Name},
10 ExpandError, HirFileId, 11 ExpandError, HirFileId,
@@ -39,20 +40,39 @@ use crate::{
39 40
40use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource}; 41use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
41 42
42pub(crate) struct LowerCtx { 43pub struct LowerCtx {
43 hygiene: Hygiene, 44 hygiene: Hygiene,
45 file_id: Option<HirFileId>,
46 source_ast_id_map: Option<Arc<AstIdMap>>,
44} 47}
45 48
46impl LowerCtx { 49impl LowerCtx {
47 pub(crate) fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self { 50 pub fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
48 LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) } 51 LowerCtx {
52 hygiene: Hygiene::new(db.upcast(), file_id),
53 file_id: Some(file_id),
54 source_ast_id_map: Some(db.ast_id_map(file_id)),
55 }
49 } 56 }
50 pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self { 57
51 LowerCtx { hygiene: hygiene.clone() } 58 pub fn with_hygiene(hygiene: &Hygiene) -> Self {
59 LowerCtx { hygiene: hygiene.clone(), file_id: None, source_ast_id_map: None }
60 }
61
62 pub(crate) fn hygiene(&self) -> &Hygiene {
63 &self.hygiene
64 }
65
66 pub(crate) fn file_id(&self) -> HirFileId {
67 self.file_id.unwrap()
52 } 68 }
53 69
54 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> { 70 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
55 Path::from_src(ast, &self.hygiene) 71 Path::from_src(ast, self)
72 }
73
74 pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> Option<FileAstId<N>> {
75 self.source_ast_id_map.as_ref().map(|ast_id_map| ast_id_map.ast_id(item))
56 } 76 }
57} 77}
58 78
@@ -531,8 +551,9 @@ impl ExprCollector<'_> {
531 } 551 }
532 } 552 }
533 ast::Expr::MacroCall(e) => { 553 ast::Expr::MacroCall(e) => {
554 let macro_ptr = AstPtr::new(&e);
534 let mut ids = vec![]; 555 let mut ids = vec![];
535 self.collect_macro_call(e, syntax_ptr.clone(), true, |this, expansion| { 556 self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
536 ids.push(match expansion { 557 ids.push(match expansion {
537 Some(it) => this.collect_expr(it), 558 Some(it) => this.collect_expr(it),
538 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()), 559 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
@@ -555,7 +576,7 @@ impl ExprCollector<'_> {
555 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>( 576 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
556 &mut self, 577 &mut self,
557 e: ast::MacroCall, 578 e: ast::MacroCall,
558 syntax_ptr: AstPtr<ast::Expr>, 579 syntax_ptr: AstPtr<ast::MacroCall>,
559 is_error_recoverable: bool, 580 is_error_recoverable: bool,
560 mut collector: F, 581 mut collector: F,
561 ) { 582 ) {
@@ -567,9 +588,13 @@ impl ExprCollector<'_> {
567 588
568 let res = match res { 589 let res = match res {
569 Ok(res) => res, 590 Ok(res) => res,
570 Err(UnresolvedMacro) => { 591 Err(UnresolvedMacro { path }) => {
571 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall( 592 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall(
572 UnresolvedMacroCall { file: outer_file, node: syntax_ptr.cast().unwrap() }, 593 UnresolvedMacroCall {
594 file: outer_file,
595 node: syntax_ptr.cast().unwrap(),
596 path,
597 },
573 )); 598 ));
574 collector(self, None); 599 collector(self, None);
575 return; 600 return;
@@ -643,10 +668,14 @@ impl ExprCollector<'_> {
643 668
644 // Note that macro could be expended to multiple statements 669 // Note that macro could be expended to multiple statements
645 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() { 670 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
671 let macro_ptr = AstPtr::new(&m);
646 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap()); 672 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
647 673
648 self.collect_macro_call(m, syntax_ptr.clone(), false, |this, expansion| { 674 self.collect_macro_call(
649 match expansion { 675 m,
676 macro_ptr,
677 false,
678 |this, expansion| match expansion {
650 Some(expansion) => { 679 Some(expansion) => {
651 let statements: ast::MacroStmts = expansion; 680 let statements: ast::MacroStmts = expansion;
652 681
@@ -660,8 +689,8 @@ impl ExprCollector<'_> {
660 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone()); 689 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
661 this.statements_in_scope.push(Statement::Expr(expr)); 690 this.statements_in_scope.push(Statement::Expr(expr));
662 } 691 }
663 } 692 },
664 }); 693 );
665 } else { 694 } else {
666 let expr = self.collect_expr_opt(stmt.expr()); 695 let expr = self.collect_expr_opt(stmt.expr());
667 self.statements_in_scope.push(Statement::Expr(expr)); 696 self.statements_in_scope.push(Statement::Expr(expr));
@@ -848,8 +877,23 @@ impl ExprCollector<'_> {
848 Pat::Missing 877 Pat::Missing
849 } 878 }
850 } 879 }
880 ast::Pat::MacroPat(mac) => match mac.macro_call() {
881 Some(call) => {
882 let macro_ptr = AstPtr::new(&call);
883 let mut pat = None;
884 self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
885 pat = Some(this.collect_pat_opt(expanded_pat));
886 });
887
888 match pat {
889 Some(pat) => return pat,
890 None => Pat::Missing,
891 }
892 }
893 None => Pat::Missing,
894 },
851 // FIXME: implement 895 // FIXME: implement
852 ast::Pat::RangePat(_) | ast::Pat::MacroPat(_) => Pat::Missing, 896 ast::Pat::RangePat(_) => Pat::Missing,
853 }; 897 };
854 let ptr = AstPtr::new(&pat); 898 let ptr = AstPtr::new(&pat);
855 self.alloc_pat(pattern, Either::Left(ptr)) 899 self.alloc_pat(pattern, Either::Left(ptr))
diff --git a/crates/hir_def/src/body/tests.rs b/crates/hir_def/src/body/tests.rs
index c1d3e998f..3e8f16306 100644
--- a/crates/hir_def/src/body/tests.rs
+++ b/crates/hir_def/src/body/tests.rs
@@ -40,6 +40,14 @@ fn block_def_map_at(ra_fixture: &str) -> String {
40 module.def_map(&db).dump(&db) 40 module.def_map(&db).dump(&db)
41} 41}
42 42
43fn check_block_scopes_at(ra_fixture: &str, expect: Expect) {
44 let (db, position) = crate::test_db::TestDB::with_position(ra_fixture);
45
46 let module = db.module_at_position(position);
47 let actual = module.def_map(&db).dump_block_scopes(&db);
48 expect.assert_eq(&actual);
49}
50
43fn check_at(ra_fixture: &str, expect: Expect) { 51fn check_at(ra_fixture: &str, expect: Expect) {
44 let actual = block_def_map_at(ra_fixture); 52 let actual = block_def_map_at(ra_fixture);
45 expect.assert_eq(&actual); 53 expect.assert_eq(&actual);
@@ -180,7 +188,7 @@ fn unresolved_macro_diag() {
180 r#" 188 r#"
181fn f() { 189fn f() {
182 m!(); 190 m!();
183 //^^^^ unresolved macro call 191 //^^^^ unresolved macro `m!`
184} 192}
185 "#, 193 "#,
186 ); 194 );
diff --git a/crates/hir_def/src/body/tests/block.rs b/crates/hir_def/src/body/tests/block.rs
index 3b6ba4cde..bc3d0f138 100644
--- a/crates/hir_def/src/body/tests/block.rs
+++ b/crates/hir_def/src/body/tests/block.rs
@@ -134,6 +134,30 @@ struct Struct {}
134} 134}
135 135
136#[test] 136#[test]
137fn nested_module_scoping() {
138 check_block_scopes_at(
139 r#"
140fn f() {
141 mod module {
142 struct Struct {}
143 fn f() {
144 use self::Struct;
145 $0
146 }
147 }
148}
149 "#,
150 expect![[r#"
151 BlockId(1) in ModuleId { krate: CrateId(0), block: Some(BlockId(0)), local_id: Idx::<ModuleData>(0) }
152 BlockId(0) in ModuleId { krate: CrateId(0), block: None, local_id: Idx::<ModuleData>(0) }
153 crate scope
154 "#]],
155 );
156 // FIXME: The module nesting here is wrong!
157 // The first block map should be located in module #1 (`mod module`), not #0 (BlockId(0) root module)
158}
159
160#[test]
137fn legacy_macro_items() { 161fn legacy_macro_items() {
138 // Checks that legacy-scoped `macro_rules!` from parent namespaces are resolved and expanded 162 // Checks that legacy-scoped `macro_rules!` from parent namespaces are resolved and expanded
139 // correctly. 163 // correctly.
diff --git a/crates/hir_def/src/child_by_source.rs b/crates/hir_def/src/child_by_source.rs
index f40a7f80d..f2e809ca9 100644
--- a/crates/hir_def/src/child_by_source.rs
+++ b/crates/hir_def/src/child_by_source.rs
@@ -80,6 +80,10 @@ impl ChildBySource for ModuleId {
80impl ChildBySource for ItemScope { 80impl ChildBySource for ItemScope {
81 fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap) { 81 fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap) {
82 self.declarations().for_each(|item| add_module_def(db, res, item)); 82 self.declarations().for_each(|item| add_module_def(db, res, item));
83 self.unnamed_consts().for_each(|konst| {
84 let src = konst.lookup(db).source(db);
85 res[keys::CONST].insert(src, konst);
86 });
83 self.impls().for_each(|imp| add_impl(db, res, imp)); 87 self.impls().for_each(|imp| add_impl(db, res, imp));
84 88
85 fn add_module_def(db: &dyn DefDatabase, map: &mut DynMap, item: ModuleDefId) { 89 fn add_module_def(db: &dyn DefDatabase, map: &mut DynMap, item: ModuleDefId) {
diff --git a/crates/hir_def/src/diagnostics.rs b/crates/hir_def/src/diagnostics.rs
index 97abf8653..a71ae2668 100644
--- a/crates/hir_def/src/diagnostics.rs
+++ b/crates/hir_def/src/diagnostics.rs
@@ -8,7 +8,7 @@ use hir_expand::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticSink};
8use hir_expand::{HirFileId, InFile}; 8use hir_expand::{HirFileId, InFile};
9use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; 9use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange};
10 10
11use crate::{db::DefDatabase, DefWithBodyId}; 11use crate::{db::DefDatabase, path::ModPath, DefWithBodyId};
12 12
13pub fn validate_body(db: &dyn DefDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) { 13pub fn validate_body(db: &dyn DefDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) {
14 let source_map = db.body_with_source_map(owner).1; 14 let source_map = db.body_with_source_map(owner).1;
@@ -103,6 +103,7 @@ impl Diagnostic for UnresolvedImport {
103pub struct UnresolvedMacroCall { 103pub struct UnresolvedMacroCall {
104 pub file: HirFileId, 104 pub file: HirFileId,
105 pub node: AstPtr<ast::MacroCall>, 105 pub node: AstPtr<ast::MacroCall>,
106 pub path: ModPath,
106} 107}
107 108
108impl Diagnostic for UnresolvedMacroCall { 109impl Diagnostic for UnresolvedMacroCall {
@@ -110,7 +111,7 @@ impl Diagnostic for UnresolvedMacroCall {
110 DiagnosticCode("unresolved-macro-call") 111 DiagnosticCode("unresolved-macro-call")
111 } 112 }
112 fn message(&self) -> String { 113 fn message(&self) -> String {
113 "unresolved macro call".to_string() 114 format!("unresolved macro `{}!`", self.path)
114 } 115 }
115 fn display_source(&self) -> InFile<SyntaxNodePtr> { 116 fn display_source(&self) -> InFile<SyntaxNodePtr> {
116 InFile::new(self.file, self.node.clone().into()) 117 InFile::new(self.file, self.node.clone().into())
diff --git a/crates/hir_def/src/find_path.rs b/crates/hir_def/src/find_path.rs
index 109d3552f..c06a37294 100644
--- a/crates/hir_def/src/find_path.rs
+++ b/crates/hir_def/src/find_path.rs
@@ -119,8 +119,7 @@ fn find_path_inner(
119 119
120 // - if the item is the crate root, return `crate` 120 // - if the item is the crate root, return `crate`
121 let root = def_map.crate_root(db); 121 let root = def_map.crate_root(db);
122 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) && def_map.block_id().is_none() { 122 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) {
123 // FIXME: the `block_id()` check should be unnecessary, but affects the result
124 return Some(ModPath::from_segments(PathKind::Crate, Vec::new())); 123 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
125 } 124 }
126 125
@@ -131,7 +130,8 @@ fn find_path_inner(
131 } 130 }
132 131
133 // - if the item is the crate root of a dependency crate, return the name from the extern prelude 132 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
134 for (name, def_id) in def_map.extern_prelude() { 133 let root_def_map = root.def_map(db);
134 for (name, def_id) in root_def_map.extern_prelude() {
135 if item == ItemInNs::Types(*def_id) { 135 if item == ItemInNs::Types(*def_id) {
136 let name = scope_name.unwrap_or_else(|| name.clone()); 136 let name = scope_name.unwrap_or_else(|| name.clone());
137 return Some(ModPath::from_segments(PathKind::Plain, vec![name])); 137 return Some(ModPath::from_segments(PathKind::Plain, vec![name]));
@@ -139,7 +139,8 @@ fn find_path_inner(
139 } 139 }
140 140
141 // - if the item is in the prelude, return the name from there 141 // - if the item is in the prelude, return the name from there
142 if let Some(prelude_module) = def_map.prelude() { 142 if let Some(prelude_module) = root_def_map.prelude() {
143 // Preludes in block DefMaps are ignored, only the crate DefMap is searched
143 let prelude_def_map = prelude_module.def_map(db); 144 let prelude_def_map = prelude_module.def_map(db);
144 let prelude_scope: &crate::item_scope::ItemScope = 145 let prelude_scope: &crate::item_scope::ItemScope =
145 &prelude_def_map[prelude_module.local_id].scope; 146 &prelude_def_map[prelude_module.local_id].scope;
@@ -298,6 +299,7 @@ fn find_local_import_locations(
298 let data = &def_map[from.local_id]; 299 let data = &def_map[from.local_id];
299 let mut worklist = 300 let mut worklist =
300 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>(); 301 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
302 // FIXME: do we need to traverse out of block expressions here?
301 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) { 303 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
302 worklist.push(ancestor); 304 worklist.push(ancestor);
303 } 305 }
@@ -425,106 +427,142 @@ mod tests {
425 427
426 #[test] 428 #[test]
427 fn same_module() { 429 fn same_module() {
428 let code = r#" 430 check_found_path(
429 //- /main.rs 431 r#"
430 struct S; 432struct S;
431 $0 433$0
432 "#; 434 "#,
433 check_found_path(code, "S", "S", "crate::S", "self::S"); 435 "S",
436 "S",
437 "crate::S",
438 "self::S",
439 );
434 } 440 }
435 441
436 #[test] 442 #[test]
437 fn enum_variant() { 443 fn enum_variant() {
438 let code = r#" 444 check_found_path(
439 //- /main.rs 445 r#"
440 enum E { A } 446enum E { A }
441 $0 447$0
442 "#; 448 "#,
443 check_found_path(code, "E::A", "E::A", "E::A", "E::A"); 449 "E::A",
450 "E::A",
451 "E::A",
452 "E::A",
453 );
444 } 454 }
445 455
446 #[test] 456 #[test]
447 fn sub_module() { 457 fn sub_module() {
448 let code = r#" 458 check_found_path(
449 //- /main.rs 459 r#"
450 mod foo { 460mod foo {
451 pub struct S; 461 pub struct S;
452 } 462}
453 $0 463$0
454 "#; 464 "#,
455 check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S"); 465 "foo::S",
466 "foo::S",
467 "crate::foo::S",
468 "self::foo::S",
469 );
456 } 470 }
457 471
458 #[test] 472 #[test]
459 fn super_module() { 473 fn super_module() {
460 let code = r#" 474 check_found_path(
461 //- /main.rs 475 r#"
462 mod foo; 476//- /main.rs
463 //- /foo.rs 477mod foo;
464 mod bar; 478//- /foo.rs
465 struct S; 479mod bar;
466 //- /foo/bar.rs 480struct S;
467 $0 481//- /foo/bar.rs
468 "#; 482$0
469 check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S"); 483 "#,
484 "super::S",
485 "super::S",
486 "crate::foo::S",
487 "super::S",
488 );
470 } 489 }
471 490
472 #[test] 491 #[test]
473 fn self_module() { 492 fn self_module() {
474 let code = r#" 493 check_found_path(
475 //- /main.rs 494 r#"
476 mod foo; 495//- /main.rs
477 //- /foo.rs 496mod foo;
478 $0 497//- /foo.rs
479 "#; 498$0
480 check_found_path(code, "self", "self", "crate::foo", "self"); 499 "#,
500 "self",
501 "self",
502 "crate::foo",
503 "self",
504 );
481 } 505 }
482 506
483 #[test] 507 #[test]
484 fn crate_root() { 508 fn crate_root() {
485 let code = r#" 509 check_found_path(
486 //- /main.rs 510 r#"
487 mod foo; 511//- /main.rs
488 //- /foo.rs 512mod foo;
489 $0 513//- /foo.rs
490 "#; 514$0
491 check_found_path(code, "crate", "crate", "crate", "crate"); 515 "#,
516 "crate",
517 "crate",
518 "crate",
519 "crate",
520 );
492 } 521 }
493 522
494 #[test] 523 #[test]
495 fn same_crate() { 524 fn same_crate() {
496 let code = r#" 525 check_found_path(
497 //- /main.rs 526 r#"
498 mod foo; 527//- /main.rs
499 struct S; 528mod foo;
500 //- /foo.rs 529struct S;
501 $0 530//- /foo.rs
502 "#; 531$0
503 check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S"); 532 "#,
533 "crate::S",
534 "crate::S",
535 "crate::S",
536 "crate::S",
537 );
504 } 538 }
505 539
506 #[test] 540 #[test]
507 fn different_crate() { 541 fn different_crate() {
508 let code = r#" 542 check_found_path(
509 //- /main.rs crate:main deps:std 543 r#"
510 $0 544//- /main.rs crate:main deps:std
511 //- /std.rs crate:std 545$0
512 pub struct S; 546//- /std.rs crate:std
513 "#; 547pub struct S;
514 check_found_path(code, "std::S", "std::S", "std::S", "std::S"); 548 "#,
549 "std::S",
550 "std::S",
551 "std::S",
552 "std::S",
553 );
515 } 554 }
516 555
517 #[test] 556 #[test]
518 fn different_crate_renamed() { 557 fn different_crate_renamed() {
519 let code = r#"
520 //- /main.rs crate:main deps:std
521 extern crate std as std_renamed;
522 $0
523 //- /std.rs crate:std
524 pub struct S;
525 "#;
526 check_found_path( 558 check_found_path(
527 code, 559 r#"
560//- /main.rs crate:main deps:std
561extern crate std as std_renamed;
562$0
563//- /std.rs crate:std
564pub struct S;
565 "#,
528 "std_renamed::S", 566 "std_renamed::S",
529 "std_renamed::S", 567 "std_renamed::S",
530 "std_renamed::S", 568 "std_renamed::S",
@@ -537,41 +575,38 @@ mod tests {
537 cov_mark::check!(partially_imported); 575 cov_mark::check!(partially_imported);
538 // Tests that short paths are used even for external items, when parts of the path are 576 // Tests that short paths are used even for external items, when parts of the path are
539 // already in scope. 577 // already in scope.
540 let code = r#" 578 check_found_path(
541 //- /main.rs crate:main deps:syntax 579 r#"
580//- /main.rs crate:main deps:syntax
542 581
543 use syntax::ast; 582use syntax::ast;
544 $0 583$0
545 584
546 //- /lib.rs crate:syntax 585//- /lib.rs crate:syntax
547 pub mod ast { 586pub mod ast {
548 pub enum ModuleItem { 587 pub enum ModuleItem {
549 A, B, C, 588 A, B, C,
550 } 589 }
551 } 590}
552 "#; 591 "#,
553 check_found_path(
554 code,
555 "ast::ModuleItem", 592 "ast::ModuleItem",
556 "syntax::ast::ModuleItem", 593 "syntax::ast::ModuleItem",
557 "syntax::ast::ModuleItem", 594 "syntax::ast::ModuleItem",
558 "syntax::ast::ModuleItem", 595 "syntax::ast::ModuleItem",
559 ); 596 );
560 597
561 let code = r#"
562 //- /main.rs crate:main deps:syntax
563
564 $0
565
566 //- /lib.rs crate:syntax
567 pub mod ast {
568 pub enum ModuleItem {
569 A, B, C,
570 }
571 }
572 "#;
573 check_found_path( 598 check_found_path(
574 code, 599 r#"
600//- /main.rs crate:main deps:syntax
601$0
602
603//- /lib.rs crate:syntax
604pub mod ast {
605 pub enum ModuleItem {
606 A, B, C,
607 }
608}
609 "#,
575 "syntax::ast::ModuleItem", 610 "syntax::ast::ModuleItem",
576 "syntax::ast::ModuleItem", 611 "syntax::ast::ModuleItem",
577 "syntax::ast::ModuleItem", 612 "syntax::ast::ModuleItem",
@@ -581,68 +616,86 @@ mod tests {
581 616
582 #[test] 617 #[test]
583 fn same_crate_reexport() { 618 fn same_crate_reexport() {
584 let code = r#" 619 check_found_path(
585 //- /main.rs 620 r#"
586 mod bar { 621mod bar {
587 mod foo { pub(super) struct S; } 622 mod foo { pub(super) struct S; }
588 pub(crate) use foo::*; 623 pub(crate) use foo::*;
589 } 624}
590 $0 625$0
591 "#; 626 "#,
592 check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S"); 627 "bar::S",
628 "bar::S",
629 "crate::bar::S",
630 "self::bar::S",
631 );
593 } 632 }
594 633
595 #[test] 634 #[test]
596 fn same_crate_reexport_rename() { 635 fn same_crate_reexport_rename() {
597 let code = r#" 636 check_found_path(
598 //- /main.rs 637 r#"
599 mod bar { 638mod bar {
600 mod foo { pub(super) struct S; } 639 mod foo { pub(super) struct S; }
601 pub(crate) use foo::S as U; 640 pub(crate) use foo::S as U;
602 } 641}
603 $0 642$0
604 "#; 643 "#,
605 check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U"); 644 "bar::U",
645 "bar::U",
646 "crate::bar::U",
647 "self::bar::U",
648 );
606 } 649 }
607 650
608 #[test] 651 #[test]
609 fn different_crate_reexport() { 652 fn different_crate_reexport() {
610 let code = r#" 653 check_found_path(
611 //- /main.rs crate:main deps:std 654 r#"
612 $0 655//- /main.rs crate:main deps:std
613 //- /std.rs crate:std deps:core 656$0
614 pub use core::S; 657//- /std.rs crate:std deps:core
615 //- /core.rs crate:core 658pub use core::S;
616 pub struct S; 659//- /core.rs crate:core
617 "#; 660pub struct S;
618 check_found_path(code, "std::S", "std::S", "std::S", "std::S"); 661 "#,
662 "std::S",
663 "std::S",
664 "std::S",
665 "std::S",
666 );
619 } 667 }
620 668
621 #[test] 669 #[test]
622 fn prelude() { 670 fn prelude() {
623 let code = r#" 671 check_found_path(
624 //- /main.rs crate:main deps:std 672 r#"
625 $0 673//- /main.rs crate:main deps:std
626 //- /std.rs crate:std 674$0
627 pub mod prelude { pub struct S; } 675//- /std.rs crate:std
628 #[prelude_import] 676pub mod prelude { pub struct S; }
629 pub use prelude::*; 677#[prelude_import]
630 "#; 678pub use prelude::*;
631 check_found_path(code, "S", "S", "S", "S"); 679 "#,
680 "S",
681 "S",
682 "S",
683 "S",
684 );
632 } 685 }
633 686
634 #[test] 687 #[test]
635 fn enum_variant_from_prelude() { 688 fn enum_variant_from_prelude() {
636 let code = r#" 689 let code = r#"
637 //- /main.rs crate:main deps:std 690//- /main.rs crate:main deps:std
638 $0 691$0
639 //- /std.rs crate:std 692//- /std.rs crate:std
640 pub mod prelude { 693pub mod prelude {
641 pub enum Option<T> { Some(T), None } 694 pub enum Option<T> { Some(T), None }
642 pub use Option::*; 695 pub use Option::*;
643 } 696}
644 #[prelude_import] 697#[prelude_import]
645 pub use prelude::*; 698pub use prelude::*;
646 "#; 699 "#;
647 check_found_path(code, "None", "None", "None", "None"); 700 check_found_path(code, "None", "None", "None", "None");
648 check_found_path(code, "Some", "Some", "Some", "Some"); 701 check_found_path(code, "Some", "Some", "Some", "Some");
@@ -650,71 +703,85 @@ mod tests {
650 703
651 #[test] 704 #[test]
652 fn shortest_path() { 705 fn shortest_path() {
653 let code = r#" 706 check_found_path(
654 //- /main.rs 707 r#"
655 pub mod foo; 708//- /main.rs
656 pub mod baz; 709pub mod foo;
657 struct S; 710pub mod baz;
658 $0 711struct S;
659 //- /foo.rs 712$0
660 pub mod bar { pub struct S; } 713//- /foo.rs
661 //- /baz.rs 714pub mod bar { pub struct S; }
662 pub use crate::foo::bar::S; 715//- /baz.rs
663 "#; 716pub use crate::foo::bar::S;
664 check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S"); 717 "#,
718 "baz::S",
719 "baz::S",
720 "crate::baz::S",
721 "self::baz::S",
722 );
665 } 723 }
666 724
667 #[test] 725 #[test]
668 fn discount_private_imports() { 726 fn discount_private_imports() {
669 let code = r#" 727 check_found_path(
670 //- /main.rs 728 r#"
671 mod foo; 729//- /main.rs
672 pub mod bar { pub struct S; } 730mod foo;
673 use bar::S; 731pub mod bar { pub struct S; }
674 //- /foo.rs 732use bar::S;
675 $0 733//- /foo.rs
676 "#; 734$0
677 // crate::S would be shorter, but using private imports seems wrong 735 "#,
678 check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S"); 736 // crate::S would be shorter, but using private imports seems wrong
737 "crate::bar::S",
738 "crate::bar::S",
739 "crate::bar::S",
740 "crate::bar::S",
741 );
679 } 742 }
680 743
681 #[test] 744 #[test]
682 fn import_cycle() { 745 fn import_cycle() {
683 let code = r#" 746 check_found_path(
684 //- /main.rs 747 r#"
685 pub mod foo; 748//- /main.rs
686 pub mod bar; 749pub mod foo;
687 pub mod baz; 750pub mod bar;
688 //- /bar.rs 751pub mod baz;
689 $0 752//- /bar.rs
690 //- /foo.rs 753$0
691 pub use super::baz; 754//- /foo.rs
692 pub struct S; 755pub use super::baz;
693 //- /baz.rs 756pub struct S;
694 pub use super::foo; 757//- /baz.rs
695 "#; 758pub use super::foo;
696 check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S"); 759 "#,
760 "crate::foo::S",
761 "crate::foo::S",
762 "crate::foo::S",
763 "crate::foo::S",
764 );
697 } 765 }
698 766
699 #[test] 767 #[test]
700 fn prefer_std_paths_over_alloc() { 768 fn prefer_std_paths_over_alloc() {
701 cov_mark::check!(prefer_std_paths); 769 cov_mark::check!(prefer_std_paths);
702 let code = r#" 770 check_found_path(
703 //- /main.rs crate:main deps:alloc,std 771 r#"
704 $0 772//- /main.rs crate:main deps:alloc,std
773$0
705 774
706 //- /std.rs crate:std deps:alloc 775//- /std.rs crate:std deps:alloc
707 pub mod sync { 776pub mod sync {
708 pub use alloc::sync::Arc; 777 pub use alloc::sync::Arc;
709 } 778}
710 779
711 //- /zzz.rs crate:alloc 780//- /zzz.rs crate:alloc
712 pub mod sync { 781pub mod sync {
713 pub struct Arc; 782 pub struct Arc;
714 } 783}
715 "#; 784 "#,
716 check_found_path(
717 code,
718 "std::sync::Arc", 785 "std::sync::Arc",
719 "std::sync::Arc", 786 "std::sync::Arc",
720 "std::sync::Arc", 787 "std::sync::Arc",
@@ -725,26 +792,25 @@ mod tests {
725 #[test] 792 #[test]
726 fn prefer_core_paths_over_std() { 793 fn prefer_core_paths_over_std() {
727 cov_mark::check!(prefer_no_std_paths); 794 cov_mark::check!(prefer_no_std_paths);
728 let code = r#" 795 check_found_path(
729 //- /main.rs crate:main deps:core,std 796 r#"
730 #![no_std] 797//- /main.rs crate:main deps:core,std
798#![no_std]
731 799
732 $0 800$0
733 801
734 //- /std.rs crate:std deps:core 802//- /std.rs crate:std deps:core
735 803
736 pub mod fmt { 804pub mod fmt {
737 pub use core::fmt::Error; 805 pub use core::fmt::Error;
738 } 806}
739 807
740 //- /zzz.rs crate:core 808//- /zzz.rs crate:core
741 809
742 pub mod fmt { 810pub mod fmt {
743 pub struct Error; 811 pub struct Error;
744 } 812}
745 "#; 813 "#,
746 check_found_path(
747 code,
748 "core::fmt::Error", 814 "core::fmt::Error",
749 "core::fmt::Error", 815 "core::fmt::Error",
750 "core::fmt::Error", 816 "core::fmt::Error",
@@ -754,26 +820,25 @@ mod tests {
754 820
755 #[test] 821 #[test]
756 fn prefer_alloc_paths_over_std() { 822 fn prefer_alloc_paths_over_std() {
757 let code = r#" 823 check_found_path(
758 //- /main.rs crate:main deps:alloc,std 824 r#"
759 #![no_std] 825//- /main.rs crate:main deps:alloc,std
826#![no_std]
760 827
761 $0 828$0
762 829
763 //- /std.rs crate:std deps:alloc 830//- /std.rs crate:std deps:alloc
764 831
765 pub mod sync { 832pub mod sync {
766 pub use alloc::sync::Arc; 833 pub use alloc::sync::Arc;
767 } 834}
768 835
769 //- /zzz.rs crate:alloc 836//- /zzz.rs crate:alloc
770 837
771 pub mod sync { 838pub mod sync {
772 pub struct Arc; 839 pub struct Arc;
773 } 840}
774 "#; 841 "#,
775 check_found_path(
776 code,
777 "alloc::sync::Arc", 842 "alloc::sync::Arc",
778 "alloc::sync::Arc", 843 "alloc::sync::Arc",
779 "alloc::sync::Arc", 844 "alloc::sync::Arc",
@@ -783,20 +848,19 @@ mod tests {
783 848
784 #[test] 849 #[test]
785 fn prefer_shorter_paths_if_not_alloc() { 850 fn prefer_shorter_paths_if_not_alloc() {
786 let code = r#" 851 check_found_path(
787 //- /main.rs crate:main deps:megaalloc,std 852 r#"
788 $0 853//- /main.rs crate:main deps:megaalloc,std
854$0
789 855
790 //- /std.rs crate:std deps:megaalloc 856//- /std.rs crate:std deps:megaalloc
791 pub mod sync { 857pub mod sync {
792 pub use megaalloc::sync::Arc; 858 pub use megaalloc::sync::Arc;
793 } 859}
794 860
795 //- /zzz.rs crate:megaalloc 861//- /zzz.rs crate:megaalloc
796 pub struct Arc; 862pub struct Arc;
797 "#; 863 "#,
798 check_found_path(
799 code,
800 "megaalloc::Arc", 864 "megaalloc::Arc",
801 "megaalloc::Arc", 865 "megaalloc::Arc",
802 "megaalloc::Arc", 866 "megaalloc::Arc",
@@ -807,12 +871,11 @@ mod tests {
807 #[test] 871 #[test]
808 fn builtins_are_in_scope() { 872 fn builtins_are_in_scope() {
809 let code = r#" 873 let code = r#"
810 //- /main.rs 874$0
811 $0
812 875
813 pub mod primitive { 876pub mod primitive {
814 pub use u8; 877 pub use u8;
815 } 878}
816 "#; 879 "#;
817 check_found_path(code, "u8", "u8", "u8", "u8"); 880 check_found_path(code, "u8", "u8", "u8", "u8");
818 check_found_path(code, "u16", "u16", "u16", "u16"); 881 check_found_path(code, "u16", "u16", "u16", "u16");
@@ -822,10 +885,10 @@ mod tests {
822 fn inner_items() { 885 fn inner_items() {
823 check_found_path( 886 check_found_path(
824 r#" 887 r#"
825 fn main() { 888fn main() {
826 struct Inner {} 889 struct Inner {}
827 $0 890 $0
828 } 891}
829 "#, 892 "#,
830 "Inner", 893 "Inner",
831 "Inner", 894 "Inner",
@@ -838,12 +901,12 @@ mod tests {
838 fn inner_items_from_outer_scope() { 901 fn inner_items_from_outer_scope() {
839 check_found_path( 902 check_found_path(
840 r#" 903 r#"
841 fn main() { 904fn main() {
842 struct Struct {} 905 struct Struct {}
843 { 906 {
844 $0 907 $0
845 } 908 }
846 } 909}
847 "#, 910 "#,
848 "Struct", 911 "Struct",
849 "Struct", 912 "Struct",
@@ -857,14 +920,14 @@ mod tests {
857 cov_mark::check!(prefixed_in_block_expression); 920 cov_mark::check!(prefixed_in_block_expression);
858 check_found_path( 921 check_found_path(
859 r#" 922 r#"
860 fn main() { 923fn main() {
861 mod module { 924 mod module {
862 struct Struct {} 925 struct Struct {}
863 } 926 }
864 { 927 {
865 $0 928 $0
866 } 929 }
867 } 930}
868 "#, 931 "#,
869 "module::Struct", 932 "module::Struct",
870 "module::Struct", 933 "module::Struct",
@@ -877,19 +940,65 @@ mod tests {
877 fn outer_items_with_inner_items_present() { 940 fn outer_items_with_inner_items_present() {
878 check_found_path( 941 check_found_path(
879 r#" 942 r#"
880 mod module { 943mod module {
881 pub struct CompleteMe; 944 pub struct CompleteMe;
882 } 945}
883 946
884 fn main() { 947fn main() {
885 fn inner() {} 948 fn inner() {}
886 $0 949 $0
887 } 950}
888 "#, 951 "#,
952 // FIXME: these could use fewer/better prefixes
889 "module::CompleteMe", 953 "module::CompleteMe",
890 "module::CompleteMe",
891 "crate::module::CompleteMe", 954 "crate::module::CompleteMe",
892 "self::module::CompleteMe", 955 "crate::module::CompleteMe",
956 "crate::module::CompleteMe",
957 )
958 }
959
960 #[test]
961 fn from_inside_module() {
962 // This worked correctly, but the test suite logic was broken.
963 cov_mark::check!(submodule_in_testdb);
964 check_found_path(
965 r#"
966mod baz {
967 pub struct Foo {}
968}
969
970mod bar {
971 fn bar() {
972 $0
973 }
974}
975 "#,
976 "crate::baz::Foo",
977 "crate::baz::Foo",
978 "crate::baz::Foo",
979 "crate::baz::Foo",
980 )
981 }
982
983 #[test]
984 fn from_inside_module_with_inner_items() {
985 check_found_path(
986 r#"
987mod baz {
988 pub struct Foo {}
989}
990
991mod bar {
992 fn bar() {
993 fn inner() {}
994 $0
995 }
996}
997 "#,
998 "crate::baz::Foo",
999 "crate::baz::Foo",
1000 "crate::baz::Foo",
1001 "crate::baz::Foo",
893 ) 1002 )
894 } 1003 }
895 1004
@@ -920,4 +1029,58 @@ pub mod name {
920 "self::name::AsName", 1029 "self::name::AsName",
921 ); 1030 );
922 } 1031 }
1032
1033 #[test]
1034 fn extern_crate() {
1035 check_found_path(
1036 r#"
1037//- /main.rs crate:main deps:dep
1038$0
1039//- /dep.rs crate:dep
1040"#,
1041 "dep",
1042 "dep",
1043 "dep",
1044 "dep",
1045 );
1046
1047 check_found_path(
1048 r#"
1049//- /main.rs crate:main deps:dep
1050fn f() {
1051 fn inner() {}
1052 $0
1053}
1054//- /dep.rs crate:dep
1055"#,
1056 "dep",
1057 "dep",
1058 "dep",
1059 "dep",
1060 );
1061 }
1062
1063 #[test]
1064 fn prelude_with_inner_items() {
1065 check_found_path(
1066 r#"
1067//- /main.rs crate:main deps:std
1068fn f() {
1069 fn inner() {}
1070 $0
1071}
1072//- /std.rs crate:std
1073pub mod prelude {
1074 pub enum Option { None }
1075 pub use Option::*;
1076}
1077#[prelude_import]
1078pub use prelude::*;
1079 "#,
1080 "None",
1081 "None",
1082 "None",
1083 "None",
1084 );
1085 }
923} 1086}
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs
index 240662486..eaeca01bd 100644
--- a/crates/hir_def/src/item_tree.rs
+++ b/crates/hir_def/src/item_tree.rs
@@ -99,6 +99,16 @@ impl ItemTree {
99 // items. 99 // items.
100 ctx.lower_macro_stmts(stmts) 100 ctx.lower_macro_stmts(stmts)
101 }, 101 },
102 ast::Pat(_pat) => {
103 // FIXME: This occurs because macros in pattern position are treated as inner
104 // items and expanded during block DefMap computation
105 return Default::default();
106 },
107 ast::Type(ty) => {
108 // Types can contain inner items. We return an empty item tree in this case, but
109 // still need to collect inner items.
110 ctx.lower_inner_items(ty.syntax())
111 },
102 ast::Expr(e) => { 112 ast::Expr(e) => {
103 // Macros can expand to expressions. We return an empty item tree in this case, but 113 // Macros can expand to expressions. We return an empty item tree in this case, but
104 // still need to collect inner items. 114 // still need to collect inner items.
@@ -186,13 +196,6 @@ impl ItemTree {
186 self.raw_attrs(of).clone().filter(db, krate) 196 self.raw_attrs(of).clone().filter(db, krate)
187 } 197 }
188 198
189 pub fn all_inner_items(&self) -> impl Iterator<Item = ModItem> + '_ {
190 match &self.data {
191 Some(data) => Some(data.inner_items.values().flatten().copied()).into_iter().flatten(),
192 None => None.into_iter().flatten(),
193 }
194 }
195
196 pub fn inner_items_of_block(&self, block: FileAstId<ast::BlockExpr>) -> &[ModItem] { 199 pub fn inner_items_of_block(&self, block: FileAstId<ast::BlockExpr>) -> &[ModItem] {
197 match &self.data { 200 match &self.data {
198 Some(data) => data.inner_items.get(&block).map(|it| &**it).unwrap_or(&[]), 201 Some(data) => data.inner_items.get(&block).map(|it| &**it).unwrap_or(&[]),
diff --git a/crates/hir_def/src/item_tree/lower.rs b/crates/hir_def/src/item_tree/lower.rs
index c5629af24..45b099cf3 100644
--- a/crates/hir_def/src/item_tree/lower.rs
+++ b/crates/hir_def/src/item_tree/lower.rs
@@ -189,7 +189,7 @@ impl Ctx {
189 block_stack.push(self.source_ast_id_map.ast_id(&block)); 189 block_stack.push(self.source_ast_id_map.ast_id(&block));
190 }, 190 },
191 ast::Item(item) => { 191 ast::Item(item) => {
192 // FIXME: This triggers for macro calls in expression position 192 // FIXME: This triggers for macro calls in expression/pattern/type position
193 let mod_items = self.lower_mod_item(&item, true); 193 let mod_items = self.lower_mod_item(&item, true);
194 let current_block = block_stack.last(); 194 let current_block = block_stack.last();
195 if let (Some(mod_items), Some(block)) = (mod_items, current_block) { 195 if let (Some(mod_items), Some(block)) = (mod_items, current_block) {
diff --git a/crates/hir_def/src/lib.rs b/crates/hir_def/src/lib.rs
index e2af0e514..25694f037 100644
--- a/crates/hir_def/src/lib.rs
+++ b/crates/hir_def/src/lib.rs
@@ -62,10 +62,11 @@ use hir_expand::{
62 ast_id_map::FileAstId, 62 ast_id_map::FileAstId,
63 eager::{expand_eager_macro, ErrorEmitted, ErrorSink}, 63 eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
64 hygiene::Hygiene, 64 hygiene::Hygiene,
65 AstId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, 65 AstId, AttrId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
66}; 66};
67use la_arena::Idx; 67use la_arena::Idx;
68use nameres::DefMap; 68use nameres::DefMap;
69use path::ModPath;
69use syntax::ast; 70use syntax::ast;
70 71
71use crate::builtin_type::BuiltinType; 72use crate::builtin_type::BuiltinType;
@@ -107,6 +108,18 @@ impl ModuleId {
107 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> { 108 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
108 self.def_map(db).containing_module(self.local_id) 109 self.def_map(db).containing_module(self.local_id)
109 } 110 }
111
112 /// Returns `true` if this module represents a block expression.
113 ///
114 /// Returns `false` if this module is a submodule *inside* a block expression
115 /// (eg. `m` in `{ mod m {} }`).
116 pub fn is_block_root(&self, db: &dyn db::DefDatabase) -> bool {
117 if self.block.is_none() {
118 return false;
119 }
120
121 self.def_map(db)[self.local_id].parent.is_none()
122 }
110} 123}
111 124
112/// An ID of a module, **local** to a specific crate 125/// An ID of a module, **local** to a specific crate
@@ -435,6 +448,16 @@ impl_from!(
435 for AttrDefId 448 for AttrDefId
436); 449);
437 450
451impl From<AssocContainerId> for AttrDefId {
452 fn from(acid: AssocContainerId) -> Self {
453 match acid {
454 AssocContainerId::ModuleId(mid) => AttrDefId::ModuleId(mid),
455 AssocContainerId::ImplId(iid) => AttrDefId::ImplId(iid),
456 AssocContainerId::TraitId(tid) => AttrDefId::TraitId(tid),
457 }
458 }
459}
460
438#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 461#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
439pub enum VariantId { 462pub enum VariantId {
440 EnumVariantId(EnumVariantId), 463 EnumVariantId(EnumVariantId),
@@ -665,7 +688,10 @@ impl<T: ast::AstNode> AstIdWithPath<T> {
665 } 688 }
666} 689}
667 690
668pub struct UnresolvedMacro; 691#[derive(Debug)]
692pub struct UnresolvedMacro {
693 pub path: ModPath,
694}
669 695
670fn macro_call_as_call_id( 696fn macro_call_as_call_id(
671 call: &AstIdWithPath<ast::MacroCall>, 697 call: &AstIdWithPath<ast::MacroCall>,
@@ -674,7 +700,8 @@ fn macro_call_as_call_id(
674 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 700 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
675 error_sink: &mut dyn FnMut(mbe::ExpandError), 701 error_sink: &mut dyn FnMut(mbe::ExpandError),
676) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> { 702) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
677 let def: MacroDefId = resolver(call.path.clone()).ok_or(UnresolvedMacro)?; 703 let def: MacroDefId =
704 resolver(call.path.clone()).ok_or_else(|| UnresolvedMacro { path: call.path.clone() })?;
678 705
679 let res = if let MacroDefKind::BuiltInEager(..) = def.kind { 706 let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
680 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast())); 707 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
@@ -690,24 +717,36 @@ fn macro_call_as_call_id(
690 ) 717 )
691 .map(MacroCallId::from) 718 .map(MacroCallId::from)
692 } else { 719 } else {
693 Ok(def.as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike(call.ast_id)).into()) 720 Ok(def
721 .as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike { ast_id: call.ast_id })
722 .into())
694 }; 723 };
695 Ok(res) 724 Ok(res)
696} 725}
697 726
698fn derive_macro_as_call_id( 727fn derive_macro_as_call_id(
699 item_attr: &AstIdWithPath<ast::Item>, 728 item_attr: &AstIdWithPath<ast::Item>,
729 derive_attr: AttrId,
700 db: &dyn db::DefDatabase, 730 db: &dyn db::DefDatabase,
701 krate: CrateId, 731 krate: CrateId,
702 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 732 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
703) -> Result<MacroCallId, UnresolvedMacro> { 733) -> Result<MacroCallId, UnresolvedMacro> {
704 let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?; 734 let def: MacroDefId = resolver(item_attr.path.clone())
705 let last_segment = item_attr.path.segments().last().ok_or(UnresolvedMacro)?; 735 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
736 let last_segment = item_attr
737 .path
738 .segments()
739 .last()
740 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
706 let res = def 741 let res = def
707 .as_lazy_macro( 742 .as_lazy_macro(
708 db.upcast(), 743 db.upcast(),
709 krate, 744 krate,
710 MacroCallKind::Derive(item_attr.ast_id, last_segment.to_string()), 745 MacroCallKind::Derive {
746 ast_id: item_attr.ast_id,
747 derive_name: last_segment.to_string(),
748 derive_attr,
749 },
711 ) 750 )
712 .into(); 751 .into();
713 Ok(res) 752 Ok(res)
diff --git a/crates/hir_def/src/nameres.rs b/crates/hir_def/src/nameres.rs
index 7dd68219f..ba027c44a 100644
--- a/crates/hir_def/src/nameres.rs
+++ b/crates/hir_def/src/nameres.rs
@@ -410,6 +410,20 @@ impl DefMap {
410 } 410 }
411 } 411 }
412 412
413 pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
414 let mut buf = String::new();
415 let mut arc;
416 let mut current_map = self;
417 while let Some(block) = &current_map.block {
418 format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
419 arc = block.parent.def_map(db);
420 current_map = &*arc;
421 }
422
423 format_to!(buf, "crate scope\n");
424 buf
425 }
426
413 fn shrink_to_fit(&mut self) { 427 fn shrink_to_fit(&mut self) {
414 // Exhaustive match to require handling new fields. 428 // Exhaustive match to require handling new fields.
415 let Self { 429 let Self {
@@ -481,7 +495,7 @@ mod diagnostics {
481 495
482 UnresolvedProcMacro { ast: MacroCallKind }, 496 UnresolvedProcMacro { ast: MacroCallKind },
483 497
484 UnresolvedMacroCall { ast: AstId<ast::MacroCall> }, 498 UnresolvedMacroCall { ast: AstId<ast::MacroCall>, path: ModPath },
485 499
486 MacroError { ast: MacroCallKind, message: String }, 500 MacroError { ast: MacroCallKind, message: String },
487 } 501 }
@@ -546,8 +560,9 @@ mod diagnostics {
546 pub(super) fn unresolved_macro_call( 560 pub(super) fn unresolved_macro_call(
547 container: LocalModuleId, 561 container: LocalModuleId,
548 ast: AstId<ast::MacroCall>, 562 ast: AstId<ast::MacroCall>,
563 path: ModPath,
549 ) -> Self { 564 ) -> Self {
550 Self { in_module: container, kind: DiagnosticKind::UnresolvedMacroCall { ast } } 565 Self { in_module: container, kind: DiagnosticKind::UnresolvedMacroCall { ast, path } }
551 } 566 }
552 567
553 pub(super) fn add_to( 568 pub(super) fn add_to(
@@ -613,12 +628,12 @@ mod diagnostics {
613 DiagnosticKind::UnresolvedProcMacro { ast } => { 628 DiagnosticKind::UnresolvedProcMacro { ast } => {
614 let mut precise_location = None; 629 let mut precise_location = None;
615 let (file, ast, name) = match ast { 630 let (file, ast, name) = match ast {
616 MacroCallKind::FnLike(ast) => { 631 MacroCallKind::FnLike { ast_id } => {
617 let node = ast.to_node(db.upcast()); 632 let node = ast_id.to_node(db.upcast());
618 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node)), None) 633 (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)), None)
619 } 634 }
620 MacroCallKind::Derive(ast, name) => { 635 MacroCallKind::Derive { ast_id, derive_name, .. } => {
621 let node = ast.to_node(db.upcast()); 636 let node = ast_id.to_node(db.upcast());
622 637
623 // Compute the precise location of the macro name's token in the derive 638 // Compute the precise location of the macro name's token in the derive
624 // list. 639 // list.
@@ -639,7 +654,7 @@ mod diagnostics {
639 }); 654 });
640 for token in tokens { 655 for token in tokens {
641 if token.kind() == SyntaxKind::IDENT 656 if token.kind() == SyntaxKind::IDENT
642 && token.text() == name.as_str() 657 && token.text() == derive_name.as_str()
643 { 658 {
644 precise_location = Some(token.text_range()); 659 precise_location = Some(token.text_range());
645 break 'outer; 660 break 'outer;
@@ -648,9 +663,9 @@ mod diagnostics {
648 } 663 }
649 664
650 ( 665 (
651 ast.file_id, 666 ast_id.file_id,
652 SyntaxNodePtr::from(AstPtr::new(&node)), 667 SyntaxNodePtr::from(AstPtr::new(&node)),
653 Some(name.clone()), 668 Some(derive_name.clone()),
654 ) 669 )
655 } 670 }
656 }; 671 };
@@ -662,20 +677,24 @@ mod diagnostics {
662 }); 677 });
663 } 678 }
664 679
665 DiagnosticKind::UnresolvedMacroCall { ast } => { 680 DiagnosticKind::UnresolvedMacroCall { ast, path } => {
666 let node = ast.to_node(db.upcast()); 681 let node = ast.to_node(db.upcast());
667 sink.push(UnresolvedMacroCall { file: ast.file_id, node: AstPtr::new(&node) }); 682 sink.push(UnresolvedMacroCall {
683 file: ast.file_id,
684 node: AstPtr::new(&node),
685 path: path.clone(),
686 });
668 } 687 }
669 688
670 DiagnosticKind::MacroError { ast, message } => { 689 DiagnosticKind::MacroError { ast, message } => {
671 let (file, ast) = match ast { 690 let (file, ast) = match ast {
672 MacroCallKind::FnLike(ast) => { 691 MacroCallKind::FnLike { ast_id, .. } => {
673 let node = ast.to_node(db.upcast()); 692 let node = ast_id.to_node(db.upcast());
674 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node))) 693 (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)))
675 } 694 }
676 MacroCallKind::Derive(ast, _) => { 695 MacroCallKind::Derive { ast_id, .. } => {
677 let node = ast.to_node(db.upcast()); 696 let node = ast_id.to_node(db.upcast());
678 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node))) 697 (ast_id.file_id, SyntaxNodePtr::from(AstPtr::new(&node)))
679 } 698 }
680 }; 699 };
681 sink.push(MacroError { file, node: ast, message: message.clone() }); 700 sink.push(MacroError { file, node: ast, message: message.clone() });
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs
index 492d8c71f..05ceb1efb 100644
--- a/crates/hir_def/src/nameres/collector.rs
+++ b/crates/hir_def/src/nameres/collector.rs
@@ -13,7 +13,7 @@ use hir_expand::{
13 builtin_macro::find_builtin_macro, 13 builtin_macro::find_builtin_macro,
14 name::{AsName, Name}, 14 name::{AsName, Name},
15 proc_macro::ProcMacroExpander, 15 proc_macro::ProcMacroExpander,
16 HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, 16 AttrId, HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
17}; 17};
18use hir_expand::{InFile, MacroCallLoc}; 18use hir_expand::{InFile, MacroCallLoc};
19use rustc_hash::{FxHashMap, FxHashSet}; 19use rustc_hash::{FxHashMap, FxHashSet};
@@ -216,7 +216,7 @@ struct MacroDirective {
216#[derive(Clone, Debug, Eq, PartialEq)] 216#[derive(Clone, Debug, Eq, PartialEq)]
217enum MacroDirectiveKind { 217enum MacroDirectiveKind {
218 FnLike { ast_id: AstIdWithPath<ast::MacroCall> }, 218 FnLike { ast_id: AstIdWithPath<ast::MacroCall> },
219 Derive { ast_id: AstIdWithPath<ast::Item> }, 219 Derive { ast_id: AstIdWithPath<ast::Item>, derive_attr: AttrId },
220} 220}
221 221
222struct DefData<'a> { 222struct DefData<'a> {
@@ -478,7 +478,7 @@ impl DefCollector<'_> {
478 self.def_map.edition, 478 self.def_map.edition,
479 ); 479 );
480 480
481 let res = self.def_map.resolve_name_in_extern_prelude(&extern_crate.name); 481 let res = self.def_map.resolve_name_in_extern_prelude(self.db, &extern_crate.name);
482 482
483 if let Some(ModuleDefId::ModuleId(m)) = res.take_types() { 483 if let Some(ModuleDefId::ModuleId(m)) = res.take_types() {
484 cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use); 484 cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use);
@@ -534,6 +534,7 @@ impl DefCollector<'_> {
534 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition); 534 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
535 if import.is_extern_crate { 535 if import.is_extern_crate {
536 let res = self.def_map.resolve_name_in_extern_prelude( 536 let res = self.def_map.resolve_name_in_extern_prelude(
537 self.db,
537 &import 538 &import
538 .path 539 .path
539 .as_ident() 540 .as_ident()
@@ -828,19 +829,23 @@ impl DefCollector<'_> {
828 res = ReachedFixedPoint::No; 829 res = ReachedFixedPoint::No;
829 return false; 830 return false;
830 } 831 }
831 Err(UnresolvedMacro) | Ok(Err(_)) => {} 832 Err(UnresolvedMacro { .. }) | Ok(Err(_)) => {}
832 } 833 }
833 } 834 }
834 MacroDirectiveKind::Derive { ast_id } => { 835 MacroDirectiveKind::Derive { ast_id, derive_attr } => {
835 match derive_macro_as_call_id(ast_id, self.db, self.def_map.krate, |path| { 836 match derive_macro_as_call_id(
836 self.resolve_derive_macro(directive.module_id, &path) 837 ast_id,
837 }) { 838 *derive_attr,
839 self.db,
840 self.def_map.krate,
841 |path| self.resolve_derive_macro(directive.module_id, &path),
842 ) {
838 Ok(call_id) => { 843 Ok(call_id) => {
839 resolved.push((directive.module_id, call_id, 0)); 844 resolved.push((directive.module_id, call_id, directive.depth));
840 res = ReachedFixedPoint::No; 845 res = ReachedFixedPoint::No;
841 return false; 846 return false;
842 } 847 }
843 Err(UnresolvedMacro) => (), 848 Err(UnresolvedMacro { .. }) => (),
844 } 849 }
845 } 850 }
846 } 851 }
@@ -938,10 +943,11 @@ impl DefCollector<'_> {
938 &mut |_| (), 943 &mut |_| (),
939 ) { 944 ) {
940 Ok(_) => (), 945 Ok(_) => (),
941 Err(UnresolvedMacro) => { 946 Err(UnresolvedMacro { path }) => {
942 self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call( 947 self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
943 directive.module_id, 948 directive.module_id,
944 ast_id.ast_id, 949 ast_id.ast_id,
950 path,
945 )); 951 ));
946 } 952 }
947 }, 953 },
@@ -1368,7 +1374,7 @@ impl ModCollector<'_, '_> {
1368 self.def_collector.unexpanded_macros.push(MacroDirective { 1374 self.def_collector.unexpanded_macros.push(MacroDirective {
1369 module_id: self.module_id, 1375 module_id: self.module_id,
1370 depth: self.macro_depth + 1, 1376 depth: self.macro_depth + 1,
1371 kind: MacroDirectiveKind::Derive { ast_id }, 1377 kind: MacroDirectiveKind::Derive { ast_id, derive_attr: derive.id },
1372 }); 1378 });
1373 } 1379 }
1374 } 1380 }
@@ -1520,12 +1526,12 @@ impl ModCollector<'_, '_> {
1520 // Built-in macro failed eager expansion. 1526 // Built-in macro failed eager expansion.
1521 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error( 1527 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1522 self.module_id, 1528 self.module_id,
1523 MacroCallKind::FnLike(ast_id.ast_id), 1529 MacroCallKind::FnLike { ast_id: ast_id.ast_id },
1524 error.unwrap().to_string(), 1530 error.unwrap().to_string(),
1525 )); 1531 ));
1526 return; 1532 return;
1527 } 1533 }
1528 Err(UnresolvedMacro) => (), 1534 Err(UnresolvedMacro { .. }) => (),
1529 } 1535 }
1530 1536
1531 // Case 2: resolve in module scope, expand during name resolution. 1537 // Case 2: resolve in module scope, expand during name resolution.
diff --git a/crates/hir_def/src/nameres/path_resolution.rs b/crates/hir_def/src/nameres/path_resolution.rs
index 60471937c..c984148c3 100644
--- a/crates/hir_def/src/nameres/path_resolution.rs
+++ b/crates/hir_def/src/nameres/path_resolution.rs
@@ -60,12 +60,26 @@ impl ResolvePathResult {
60} 60}
61 61
62impl DefMap { 62impl DefMap {
63 pub(super) fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs { 63 pub(super) fn resolve_name_in_extern_prelude(
64 &self,
65 db: &dyn DefDatabase,
66 name: &Name,
67 ) -> PerNs {
64 if name == &name!(self) { 68 if name == &name!(self) {
65 cov_mark::hit!(extern_crate_self_as); 69 cov_mark::hit!(extern_crate_self_as);
66 return PerNs::types(self.module_id(self.root).into(), Visibility::Public); 70 return PerNs::types(self.module_id(self.root).into(), Visibility::Public);
67 } 71 }
68 self.extern_prelude 72
73 let arc;
74 let root = match self.block {
75 Some(_) => {
76 arc = self.crate_root(db).def_map(db);
77 &*arc
78 }
79 None => sel