Repository: rust-analyzer/rust-analyzer
Pull request #6467 (2020-11-04 14:38:03)

Don't stack overflow on circular modules
bors r+
🤖


Patch:
diff --git a/crates/assists/src/handlers/add_custom_impl.rs b/crates/assists/src/handlers/add_custom_impl.rs
index 669dd9b217..8757fa33f2 100644
--- a/crates/assists/src/handlers/add_custom_impl.rs
+++ b/crates/assists/src/handlers/add_custom_impl.rs
@@ -1,16 +1,13 @@
-use ide_db::imports_locator;
 use itertools::Itertools;
 use syntax::{
-    ast::{self, make, AstNode},
+    ast::{self, AstNode},
     Direction, SmolStr,
     SyntaxKind::{IDENT, WHITESPACE},
     TextRange, TextSize,
 };
 
 use crate::{
-    assist_config::SnippetCap,
-    assist_context::{AssistBuilder, AssistContext, Assists},
-    utils::mod_path_to_ast,
+    assist_context::{AssistContext, Assists},
     AssistId, AssistKind,
 };
 
@@ -33,151 +30,78 @@ use crate::{
 // ```
 pub(crate) fn add_custom_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
     let attr = ctx.find_node_at_offset::<ast::Attr>()?;
+    let input = attr.token_tree()?;
 
     let attr_name = attr
         .syntax()
         .descendants_with_tokens()
         .filter(|t| t.kind() == IDENT)
-        .find_map(syntax::NodeOrToken::into_token)
-        .filter(|t| t.text() == "derive")?
+        .find_map(|i| i.into_token())
+        .filter(|t| *t.text() == "derive")?
         .text()
         .clone();
 
     let trait_token =
         ctx.token_at_offset().find(|t| t.kind() == IDENT && *t.text() != attr_name)?;
-    let trait_path = make::path_unqualified(make::path_segment(make::name_ref(trait_token.text())));
 
     let annotated = attr.syntax().siblings(Direction::Next).find_map(ast::Name::cast)?;
     let annotated_name = annotated.syntax().text().to_string();
-    let insert_pos = annotated.syntax().parent()?.text_range().end();
-
-    let current_module = ctx.sema.scope(annotated.syntax()).module()?;
-    let current_crate = current_module.krate();
-
-    let found_traits = imports_locator::find_imports(&ctx.sema, current_crate, trait_token.text())
-        .into_iter()
-        .filter_map(|candidate: either::Either<hir::ModuleDef, hir::MacroDef>| match candidate {
-            either::Either::Left(hir::ModuleDef::Trait(trait_)) => Some(trait_),
-            _ => None,
-        })
-        .flat_map(|trait_| {
-            current_module
-                .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
-                .as_ref()
-                .map(mod_path_to_ast)
-                .zip(Some(trait_))
-        });
+    let start_offset = annotated.syntax().parent()?.text_range().end();
 
-    let mut no_traits_found = true;
-    for (trait_path, _trait) in found_traits.inspect(|_| no_traits_found = false) {
-        add_assist(acc, ctx.config.snippet_cap, &attr, &trait_path, &annotated_name, insert_pos)?;
-    }
-    if no_traits_found {
-        add_assist(acc, ctx.config.snippet_cap, &attr, &trait_path, &annotated_name, insert_pos)?;
-    }
-    Some(())
-}
+    let label =
+        format!("Add custom impl `{}` for `{}`", trait_token.text().as_str(), annotated_name);
 
-fn add_assist(
-    acc: &mut Assists,
-    snippet_cap: Option<SnippetCap>,
-    attr: &ast::Attr,
-    trait_path: &ast::Path,
-    annotated_name: &str,
-    insert_pos: TextSize,
-) -> Option<()> {
     let target = attr.syntax().text_range();
-    let input = attr.token_tree()?;
-    let label = format!("Add custom impl `{}` for `{}`", trait_path, annotated_name);
-    let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
-
     acc.add(AssistId("add_custom_impl", AssistKind::Refactor), label, target, |builder| {
-        update_attribute(builder, &input, &trait_name, &attr);
-        match snippet_cap {
+        let new_attr_input = input
+            .syntax()
+            .descendants_with_tokens()
+            .filter(|t| t.kind() == IDENT)
+            .filter_map(|t| t.into_token().map(|t| t.text().clone()))
+            .filter(|t| t != trait_token.text())
+            .collect::<Vec<SmolStr>>();
+        let has_more_derives = !new_attr_input.is_empty();
+
+        if has_more_derives {
+            let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
+            builder.replace(input.syntax().text_range(), new_attr_input);
+        } else {
+            let attr_range = attr.syntax().text_range();
+            builder.delete(attr_range);
+
+            let line_break_range = attr
+                .syntax()
+                .next_sibling_or_token()
+                .filter(|t| t.kind() == WHITESPACE)
+                .map(|t| t.text_range())
+                .unwrap_or_else(|| TextRange::new(TextSize::from(0), TextSize::from(0)));
+            builder.delete(line_break_range);
+        }
+
+        match ctx.config.snippet_cap {
             Some(cap) => {
                 builder.insert_snippet(
                     cap,
-                    insert_pos,
-                    format!("\n\nimpl {} for {} {{\n    $0\n}}", trait_path, annotated_name),
+                    start_offset,
+                    format!("\n\nimpl {} for {} {{\n    $0\n}}", trait_token, annotated_name),
                 );
             }
             None => {
                 builder.insert(
-                    insert_pos,
-                    format!("\n\nimpl {} for {} {{\n\n}}", trait_path, annotated_name),
+                    start_offset,
+                    format!("\n\nimpl {} for {} {{\n\n}}", trait_token, annotated_name),
                 );
             }
         }
     })
 }
 
-fn update_attribute(
-    builder: &mut AssistBuilder,
-    input: &ast::TokenTree,
-    trait_name: &ast::NameRef,
-    attr: &ast::Attr,
-) {
-    let new_attr_input = input
-        .syntax()
-        .descendants_with_tokens()
-        .filter(|t| t.kind() == IDENT)
-        .filter_map(|t| t.into_token().map(|t| t.text().clone()))
-        .filter(|t| t != trait_name.text())
-        .collect::<Vec<SmolStr>>();
-    let has_more_derives = !new_attr_input.is_empty();
-
-    if has_more_derives {
-        let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
-        builder.replace(input.syntax().text_range(), new_attr_input);
-    } else {
-        let attr_range = attr.syntax().text_range();
-        builder.delete(attr_range);
-
-        let line_break_range = attr
-            .syntax()
-            .next_sibling_or_token()
-            .filter(|t| t.kind() == WHITESPACE)
-            .map(|t| t.text_range())
-            .unwrap_or_else(|| TextRange::new(TextSize::from(0), TextSize::from(0)));
-        builder.delete(line_break_range);
-    }
-}
-
 #[cfg(test)]
 mod tests {
     use crate::tests::{check_assist, check_assist_not_applicable};
 
     use super::*;
 
-    #[test]
-    fn add_custom_impl_qualified() {
-        check_assist(
-            add_custom_impl,
-            "
-mod fmt {
-    pub trait Debug {}
-}
-
-#[derive(Debu<|>g)]
-struct Foo {
-    bar: String,
-}
-",
-            "
-mod fmt {
-    pub trait Debug {}
-}
-
-struct Foo {
-    bar: String,
-}
-
-impl fmt::Debug for Foo {
-    $0
-}
-",
-        )
-    }
     #[test]
     fn add_custom_impl_for_unique_input() {
         check_assist(
diff --git a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs
index 14209b7714..dddab255ee 100644
--- a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs
+++ b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs
@@ -1,6 +1,3 @@
-use std::iter;
-
-use either::Either;
 use hir::{AsName, EnumVariant, Module, ModuleDef, Name};
 use ide_db::{defs::Definition, search::Reference, RootDatabase};
 use rustc_hash::{FxHashMap, FxHashSet};
@@ -34,32 +31,40 @@ pub(crate) fn extract_struct_from_enum_variant(
     ctx: &AssistContext,
 ) -> Option<()> {
     let variant = ctx.find_node_at_offset::<ast::Variant>()?;
-    let field_list = extract_field_list_if_applicable(&variant)?;
+    let field_list = match variant.kind() {
+        ast::StructKind::Tuple(field_list) => field_list,
+        _ => return None,
+    };
+
+    // skip 1-tuple variants
+    if field_list.fields().count() == 1 {
+        return None;
+    }
 
     let variant_name = variant.name()?;
     let variant_hir = ctx.sema.to_def(&variant)?;
-    if existing_definition(ctx.db(), &variant_name, &variant_hir) {
+    if existing_struct_def(ctx.db(), &variant_name, &variant_hir) {
         return None;
     }
-
     let enum_ast = variant.parent_enum();
+    let visibility = enum_ast.visibility();
     let enum_hir = ctx.sema.to_def(&enum_ast)?;
+    let variant_hir_name = variant_hir.name(ctx.db());
+    let enum_module_def = ModuleDef::from(enum_hir);
+    let current_module = enum_hir.module(ctx.db());
     let target = variant.syntax().text_range();
     acc.add(
         AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
         "Extract struct from enum variant",
         target,
         |builder| {
-            let variant_hir_name = variant_hir.name(ctx.db());
-            let enum_module_def = ModuleDef::from(enum_hir);
-            let usages =
-                Definition::ModuleDef(ModuleDef::EnumVariant(variant_hir)).usages(&ctx.sema).all();
+            let definition = Definition::ModuleDef(ModuleDef::EnumVariant(variant_hir));
+            let res = definition.usages(&ctx.sema).all();
 
             let mut visited_modules_set = FxHashSet::default();
-            let current_module = enum_hir.module(ctx.db());
             visited_modules_set.insert(current_module);
             let mut rewriters = FxHashMap::default();
-            for reference in usages {
+            for reference in res {
                 let rewriter = rewriters
                     .entry(reference.file_range.file_id)
                     .or_insert_with(SyntaxRewriter::default);
@@ -81,49 +86,26 @@ pub(crate) fn extract_struct_from_enum_variant(
                 builder.rewrite(rewriter);
             }
             builder.edit_file(ctx.frange.file_id);
-            update_variant(&mut rewriter, &variant);
+            update_variant(&mut rewriter, &variant_name, &field_list);
             extract_struct_def(
                 &mut rewriter,
                 &enum_ast,
                 variant_name.clone(),
                 &field_list,
                 &variant.parent_enum().syntax().clone().into(),
-                enum_ast.visibility(),
+                visibility,
             );
             builder.rewrite(rewriter);
         },
     )
 }
 
-fn extract_field_list_if_applicable(
-    variant: &ast::Variant,
-) -> Option<Either<ast::RecordFieldList, ast::TupleFieldList>> {
-    match variant.kind() {
-        ast::StructKind::Record(field_list) if field_list.fields().next().is_some() => {
-            Some(Either::Left(field_list))
-        }
-        ast::StructKind::Tuple(field_list) if field_list.fields().count() > 1 => {
-            Some(Either::Right(field_list))
-        }
-        _ => None,
-    }
-}
-
-fn existing_definition(db: &RootDatabase, variant_name: &ast::Name, variant: &EnumVariant) -> bool {
+fn existing_struct_def(db: &RootDatabase, variant_name: &ast::Name, variant: &EnumVariant) -> bool {
     variant
         .parent_enum(db)
         .module(db)
         .scope(db, None)
         .into_iter()
-        .filter(|(_, def)| match def {
-            // only check type-namespace
-            hir::ScopeDef::ModuleDef(def) => matches!(def,
-                ModuleDef::Module(_) | ModuleDef::Adt(_) |
-                ModuleDef::EnumVariant(_) | ModuleDef::Trait(_) |
-                ModuleDef::TypeAlias(_) | ModuleDef::BuiltinType(_)
-            ),
-            _ => false,
-        })
         .any(|(name, _)| name == variant_name.as_name())
 }
 
@@ -151,29 +133,19 @@ fn extract_struct_def(
     rewriter: &mut SyntaxRewriter,
     enum_: &ast::Enum,
     variant_name: ast::Name,
-    field_list: &Either<ast::RecordFieldList, ast::TupleFieldList>,
+    variant_list: &ast::TupleFieldList,
     start_offset: &SyntaxElement,
     visibility: Option<ast::Visibility>,
 ) -> Option<()> {
-    let pub_vis = Some(make::visibility_pub());
-    let field_list = match field_list {
-        Either::Left(field_list) => {
-            make::record_field_list(field_list.fields().flat_map(|field| {
-                Some(make::record_field(pub_vis.clone(), field.name()?, field.ty()?))
-            }))
-            .into()
-        }
-        Either::Right(field_list) => make::tuple_field_list(
-            field_list
-                .fields()
-                .flat_map(|field| Some(make::tuple_field(pub_vis.clone(), field.ty()?))),
-        )
-        .into(),
-    };
+    let variant_list = make::tuple_field_list(
+        variant_list
+            .fields()
+            .flat_map(|field| Some(make::tuple_field(Some(make::visibility_pub()), field.ty()?))),
+    );
 
     rewriter.insert_before(
         start_offset,
-        make::struct_(visibility, variant_name, None, field_list).syntax(),
+        make::struct_(visibility, variant_name, None, variant_list.into()).syntax(),
     );
     rewriter.insert_before(start_offset, &make::tokens::blank_line());
 
@@ -184,14 +156,15 @@ fn extract_struct_def(
     Some(())
 }
 
-fn update_variant(rewriter: &mut SyntaxRewriter, variant: &ast::Variant) -> Option<()> {
-    let name = variant.name()?;
-    let tuple_field = make::tuple_field(None, make::ty(name.text()));
-    let replacement = make::variant(
-        name,
-        Some(ast::FieldList::TupleFieldList(make::tuple_field_list(iter::once(tuple_field)))),
-    );
-    rewriter.replace(variant.syntax(), replacement.syntax());
+fn update_variant(
+    rewriter: &mut SyntaxRewriter,
+    variant_name: &ast::Name,
+    field_list: &ast::TupleFieldList,
+) -> Option<()> {
+    let (l, r): (SyntaxElement, SyntaxElement) =
+        (field_list.l_paren_token()?.into(), field_list.r_paren_token()?.into());
+    let replacement = vec![l, variant_name.syntax().clone().into(), r];
+    rewriter.replace_with_many(field_list.syntax(), replacement);
     Some(())
 }
 
@@ -238,47 +211,12 @@ mod tests {
     use super::*;
 
     #[test]
-    fn test_extract_struct_several_fields_tuple() {
+    fn test_extract_struct_several_fields() {
         check_assist(
             extract_struct_from_enum_variant,
             "enum A { <|>One(u32, u32) }",
             r#"struct One(pub u32, pub u32);
 
-enum A { One(One) }"#,
-        );
-    }
-
-    #[test]
-    fn test_extract_struct_several_fields_named() {
-        check_assist(
-            extract_struct_from_enum_variant,
-            "enum A { <|>One { foo: u32, bar: u32 } }",
-            r#"struct One{ pub foo: u32, pub bar: u32 }
-
-enum A { One(One) }"#,
-        );
-    }
-
-    #[test]
-    fn test_extract_struct_one_field_named() {
-        check_assist(
-            extract_struct_from_enum_variant,
-            "enum A { <|>One { foo: u32 } }",
-            r#"struct One{ pub foo: u32 }
-
-enum A { One(One) }"#,
-        );
-    }
-
-    #[test]
-    fn test_extract_enum_variant_name_value_namespace() {
-        check_assist(
-            extract_struct_from_enum_variant,
-            r#"const One: () = ();
-enum A { <|>One(u32, u32) }"#,
-            r#"const One: () = ();
-struct One(pub u32, pub u32);
-
 enum A { One(One) }"#,
         );
     }
@@ -360,7 +298,7 @@ fn another_fn() {
     fn test_extract_enum_not_applicable_if_struct_exists() {
         check_not_applicable(
             r#"struct One;
-        enum A { <|>One(u8, u32) }"#,
+        enum A { <|>One(u8) }"#,
         );
     }
 
@@ -368,14 +306,4 @@ fn another_fn() {
     fn test_extract_not_applicable_one_field() {
         check_not_applicable(r"enum A { <|>One(u32) }");
     }
-
-    #[test]
-    fn test_extract_not_applicable_no_field_tuple() {
-        check_not_applicable(r"enum A { <|>None() }");
-    }
-
-    #[test]
-    fn test_extract_not_applicable_no_field_named() {
-        check_not_applicable(r"enum A { <|>None {} }");
-    }
 }
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs
index 59b6644c38..386287518a 100644
--- a/crates/hir_def/src/nameres/collector.rs
+++ b/crates/hir_def/src/nameres/collector.rs
@@ -1116,17 +1116,20 @@ impl ModCollector<'_, '_> {
                     &self.item_tree[module.visibility],
                 );
 
-                ModCollector {
-                    def_collector: &mut *self.def_collector,
-                    macro_depth: self.macro_depth,
-                    module_id,
-                    file_id: self.file_id,
-                    item_tree: self.item_tree,
-                    mod_dir: self.mod_dir.descend_into_definition(&module.name, path_attr),
-                }
-                .collect(&*items);
-                if is_macro_use {
-                    self.import_all_legacy_macros(module_id);
+                if let Some(mod_dir) = self.mod_dir.descend_into_definition(&module.name, path_attr)
+                {
+                    ModCollector {
+                        def_collector: &mut *self.def_collector,
+                        macro_depth: self.macro_depth,
+                        module_id,
+                        file_id: self.file_id,
+                        item_tree: self.item_tree,
+                        mod_dir,
+                    }
+                    .collect(&*items);
+                    if is_macro_use {
+                        self.import_all_legacy_macros(module_id);
+                    }
                 }
             }
             // out of line module, resolve, parse and recurse
diff --git a/crates/hir_def/src/nameres/mod_resolution.rs b/crates/hir_def/src/nameres/mod_resolution.rs
index e8389b4846..c0c789caef 100644
--- a/crates/hir_def/src/nameres/mod_resolution.rs
+++ b/crates/hir_def/src/nameres/mod_resolution.rs
@@ -2,9 +2,12 @@
 use base_db::FileId;
 use hir_expand::name::Name;
 use syntax::SmolStr;
+use test_utils::mark;
 
 use crate::{db::DefDatabase, HirFileId};
 
+const MOD_DEPTH_LIMIT: u32 = 32;
+
 #[derive(Clone, Debug)]
 pub(super) struct ModDir {
     /// `` for `mod.rs`, `lib.rs`
@@ -14,18 +17,28 @@ pub(super) struct ModDir {
     dir_path: DirPath,
     /// inside `./foo.rs`, mods with `#[path]` should *not* be relative to `./foo/`
     root_non_dir_owner: bool,
+    depth: u32,
 }
 
 impl ModDir {
     pub(super) fn root() -> ModDir {
-        ModDir { dir_path: DirPath::empty(), root_non_dir_owner: false }
+        ModDir { dir_path: DirPath::empty(), root_non_dir_owner: false, depth: 0 }
+    }
+    fn child(&self, dir_path: DirPath, root_non_dir_owner: bool) -> Option<ModDir> {
+        let depth = self.depth + 1;
+        if depth > MOD_DEPTH_LIMIT {
+            log::error!("MOD_DEPTH_LIMIT exceeded");
+            mark::hit!(circular_mods);
+            return None;
+        }
+        Some(ModDir { dir_path, root_non_dir_owner, depth })
     }
 
     pub(super) fn descend_into_definition(
         &self,
         name: &Name,
         attr_path: Option<&SmolStr>,
-    ) -> ModDir {
+    ) -> Option<ModDir> {
         let path = match attr_path.map(|it| it.as_str()) {
             None => {
                 let mut path = self.dir_path.clone();
@@ -40,7 +53,7 @@ impl ModDir {
                 DirPath::new(path)
             }
         };
-        ModDir { dir_path: path, root_non_dir_owner: false }
+        self.child(path, false)
     }
 
     pub(super) fn resolve_declaration(
@@ -72,7 +85,9 @@ impl ModDir {
                 } else {
                     (DirPath::new(format!("{}/", name)), true)
                 };
-                return Ok((file_id, is_mod_rs, ModDir { dir_path, root_non_dir_owner }));
+                if let Some(mod_dir) = self.child(dir_path, root_non_dir_owner) {
+                    return Ok((file_id, is_mod_rs, mod_dir));
+                }
             }
         }
         Err(candidate_files.remove(0))
diff --git a/crates/ide/src/diagnostics/fixes.rs b/crates/ide/src/diagnostics/fixes.rs
index d275dd75ba..02e17ba437 100644
--- a/crates/ide/src/diagnostics/fixes.rs
+++ b/crates/ide/src/diagnostics/fixes.rs
@@ -157,8 +157,7 @@ fn missing_record_expr_field_fix(
         return None;
     }
     let new_field = make::record_field(
-        None,
-        make::name(record_expr_field.field_name()?.text()),
+        record_expr_field.field_name()?,
         make::ty(&new_field_type.display_source_code(sema.db, module.into()).ok()?),
     );
 
diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs
index b1578820fe..2cf436e7a1 100644
--- a/crates/syntax/src/ast/make.rs
+++ b/crates/syntax/src/ast/make.rs
@@ -110,16 +110,8 @@ pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::Re
     }
 }
 
-pub fn record_field(
-    visibility: Option<ast::Visibility>,
-    name: ast::Name,
-    ty: ast::Type,
-) -> ast::RecordField {
-    let visibility = match visibility {
-        None => String::new(),
-        Some(it) => format!("{} ", it),
-    };
-    ast_from_text(&format!("struct S {{ {}{}: {}, }}", visibility, name, ty))
+pub fn record_field(name: ast::NameRef, ty: ast::Type) -> ast::RecordField {
+    ast_from_text(&format!("struct S {{ {}: {}, }}", name, ty))
 }
 
 pub fn block_expr(
@@ -368,13 +360,6 @@ pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> as
     ast_from_text(&format!("struct f({});", fields))
 }
 
-pub fn record_field_list(
-    fields: impl IntoIterator<Item = ast::RecordField>,
-) -> ast::RecordFieldList {
-    let fields = fields.into_iter().join(", ");
-    ast_from_text(&format!("struct f {{ {} }}", fields))
-}
-
 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
     let visibility = match visibility {
         None => String::new(),
@@ -383,14 +368,6 @@ pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::T
     ast_from_text(&format!("struct f({}{});", visibility, ty))
 }
 
-pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
-    let field_list = match field_list {
-        None => String::new(),
-        Some(it) => format!("{}", it),
-    };
-    ast_from_text(&format!("enum f {{ {}{} }}", name, field_list))
-}
-
 pub fn fn_(
     visibility: Option<ast::Visibility>,
     fn_name: ast::Name,


Test patch:
diff --git a/crates/hir_def/src/nameres/tests.rs b/crates/hir_def/src/nameres/tests.rs
index 9c19bf572f..a4d1fb8f31 100644
--- a/crates/hir_def/src/nameres/tests.rs
+++ b/crates/hir_def/src/nameres/tests.rs
@@ -20,9 +20,8 @@ fn compute_crate_def_map(fixture: &str) -> Arc<CrateDefMap> {
 }
 
 fn check(ra_fixture: &str, expect: Expect) {
-    let db = TestDB::with_files(ra_fixture);
-    let krate = db.crate_graph().iter().next().unwrap();
-    let actual = db.crate_def_map(krate).dump();
+    let def_map = compute_crate_def_map(ra_fixture);
+    let actual = def_map.dump();
     expect.assert_eq(&actual);
 }
 
diff --git a/crates/hir_def/src/nameres/tests/mod_resolution.rs b/crates/hir_def/src/nameres/tests/mod_resolution.rs
index ec9d589a34..ba295fd9e0 100644
--- a/crates/hir_def/src/nameres/tests/mod_resolution.rs
+++ b/crates/hir_def/src/nameres/tests/mod_resolution.rs
@@ -771,3 +771,30 @@ struct X;
         "#]],
     );
 }
+
+#[test]
+fn circular_mods() {
+    mark::check!(circular_mods);
+    compute_crate_def_map(
+        r#"
+//- /lib.rs
+mod foo;
+//- /foo.rs
+#[path = "./foo.rs"]
+mod foo;
+"#,
+    );
+
+    compute_crate_def_map(
+        r#"
+//- /lib.rs
+mod foo;
+//- /foo.rs
+#[path = "./bar.rs"]
+mod bar;
+//- /bar.rs
+#[path = "./foo.rs"]
+mod foo;
+"#,
+    );
+}