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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//! Monomorphization of mir, which is used in mir interpreter and const eval.
//!
//! The job of monomorphization is:
//! * Monomorphization. That is, replacing `Option<T>` with `Option<i32>` where `T:=i32` substitution
//!   is provided
//! * Normalizing types, for example replacing RPIT of other functions called in this body.
//!
//! So the monomorphization should be called even if the substitution is empty.

use hir_def::DefWithBodyId;
use rustc_type_ir::inherent::IntoKind;
use rustc_type_ir::{
    FallibleTypeFolder, TypeFlags, TypeFoldable, TypeSuperFoldable, TypeVisitableExt,
};
use triomphe::Arc;

use crate::{
    ParamEnvAndCrate,
    next_solver::{
        Allocation, AllocationData, Const, ConstKind, Region, RegionKind, StoredConst,
        StoredGenericArgs, StoredTy,
    },
    traits::StoredParamEnvAndCrate,
};
use crate::{
    db::{HirDatabase, InternedClosureId},
    next_solver::{
        DbInterner, GenericArgs, Ty, TyKind, TypingMode,
        infer::{DbInternerInferExt, InferCtxt, traits::ObligationCause},
        obligation_ctxt::ObligationCtxt,
        references_non_lt_error,
    },
};

use super::{MirBody, MirLowerError, Operand, OperandKind, Rvalue, StatementKind, TerminatorKind};

struct Filler<'db> {
    infcx: InferCtxt<'db>,
    trait_env: ParamEnvAndCrate<'db>,
    subst: GenericArgs<'db>,
}

impl<'db> FallibleTypeFolder<DbInterner<'db>> for Filler<'db> {
    type Error = MirLowerError;

    fn cx(&self) -> DbInterner<'db> {
        self.infcx.interner
    }

    fn try_fold_ty(&mut self, ty: Ty<'db>) -> Result<Ty<'db>, Self::Error> {
        if !ty.has_type_flags(TypeFlags::HAS_ALIAS | TypeFlags::HAS_PARAM) {
            return Ok(ty);
        }

        match ty.kind() {
            TyKind::Alias(..) => {
                // First instantiate params.
                let ty = ty.try_super_fold_with(self)?;

                let mut ocx = ObligationCtxt::new(&self.infcx);
                let ty = ocx
                    .structurally_normalize_ty(
                        &ObligationCause::dummy(),
                        self.trait_env.param_env,
                        ty,
                    )
                    .map_err(|_| MirLowerError::NotSupported("can't normalize alias".to_owned()))?;
                ty.try_super_fold_with(self)
            }
            TyKind::Param(param) => Ok(self
                .subst
                .as_slice()
                .get(param.index as usize)
                .and_then(|arg| arg.ty())
                .ok_or_else(|| {
                    MirLowerError::GenericArgNotProvided(param.id.into(), self.subst.store())
                })?),
            _ => ty.try_super_fold_with(self),
        }
    }

    fn try_fold_const(&mut self, ct: Const<'db>) -> Result<Const<'db>, Self::Error> {
        let ConstKind::Param(param) = ct.kind() else {
            return ct.try_super_fold_with(self);
        };
        self.subst.as_slice().get(param.index as usize).and_then(|arg| arg.konst()).ok_or_else(
            || MirLowerError::GenericArgNotProvided(param.id.into(), self.subst.store()),
        )
    }

    fn try_fold_region(&mut self, region: Region<'db>) -> Result<Region<'db>, Self::Error> {
        let RegionKind::ReEarlyParam(param) = region.kind() else {
            return Ok(region);
        };
        self.subst.as_slice().get(param.index as usize).and_then(|arg| arg.region()).ok_or_else(
            || MirLowerError::GenericArgNotProvided(param.id.into(), self.subst.store()),
        )
    }
}

impl<'db> Filler<'db> {
    fn new(db: &'db dyn HirDatabase, env: ParamEnvAndCrate<'db>, subst: GenericArgs<'db>) -> Self {
        let interner = DbInterner::new_with(db, env.krate);
        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
        Self { infcx, trait_env: env, subst }
    }

    fn fill_ty(&mut self, t: &mut StoredTy) -> Result<(), MirLowerError> {
        // Can't deep normalized as that'll try to normalize consts and fail.
        *t = t.as_ref().try_fold_with(self)?.store();
        if references_non_lt_error(&t.as_ref()) {
            Err(MirLowerError::NotSupported("monomorphization resulted in errors".to_owned()))
        } else {
            Ok(())
        }
    }

    fn fill_const(&mut self, t: &mut StoredConst) -> Result<(), MirLowerError> {
        // Can't deep normalized as that'll try to normalize consts and fail.
        *t = t.as_ref().try_fold_with(self)?.store();
        if references_non_lt_error(&t.as_ref()) {
            Err(MirLowerError::NotSupported("monomorphization resulted in errors".to_owned()))
        } else {
            Ok(())
        }
    }

    fn fill_args(&mut self, t: &mut StoredGenericArgs) -> Result<(), MirLowerError> {
        // Can't deep normalized as that'll try to normalize consts and fail.
        *t = t.as_ref().try_fold_with(self)?.store();
        if references_non_lt_error(&t.as_ref()) {
            Err(MirLowerError::NotSupported("monomorphization resulted in errors".to_owned()))
        } else {
            Ok(())
        }
    }

    fn fill_operand(&mut self, op: &mut Operand) -> Result<(), MirLowerError> {
        match &mut op.kind {
            OperandKind::Constant { konst, ty } => {
                self.fill_const(konst)?;
                self.fill_ty(ty)?;
            }
            OperandKind::Allocation { allocation } => {
                let alloc = allocation.as_ref();
                let mut ty = alloc.ty.store();
                self.fill_ty(&mut ty)?;
                *allocation = Allocation::new(AllocationData {
                    ty: ty.as_ref(),
                    memory: alloc.memory.clone(),
                    // FIXME: Do we need to fill the memory map too?
                    memory_map: alloc.memory_map.clone(),
                })
                .store();
            }
            OperandKind::Copy(_) | OperandKind::Move(_) | OperandKind::Static(_) => (),
        }
        Ok(())
    }

    fn fill_body(&mut self, body: &mut MirBody) -> Result<(), MirLowerError> {
        for (_, l) in body.locals.iter_mut() {
            self.fill_ty(&mut l.ty)?;
        }
        for (_, bb) in body.basic_blocks.iter_mut() {
            for statement in &mut bb.statements {
                match &mut statement.kind {
                    StatementKind::Assign(_, r) => match r {
                        Rvalue::Aggregate(ak, ops) => {
                            for op in &mut **ops {
                                self.fill_operand(op)?;
                            }
                            match ak {
                                super::AggregateKind::Array(ty)
                                | super::AggregateKind::Tuple(ty)
                                | super::AggregateKind::Closure(ty) => self.fill_ty(ty)?,
                                super::AggregateKind::Adt(_, subst) => self.fill_args(subst)?,
                                super::AggregateKind::Union(_, _) => (),
                            }
                        }
                        Rvalue::ShallowInitBox(_, ty) | Rvalue::ShallowInitBoxWithAlloc(ty) => {
                            self.fill_ty(ty)?;
                        }
                        Rvalue::Use(op) => {
                            self.fill_operand(op)?;
                        }
                        Rvalue::Repeat(op, len) => {
                            self.fill_operand(op)?;
                            self.fill_const(len)?;
                        }
                        Rvalue::Ref(_, _)
                        | Rvalue::Len(_)
                        | Rvalue::Cast(_, _, _)
                        | Rvalue::CheckedBinaryOp(_, _, _)
                        | Rvalue::UnaryOp(_, _)
                        | Rvalue::Discriminant(_)
                        | Rvalue::CopyForDeref(_) => (),
                        Rvalue::ThreadLocalRef(n)
                        | Rvalue::AddressOf(n)
                        | Rvalue::BinaryOp(n)
                        | Rvalue::NullaryOp(n) => match *n {},
                    },
                    StatementKind::Deinit(_)
                    | StatementKind::FakeRead(_)
                    | StatementKind::StorageLive(_)
                    | StatementKind::StorageDead(_)
                    | StatementKind::Nop => (),
                }
            }
            if let Some(terminator) = &mut bb.terminator {
                match &mut terminator.kind {
                    TerminatorKind::Call { func, args, .. } => {
                        self.fill_operand(func)?;
                        for op in &mut **args {
                            self.fill_operand(op)?;
                        }
                    }
                    TerminatorKind::SwitchInt { discr, .. } => {
                        self.fill_operand(discr)?;
                    }
                    TerminatorKind::Goto { .. }
                    | TerminatorKind::UnwindResume
                    | TerminatorKind::Abort
                    | TerminatorKind::Return
                    | TerminatorKind::Unreachable
                    | TerminatorKind::Drop { .. }
                    | TerminatorKind::DropAndReplace { .. }
                    | TerminatorKind::Assert { .. }
                    | TerminatorKind::Yield { .. }
                    | TerminatorKind::CoroutineDrop
                    | TerminatorKind::FalseEdge { .. }
                    | TerminatorKind::FalseUnwind { .. } => (),
                }
            }
        }
        Ok(())
    }
}

pub fn monomorphized_mir_body_query(
    db: &dyn HirDatabase,
    owner: DefWithBodyId,
    subst: StoredGenericArgs,
    trait_env: StoredParamEnvAndCrate,
) -> Result<Arc<MirBody>, MirLowerError> {
    let mut filler = Filler::new(db, trait_env.as_ref(), subst.as_ref());
    let body = db.mir_body(owner)?;
    let mut body = (*body).clone();
    filler.fill_body(&mut body)?;
    Ok(Arc::new(body))
}

pub(crate) fn monomorphized_mir_body_cycle_result(
    _db: &dyn HirDatabase,
    _: salsa::Id,
    _: DefWithBodyId,
    _: StoredGenericArgs,
    _: StoredParamEnvAndCrate,
) -> Result<Arc<MirBody>, MirLowerError> {
    Err(MirLowerError::Loop)
}

pub fn monomorphized_mir_body_for_closure_query(
    db: &dyn HirDatabase,
    closure: InternedClosureId,
    subst: StoredGenericArgs,
    trait_env: StoredParamEnvAndCrate,
) -> Result<Arc<MirBody>, MirLowerError> {
    let mut filler = Filler::new(db, trait_env.as_ref(), subst.as_ref());
    let body = db.mir_body_for_closure(closure)?;
    let mut body = (*body).clone();
    filler.fill_body(&mut body)?;
    Ok(Arc::new(body))
}
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
use std::iter;

use expect_test::{expect, Expect};
use hir::Semantics;
use ide_db::{
    defs::Definition,
    documentation::{Documentation, HasDocs},
    FilePosition, FileRange, RootDatabase,
};
use itertools::Itertools;
use syntax::{ast, match_ast, AstNode, SyntaxNode};

use crate::{
    doc_links::{extract_definitions_from_docs, resolve_doc_path_for_def, rewrite_links},
    fixture, TryToNav,
};

fn check_external_docs(
    #[rust_analyzer::rust_fixture] ra_fixture: &str,
    target_dir: Option<&str>,
    expect_web_url: Option<Expect>,
    expect_local_url: Option<Expect>,
    sysroot: Option<&str>,
) {
    let (analysis, position) = fixture::position(ra_fixture);
    let links = analysis.external_docs(position, target_dir, sysroot).unwrap();

    let web_url = links.web_url;
    let local_url = links.local_url;

    match (expect_web_url, web_url) {
        (Some(expect), Some(url)) => expect.assert_eq(&url),
        (None, None) => (),
        _ => panic!("Unexpected web url"),
    }

    match (expect_local_url, local_url) {
        (Some(expect), Some(url)) => expect.assert_eq(&url),
        (None, None) => (),
        _ => panic!("Unexpected local url"),
    }
}

fn check_rewrite(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) {
    let (analysis, position) = fixture::position(ra_fixture);
    let sema = &Semantics::new(&*analysis.db);
    let (cursor_def, docs) = def_under_cursor(sema, &position);
    let res = rewrite_links(sema.db, docs.as_str(), cursor_def);
    expect.assert_eq(&res)
}

fn check_doc_links(#[rust_analyzer::rust_fixture] ra_fixture: &str) {
    let key_fn = |&(FileRange { file_id, range }, _): &_| (file_id, range.start());

    let (analysis, position, mut expected) = fixture::annotations(ra_fixture);
    expected.sort_by_key(key_fn);
    let sema = &Semantics::new(&*analysis.db);
    let (cursor_def, docs) = def_under_cursor(sema, &position);
    let defs = extract_definitions_from_docs(&docs);
    let actual: Vec<_> = defs
        .into_iter()
        .flat_map(|(_, link, ns)| {
            let def = resolve_doc_path_for_def(sema.db, cursor_def, &link, ns)
                .unwrap_or_else(|| panic!("Failed to resolve {link}"));
            def.try_to_nav(sema.db).unwrap().into_iter().zip(iter::repeat(link))
        })
        .map(|(nav_target, link)| {
            let range =
                FileRange { file_id: nav_target.file_id, range: nav_target.focus_or_full_range() };
            (range, link)
        })
        .sorted_by_key(key_fn)
        .collect();
    assert_eq!(expected, actual);
}

fn def_under_cursor(
    sema: &Semantics<'_, RootDatabase>,
    position: &FilePosition,
) -> (Definition, Documentation) {
    let (docs, def) = sema
        .parse_guess_edition(position.file_id)
        .syntax()
        .token_at_offset(position.offset)
        .left_biased()
        .unwrap()
        .parent_ancestors()
        .find_map(|it| node_to_def(sema, &it))
        .expect("no def found")
        .unwrap();
    let docs = docs.expect("no docs found for cursor def");
    (def, docs)
}

fn node_to_def(
    sema: &Semantics<'_, RootDatabase>,
    node: &SyntaxNode,
) -> Option<Option<(Option<Documentation>, Definition)>> {
    Some(match_ast! {
        match node {
            ast::SourceFile(it)  => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Module(def))),
            ast::Module(it)      => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Module(def))),
            ast::Fn(it)          => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Function(def))),
            ast::Struct(it)      => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Adt(hir::Adt::Struct(def)))),
            ast::Union(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Adt(hir::Adt::Union(def)))),
            ast::Enum(it)        => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Adt(hir::Adt::Enum(def)))),
            ast::Variant(it)     => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Variant(def))),
            ast::Trait(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Trait(def))),
            ast::Static(it)      => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Static(def))),
            ast::Const(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Const(def))),
            ast::TypeAlias(it)   => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::TypeAlias(def))),
            ast::Impl(it)        => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::SelfType(def))),
            ast::RecordField(it) => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Field(def))),
            ast::TupleField(it)  => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Field(def))),
            ast::Macro(it)       => sema.to_def(&it).map(|def| (def.docs(sema.db), Definition::Macro(def))),
            // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
            _ => return None,
        }
    })
}

#[test]
fn external_docs_doc_builtin_type() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
let x: u3$02 = 0;
"#,
        Some("/home/user/project"),
        Some(expect![[r#"https://doc.rust-lang.org/nightly/core/primitive.u32.html"#]]),
        Some(expect![[r#"file:///sysroot/share/doc/rust/html/core/primitive.u32.html"#]]),
        Some("/sysroot"),
    );
}

#[test]
fn external_docs_doc_url_crate() {
    check_external_docs(
        r#"
//- /main.rs crate:main deps:foo
use foo$0::Foo;
//- /lib.rs crate:foo
pub struct Foo;
"#,
        Some("/home/user/project"),
        Some(expect![[r#"https://docs.rs/foo/*/foo/index.html"#]]),
        Some(expect![[r#"file:///home/user/project/doc/foo/index.html"#]]),
        Some("/sysroot"),
    );
}

#[test]
fn external_docs_doc_url_std_crate() {
    check_external_docs(
        r#"
//- /main.rs crate:std
use self$0;
"#,
        Some("/home/user/project"),
        Some(expect!["https://doc.rust-lang.org/stable/std/index.html"]),
        Some(expect!["file:///sysroot/share/doc/rust/html/std/index.html"]),
        Some("/sysroot"),
    );
}

#[test]
fn external_docs_doc_url_struct() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Fo$0o;
"#,
        Some("/home/user/project"),
        Some(expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]]),
        Some(expect![[r#"file:///home/user/project/doc/foo/struct.Foo.html"#]]),
        Some("/sysroot"),
    );
}

#[test]
fn external_docs_doc_url_windows_backslash_path() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Fo$0o;
"#,
        Some(r"C:\Users\user\project"),
        Some(expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]]),
        Some(expect![[r#"file:///C:/Users/user/project/doc/foo/struct.Foo.html"#]]),
        Some("/sysroot"),
    );
}

#[test]
fn external_docs_doc_url_windows_slash_path() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Fo$0o;
"#,
        Some("C:/Users/user/project"),
        Some(expect![[r#"https://docs.rs/foo/*/foo/struct.Foo.html"#]]),
        Some(expect![[r#"file:///C:/Users/user/project/doc/foo/struct.Foo.html"#]]),
        Some("/sysroot"),
    );
}

#[test]
fn external_docs_doc_url_struct_field() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Foo {
    field$0: ()
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#structfield.field"##]]),
        None,
        None,
    );
}

#[test]
fn external_docs_doc_url_fn() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub fn fo$0o() {}
"#,
        None,
        Some(expect![[r#"https://docs.rs/foo/*/foo/fn.foo.html"#]]),
        None,
        None,
    );
}

#[test]
fn external_docs_doc_url_impl_assoc() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Foo;
impl Foo {
    pub fn method$0() {}
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#method.method"##]]),
        None,
        None,
    );
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Foo;
impl Foo {
    const CONST$0: () = ();
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#associatedconstant.CONST"##]]),
        None,
        None,
    );
}

#[test]
fn external_docs_doc_url_impl_trait_assoc() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Foo;
pub trait Trait {
    fn method() {}
}
impl Trait for Foo {
    pub fn method$0() {}
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#method.method"##]]),
        None,
        None,
    );
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Foo;
pub trait Trait {
    const CONST: () = ();
}
impl Trait for Foo {
    const CONST$0: () = ();
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#associatedconstant.CONST"##]]),
        None,
        None,
    );
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub struct Foo;
pub trait Trait {
    type Type;
}
impl Trait for Foo {
    type Type$0 = ();
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/struct.Foo.html#associatedtype.Type"##]]),
        None,
        None,
    );
}

#[test]
fn external_docs_doc_url_trait_assoc() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub trait Foo {
    fn method$0();
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/trait.Foo.html#tymethod.method"##]]),
        None,
        None,
    );
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub trait Foo {
    const CONST$0: ();
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/trait.Foo.html#associatedconstant.CONST"##]]),
        None,
        None,
    );
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub trait Foo {
    type Type$0;
}
"#,
        None,
        Some(expect![[r##"https://docs.rs/foo/*/foo/trait.Foo.html#associatedtype.Type"##]]),
        None,
        None,
    );
}

#[test]
fn external_docs_trait() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
trait Trait$0 {}
"#,
        None,
        Some(expect![[r#"https://docs.rs/foo/*/foo/trait.Trait.html"#]]),
        None,
        None,
    )
}

#[test]
fn external_docs_module() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub mod foo {
    pub mod ba$0r {}
}
"#,
        None,
        Some(expect![[r#"https://docs.rs/foo/*/foo/foo/bar/index.html"#]]),
        None,
        None,
    )
}

#[test]
fn external_docs_reexport_order() {
    check_external_docs(
        r#"
//- /main.rs crate:foo
pub mod wrapper {
    pub use module::Item;

    pub mod module {
        pub struct Item;
    }
}

fn foo() {
    let bar: wrapper::It$0em;
}
        "#,
        None,
        Some(expect![[r#"https://docs.rs/foo/*/foo/wrapper/module/struct.Item.html"#]]),
        None,
        None,
    )
}

#[test]
fn doc_links_items_simple() {
    check_doc_links(
        r#"
//- /main.rs crate:main deps:krate
/// [`krate`]
//! [`Trait`]
//! [`function`]
//! [`CONST`]
//! [`STATIC`]
//! [`Struct`]
//! [`Enum`]
//! [`Union`]
//! [`Type`]
//! [`module`]
use self$0;

const CONST: () = ();
   // ^^^^^ CONST
static STATIC: () = ();
    // ^^^^^^ STATIC
trait Trait {
   // ^^^^^ Trait
}
fn function() {}
// ^^^^^^^^ function
struct Struct;
    // ^^^^^^ Struct
enum Enum {}
  // ^^^^ Enum
union Union {__: ()}
   // ^^^^^ Union
type Type = ();
  // ^^^^ Type
mod module {}
 // ^^^^^^ module
//- /krate.rs crate:krate
// empty
//^file krate
"#,
    )
}

#[test]
fn doc_links_inherent_impl_items() {
    check_doc_links(
        r#"
/// [`Struct::CONST`]
/// [`Struct::function`]
struct Struct$0;

impl Struct {
    const CONST: () = ();
       // ^^^^^ Struct::CONST
    fn function() {}
    // ^^^^^^^^ Struct::function
}
"#,
    )
}

#[test]
fn doc_links_trait_impl_items() {
    check_doc_links(
        r#"
trait Trait {
    type Type;
    const CONST: usize;
       // ^^^^^ Struct::CONST
    fn function();
    // ^^^^^^^^ Struct::function
}
// FIXME #9694: [`Struct::Type`]
/// [`Struct::CONST`]
/// [`Struct::function`]
struct Struct$0;

impl Trait for Struct {
    type Type = ();
    const CONST: () = ();
    fn function() {}
}
"#,
    )
}

#[test]
fn doc_links_trait_items() {
    check_doc_links(
        r#"
/// [`Trait`]
/// [`Trait::Type`]
/// [`Trait::CONST`]
/// [`Trait::function`]
trait Trait$0 {
   // ^^^^^ Trait
type Type;
  // ^^^^ Trait::Type
const CONST: usize;
   // ^^^^^ Trait::CONST
fn function();
// ^^^^^^^^ Trait::function
}
    "#,
    )
}

#[test]
fn doc_links_field() {
    check_doc_links(
        r#"
/// [`S::f`]
/// [`S2::f`]
/// [`T::0`]
/// [`U::a`]
/// [`E::A::f`]
/// [`E::B::0`]
struct S$0 {
    f: i32,
  //^ S::f
  //^ S2::f
}
type S2 = S;
struct T(i32);
       //^^^ T::0
union U {
    a: i32,
  //^ U::a
}
enum E {
    A { f: i32 },
      //^ E::A::f
    B(i32),
    //^^^ E::B::0
}
"#,
    );
}

#[test]
fn doc_links_field_via_self() {
    check_doc_links(
        r#"
/// [`Self::f`]
struct S$0 {
    f: i32,
  //^ Self::f
}
"#,
    );
}

#[test]
fn doc_links_tuple_field_via_self() {
    check_doc_links(
        r#"
/// [`Self::0`]
struct S$0(i32);
       //^^^ Self::0
"#,
    );
}

#[test]
fn rewrite_html_root_url() {
    check_rewrite(
        r#"
//- /main.rs crate:foo
#![doc(arbitrary_attribute = "test", html_root_url = "https:/example.com", arbitrary_attribute2)]

pub mod foo {
    pub struct Foo;
}
/// [Foo](foo::Foo)
pub struct B$0ar
"#,
        expect![[r#"[Foo](https://example.com/foo/foo/struct.Foo.html)"#]],
    );
}

#[test]
fn rewrite_on_field() {
    check_rewrite(
        r#"
//- /main.rs crate:foo
pub struct Foo {
    /// [Foo](struct.Foo.html)
    fie$0ld: ()
}
"#,
        expect![[r#"[Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
    );
}

#[test]
fn rewrite_struct() {
    check_rewrite(
        r#"
//- /main.rs crate:foo
/// [Foo]
pub struct $0Foo;
"#,
        expect![[r#"[Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
    );
    check_rewrite(
        r#"
//- /main.rs crate:foo
/// [`Foo`]
pub struct $0Foo;
"#,
        expect![[r#"[`Foo`](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
    );
    check_rewrite(
        r#"
//- /main.rs crate:foo
/// [Foo](struct.Foo.html)
pub struct $0Foo;
"#,
        expect![[r#"[Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
    );
    check_rewrite(
        r#"
//- /main.rs crate:foo
/// [struct Foo](struct.Foo.html)
pub struct $0Foo;
"#,
        expect![[r#"[struct Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
    );
    check_rewrite(
        r#"
//- /main.rs crate:foo
/// [my Foo][foo]
///
/// [foo]: Foo
pub struct $0Foo;
"#,
        expect![[r#"[my Foo](https://docs.rs/foo/*/foo/struct.Foo.html)"#]],
    );
    check_rewrite(
        r#"
//- /main.rs crate:foo
/// [`foo`]
///
/// [`foo`]: Foo
pub struct $0Foo;
"#,
        expect![["[`foo`]"]],
    );
}

#[test]
fn rewrite_intra_doc_link() {
    check_rewrite(
        r#"
        //- minicore: eq, derive
        //- /main.rs crate:foo
        //! $0[PartialEq]
        fn main() {}
        "#,
        expect!["[PartialEq](https://doc.rust-lang.org/stable/core/cmp/trait.PartialEq.html)"],
    );
}

#[test]
fn rewrite_intra_doc_link_with_anchor() {
    check_rewrite(
        r#"
        //- minicore: eq, derive
        //- /main.rs crate:foo
        //! $0[PartialEq#derivable]
        fn main() {}
        "#,
        expect!["[PartialEq#derivable](https://doc.rust-lang.org/stable/core/cmp/trait.PartialEq.html#derivable)"],
    );
}