Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Author: GreasySlug <[email protected]>
# This theme is base on base16_theme(Author: NNB <[email protected]>)

"ui.background" = { fg = "white"}
"ui.background.separator" = { fg = "gray" }
"ui.text" = { fg = "light-gray" }
"ui.text.focus" = { fg = "white" }
"ui.menu" = { fg = "white" }
"ui.menu.selected" = { modifiers = ["reversed"] }
"ui.menu.scroll" = { fg = "light-gray" }
"ui.linenr" = { fg = "light-gray" }
"ui.linenr.selected" = { fg = "white",  modifiers = ["bold"] }
"ui.popup" = { fg = "white" }
"ui.window" = { fg = "gray" }
"ui.selection" = { bg = "gray" }
"comment" = "light-gray"
"ui.statusline" = { fg = "white" }
"ui.statusline.inactive" = { fg = "gray" }
"ui.statusline.normal" = { fg = "black", bg = "blue" }
"ui.statusline.insert" = { fg = "black", bg = "green" }
"ui.statusline.select" = { fg = "black", bg = "magenta" }
"ui.help" = { fg = "light-gray" }
"ui.cursor" = { modifiers = ["reversed"] }
"ui.cursor.match" = { fg = "light-yellow", underline = { color = "light-yellow", style = "line" } }
"ui.cursor.primary" = { modifiers = ["reversed", "slow_blink"] }
"ui.cursor.secondary" = { modifiers = ["reversed"] }
"ui.virtual.ruler" = { bg = "gray" }
"ui.virtual.whitespace" = "gray"
"ui.virtual.indent-guide" = "gray"
"ui.virtual.inlay-hint" = { fg = "white", bg = "gray" }
"ui.virtual.inlay-hint.parameter" = { fg = "white", bg = "gray"}
"ui.virtual.inlay-hint.type" = { fg = "white", bg = "gray"}
"ui.virtual.wrap" = "gray"

"variable" = "light-red"
"constant.numeric" = "yellow"
"constant" = "yellow"
"attribute" = "yellow"
"type" = "light-yellow"
"string"  = "light-green"
"variable.other.member" = "green"
"constant.character.escape" = "light-cyan"
"function" = "light-blue"
"constructor" = "light-blue"
"special" = "light-blue"
"keyword" = "light-magenta"
"label" = "light-magenta"
"namespace" = "light-magenta"

"markup.heading" = "light-blue"
"markup.list" = "light-red"
"markup.bold" = { fg = "light-yellow", modifiers = ["bold"] }
"markup.italic" = { fg = "light-magenta", modifiers = ["italic"] }
"markup.strikethrough" = { modifiers = ["crossed_out"] }
"markup.link.url" = { fg = "yellow", underline = { color = "yellow", style = "line"} }
"markup.link.text" = "light-red"
"markup.quote" = "light-cyan"
"markup.raw" = "green"
"markup.normal" = { fg = "blue" }
"markup.insert" = { fg = "green" }
"markup.select" = { fg = "magenta" }

"diff.plus" = "light-green"
"diff.delta" = "light-blue"
"diff.delta.moved" = "blue"
"diff.minus" = "light-red"

"ui.gutter" = "gray"
"info" = "light-blue"
"hint" = "light-gray"
"debug" = "light-gray"
"warning" = "light-yellow"
"error" = "light-red"

"diagnostic.info" = { underline = { color = "light-blue", style = "dotted" } }
"diagnostic.hint" = { underline = { color = "light-gray", style = "double_line" } }
"diagnostic.debug" = { underline ={ color ="light-gray", style = "dashed" } }
"diagnostic.warning" = { underline = { color = "light-yellow", style = "curl" } }
"diagnostic.error" = { underline = { color ="light-red", style = "curl" } }
a id='n253' href='#n253'>253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
//! Completes mod declarations.

use std::iter;

use hir::{HirFileIdExt, Module};
use ide_db::{
    base_db::{SourceRootDatabase, VfsPath},
    FxHashSet, RootDatabase, SymbolKind,
};
use syntax::{ast, AstNode, SyntaxKind, ToSmolStr};

use crate::{context::CompletionContext, CompletionItem, Completions};

/// Complete mod declaration, i.e. `mod $0;`
pub(crate) fn complete_mod(
    acc: &mut Completions,
    ctx: &CompletionContext<'_>,
    mod_under_caret: &ast::Module,
) -> Option<()> {
    if mod_under_caret.item_list().is_some() {
        return None;
    }

    let _p = tracing::info_span!("completion::complete_mod").entered();

    let mut current_module = ctx.module;
    // For `mod $0`, `ctx.module` is its parent, but for `mod f$0`, it's `mod f` itself, but we're
    // interested in its parent.
    if ctx.original_token.kind() == SyntaxKind::IDENT {
        if let Some(module) =
            ctx.original_token.parent_ancestors().nth(1).and_then(ast::Module::cast)
        {
            match ctx.sema.to_def(&module) {
                Some(module) if module == current_module => {
                    if let Some(parent) = current_module.parent(ctx.db) {
                        current_module = parent;
                    }
                }
                _ => {}
            }
        }
    }

    let module_definition_file =
        current_module.definition_source_file_id(ctx.db).original_file(ctx.db);
    let source_root = ctx.db.source_root(ctx.db.file_source_root(module_definition_file.file_id()));
    let directory_to_look_for_submodules = directory_to_look_for_submodules(
        current_module,
        ctx.db,
        source_root.path_for_file(&module_definition_file.file_id())?,
    )?;

    let existing_mod_declarations = current_module
        .children(ctx.db)
        .filter_map(|module| Some(module.name(ctx.db)?.display(ctx.db, ctx.edition).to_string()))
        .filter(|module| module != ctx.original_token.text())
        .collect::<FxHashSet<_>>();

    let module_declaration_file =
        current_module.declaration_source_range(ctx.db).map(|module_declaration_source_file| {
            module_declaration_source_file.file_id.original_file(ctx.db)
        });

    source_root
        .iter()
        .filter(|&submodule_candidate_file| submodule_candidate_file != module_definition_file)
        .filter(|&submodule_candidate_file| {
            module_declaration_file.is_none_or(|it| it != submodule_candidate_file)
        })
        .filter_map(|submodule_file| {
            let submodule_path = source_root.path_for_file(&submodule_file)?;
            let directory_with_submodule = submodule_path.parent()?;
            let (name, ext) = submodule_path.name_and_extension()?;
            if ext != Some("rs") {
                return None;
            }
            match name {
                "lib" | "main" => None,
                "mod" => {
                    if directory_with_submodule.parent()? == directory_to_look_for_submodules {
                        match directory_with_submodule.name_and_extension()? {
                            (directory_name, None) => Some(directory_name.to_owned()),
                            _ => None,
                        }
                    } else {
                        None
                    }
                }
                file_name if directory_with_submodule == directory_to_look_for_submodules => {
                    Some(file_name.to_owned())
                }
                _ => None,
            }
        })
        .filter(|name| !existing_mod_declarations.contains(name))
        .for_each(|submodule_name| {
            let mut label = submodule_name;
            if mod_under_caret.semicolon_token().is_none() {
                label.push(';');
            }
            let item =
                CompletionItem::new(SymbolKind::Module, ctx.source_range(), &label, ctx.edition);
            item.add_to(acc, ctx.db)
        });

    Some(())
}

fn directory_to_look_for_submodules(
    module: Module,
    db: &RootDatabase,
    module_file_path: &VfsPath,
) -> Option<VfsPath> {
    let directory_with_module_path = module_file_path.parent()?;
    let (name, ext) = module_file_path.name_and_extension()?;
    if ext != Some("rs") {
        return None;
    }
    let base_directory = match name {
        "mod" | "lib" | "main" => Some(directory_with_module_path),
        regular_rust_file_name => {
            if matches!(
                (
                    directory_with_module_path
                        .parent()
                        .as_ref()
                        .and_then(|path| path.name_and_extension()),
                    directory_with_module_path.name_and_extension(),
                ),
                (Some(("src", None)), Some(("bin", None)))
            ) {
                // files in /src/bin/ can import each other directly
                Some(directory_with_module_path)
            } else {
                directory_with_module_path.join(regular_rust_file_name)
            }
        }
    }?;

    module_chain_to_containing_module_file(module, db)
        .into_iter()
        .filter_map(|module| module.name(db))
        .try_fold(base_directory, |path, name| {
            path.join(&name.unescaped().display_no_db().to_smolstr())
        })
}

fn module_chain_to_containing_module_file(
    current_module: Module,
    db: &RootDatabase,
) -> Vec<Module> {
    let mut path =
        iter::successors(Some(current_module), |current_module| current_module.parent(db))
            .take_while(|current_module| current_module.is_inline(db))
            .collect::<Vec<_>>();
    path.reverse();
    path
}

#[cfg(test)]
mod tests {
    use expect_test::{expect, Expect};

    use crate::tests::completion_list;

    fn check(ra_fixture: &str, expect: Expect) {
        let actual = completion_list(ra_fixture);
        expect.assert_eq(&actual);
    }

    #[test]
    fn lib_module_completion() {
        check(
            r#"
//- /lib.rs
mod $0
//- /foo.rs
fn foo() {}
//- /foo/ignored_foo.rs
fn ignored_foo() {}
//- /bar/mod.rs
fn bar() {}
//- /bar/ignored_bar.rs
fn ignored_bar() {}
"#,
            expect![[r#"
                md bar;
                md foo;
            "#]],
        );
    }

    #[test]
    fn no_module_completion_with_module_body() {
        check(
            r#"
//- /lib.rs
mod $0 {

}
//- /foo.rs
fn foo() {}
"#,
            expect![[r#""#]],
        );
    }

    #[test]
    fn main_module_completion() {
        check(
            r#"
//- /main.rs
mod $0
//- /foo.rs
fn foo() {}
//- /foo/ignored_foo.rs
fn ignored_foo() {}
//- /bar/mod.rs
fn bar() {}
//- /bar/ignored_bar.rs
fn ignored_bar() {}
"#,
            expect![[r#"
                md bar;
                md foo;
            "#]],
        );
    }

    #[test]
    fn main_test_module_completion() {
        check(
            r#"
//- /main.rs
mod tests {
    mod $0;
}
//- /tests/foo.rs
fn foo() {}
"#,
            expect![[r#"
                md foo
            "#]],
        );
    }

    #[test]
    fn directly_nested_module_completion() {
        check(
            r#"
//- /lib.rs
mod foo;
//- /foo.rs
mod $0;
//- /foo/bar.rs
fn bar() {}
//- /foo/bar/ignored_bar.rs
fn ignored_bar() {}
//- /foo/baz/mod.rs
fn baz() {}
//- /foo/moar/ignored_moar.rs
fn ignored_moar() {}
"#,
            expect![[r#"
                md bar
                md baz
            "#]],
        );
    }

    #[test]
    fn nested_in_source_module_completion() {
        check(
            r#"
//- /lib.rs
mod foo;
//- /foo.rs
mod bar {
    mod $0
}
//- /foo/bar/baz.rs
fn baz() {}
"#,
            expect![[r#"
                md baz;
            "#]],
        );
    }

    // FIXME binary modules are not supported in tests properly
    // Binary modules are a bit special, they allow importing the modules from `/src/bin`
    // and that's why are good to test two things:
    // * no cycles are allowed in mod declarations
    // * no modules from the parent directory are proposed
    // Unfortunately, binary modules support is in cargo not rustc,
    // hence the test does not work now
    //
    // #[test]
    // fn regular_bin_module_completion() {
    //     check(
    //         r#"
    //         //- /src/bin.rs
    //         fn main() {}
    //         //- /src/bin/foo.rs
    //         mod $0
    //         //- /src/bin/bar.rs
    //         fn bar() {}
    //         //- /src/bin/bar/bar_ignored.rs
    //         fn bar_ignored() {}
    //     "#,
    //         expect![[r#"
    //             md bar;
    //         "#]],foo
    //     );
    // }

    #[test]
    fn already_declared_bin_module_completion_omitted() {
        check(
            r#"
//- /src/bin.rs crate:main
fn main() {}
//- /src/bin/foo.rs
mod $0
//- /src/bin/bar.rs
mod foo;
fn bar() {}
//- /src/bin/bar/bar_ignored.rs
fn bar_ignored() {}
"#,
            expect![[r#""#]],
        );
    }

    #[test]
    fn name_partially_typed() {
        check(
            r#"
//- /lib.rs
mod f$0
//- /foo.rs
fn foo() {}
//- /foo/ignored_foo.rs
fn ignored_foo() {}
//- /bar/mod.rs
fn bar() {}
//- /bar/ignored_bar.rs
fn ignored_bar() {}
"#,
            expect![[r#"
                md bar;
                md foo;
            "#]],
        );
    }

    #[test]
    fn semi_colon_completion() {
        check(
            r#"
//- /lib.rs
mod foo;
//- /foo.rs
mod bar {
    mod baz$0
}
//- /foo/bar/baz.rs
fn baz() {}
"#,
            expect![[r#"
                md baz;
            "#]],
        );
    }
}