1use std::{borrow::Cow, env, mem, ops::Not};
3
4use either::Either;
5use hir::{
6 Adt, AsAssocItem, AsExternAssocItem, CaptureKind, DisplayTarget, DropGlue,
7 DynCompatibilityViolation, HasCrate, HasSource, HirDisplay, Layout, LayoutError,
8 MethodViolation, Name, Semantics, Symbol, Trait, Type, TypeInfo, Variant,
9};
10use ide_db::{
11 RootDatabase,
12 defs::{Definition, find_std_module},
13 documentation::{Documentation, HasDocs},
14 famous_defs::FamousDefs,
15 generated::lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
16 syntax_helpers::prettify_macro_expansion,
17};
18use itertools::Itertools;
19use rustc_apfloat::{
20 Float,
21 ieee::{Half as f16, Quad as f128},
22};
23use span::{Edition, TextSize};
24use stdx::format_to;
25use syntax::{AstNode, AstToken, Direction, SyntaxToken, T, algo, ast, match_ast};
26
27use crate::{
28 HoverAction, HoverConfig, HoverResult, Markup, MemoryLayoutHoverConfig,
29 MemoryLayoutHoverRenderKind,
30 doc_links::{remove_links, rewrite_links},
31 hover::{SubstTyLen, notable_traits, walk_and_push_ty},
32 interpret::render_const_eval_error,
33};
34
35pub(super) fn type_info_of(
36 sema: &Semantics<'_, RootDatabase>,
37 _config: &HoverConfig<'_>,
38 expr_or_pat: &Either<ast::Expr, ast::Pat>,
39 edition: Edition,
40 display_target: DisplayTarget,
41) -> Option<HoverResult> {
42 let ty_info = match expr_or_pat {
43 Either::Left(expr) => sema.type_of_expr(expr)?,
44 Either::Right(pat) => sema.type_of_pat(pat)?,
45 };
46 type_info(sema, _config, ty_info, edition, display_target)
47}
48
49pub(super) fn closure_expr(
50 sema: &Semantics<'_, RootDatabase>,
51 config: &HoverConfig<'_>,
52 c: ast::ClosureExpr,
53 edition: Edition,
54 display_target: DisplayTarget,
55) -> Option<HoverResult> {
56 let TypeInfo { original, .. } = sema.type_of_expr(&c.into())?;
57 closure_ty(sema, config, &TypeInfo { original, adjusted: None }, edition, display_target)
58}
59
60pub(super) fn try_expr(
61 sema: &Semantics<'_, RootDatabase>,
62 _config: &HoverConfig<'_>,
63 try_expr: &ast::TryExpr,
64 edition: Edition,
65 display_target: DisplayTarget,
66) -> Option<HoverResult> {
67 let inner_ty = sema.type_of_expr(&try_expr.expr()?)?.original;
68 let mut ancestors = try_expr.syntax().ancestors();
69 let mut body_ty = loop {
70 let next = ancestors.next()?;
71 break match_ast! {
72 match next {
73 ast::Fn(fn_) => sema.to_def(&fn_)?.ret_type(sema.db),
74 ast::Item(__) => return None,
75 ast::ClosureExpr(closure) => sema.type_of_expr(&closure.body()?)?.original,
76 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try { .. } | ast::BlockModifier::Const(_))) {
77 sema.type_of_expr(&block_expr.into())?.original
78 } else {
79 continue;
80 },
81 _ => continue,
82 }
83 };
84 };
85
86 if inner_ty == body_ty {
87 return None;
88 }
89
90 let mut inner_ty = inner_ty;
91 let mut s = "Try Target".to_owned();
92
93 let adts = inner_ty.as_adt().zip(body_ty.as_adt());
94 if let Some((hir::Adt::Enum(inner), hir::Adt::Enum(body))) = adts {
95 let famous_defs = FamousDefs(sema, sema.scope(try_expr.syntax())?.krate());
96 if let Some(option_enum) = famous_defs.core_option_Option()
98 && inner == option_enum
99 && body == option_enum
100 {
101 cov_mark::hit!(hover_try_expr_opt_opt);
102 return None;
103 }
104
105 if let Some(result_enum) = famous_defs.core_result_Result()
107 && inner == result_enum
108 && body == result_enum
109 {
110 let error_type_args =
111 inner_ty.type_arguments().nth(1).zip(body_ty.type_arguments().nth(1));
112 if let Some((inner, body)) = error_type_args {
113 inner_ty = inner;
114 body_ty = body;
115 "Try Error".clone_into(&mut s);
116 }
117 }
118 }
119
120 let mut res = HoverResult::default();
121
122 let mut targets: Vec<hir::ModuleDef> = Vec::new();
123 let mut push_new_def = |item: hir::ModuleDef| {
124 if !targets.contains(&item) {
125 targets.push(item);
126 }
127 };
128 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
129 walk_and_push_ty(sema.db, &body_ty, &mut push_new_def);
130 if let Some(actions) = HoverAction::goto_type_from_targets(sema, targets, edition) {
131 res.actions.push(actions);
132 }
133
134 let inner_ty = inner_ty.display(sema.db, display_target).to_string();
135 let body_ty = body_ty.display(sema.db, display_target).to_string();
136 let ty_len_max = inner_ty.len().max(body_ty.len());
137
138 let l = "Propagated as: ".len() - " Type: ".len();
139 let static_text_len_diff = l as isize - s.len() as isize;
140 let tpad = static_text_len_diff.max(0) as usize;
141 let ppad = static_text_len_diff.min(0).unsigned_abs();
142
143 res.markup = format!(
144 "```text\n{} Type: {:>pad0$}\nPropagated as: {:>pad1$}\n```\n",
145 s,
146 inner_ty,
147 body_ty,
148 pad0 = ty_len_max + tpad,
149 pad1 = ty_len_max + ppad,
150 )
151 .into();
152 Some(res)
153}
154
155pub(super) fn deref_expr(
156 sema: &Semantics<'_, RootDatabase>,
157 _config: &HoverConfig<'_>,
158 deref_expr: &ast::PrefixExpr,
159 edition: Edition,
160 display_target: DisplayTarget,
161) -> Option<HoverResult> {
162 let inner_ty = sema.type_of_expr(&deref_expr.expr()?)?.original;
163 let TypeInfo { original, adjusted } =
164 sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?;
165
166 let mut res = HoverResult::default();
167 let mut targets: Vec<hir::ModuleDef> = Vec::new();
168 let mut push_new_def = |item: hir::ModuleDef| {
169 if !targets.contains(&item) {
170 targets.push(item);
171 }
172 };
173 walk_and_push_ty(sema.db, &inner_ty, &mut push_new_def);
174 walk_and_push_ty(sema.db, &original, &mut push_new_def);
175
176 res.markup = if let Some(adjusted_ty) = adjusted {
177 walk_and_push_ty(sema.db, &adjusted_ty, &mut push_new_def);
178 let original = original.display(sema.db, display_target).to_string();
179 let adjusted = adjusted_ty.display(sema.db, display_target).to_string();
180 let inner = inner_ty.display(sema.db, display_target).to_string();
181 let type_len = "To type: ".len();
182 let coerced_len = "Coerced to: ".len();
183 let deref_len = "Dereferenced from: ".len();
184 let max_len = (original.len() + type_len)
185 .max(adjusted.len() + coerced_len)
186 .max(inner.len() + deref_len);
187 format!(
188 "```text\nDereferenced from: {:>ipad$}\nTo type: {:>apad$}\nCoerced to: {:>opad$}\n```\n",
189 inner,
190 original,
191 adjusted,
192 ipad = max_len - deref_len,
193 apad = max_len - type_len,
194 opad = max_len - coerced_len,
195 )
196 .into()
197 } else {
198 let original = original.display(sema.db, display_target).to_string();
199 let inner = inner_ty.display(sema.db, display_target).to_string();
200 let type_len = "To type: ".len();
201 let deref_len = "Dereferenced from: ".len();
202 let max_len = (original.len() + type_len).max(inner.len() + deref_len);
203 format!(
204 "```text\nDereferenced from: {:>ipad$}\nTo type: {:>apad$}\n```\n",
205 inner,
206 original,
207 ipad = max_len - deref_len,
208 apad = max_len - type_len,
209 )
210 .into()
211 };
212 if let Some(actions) = HoverAction::goto_type_from_targets(sema, targets, edition) {
213 res.actions.push(actions);
214 }
215
216 Some(res)
217}
218
219pub(super) fn underscore(
220 sema: &Semantics<'_, RootDatabase>,
221 config: &HoverConfig<'_>,
222 token: &SyntaxToken,
223 edition: Edition,
224 display_target: DisplayTarget,
225) -> Option<HoverResult> {
226 if token.kind() != T![_] {
227 return None;
228 }
229 let parent = token.parent()?;
230 match_ast! {
231 match parent {
232 ast::InferType(it) => type_info(sema, config, TypeInfo { original: sema.resolve_type(&ast::Type::InferType(it))?, adjusted: None}, edition, display_target),
233 ast::UnderscoreExpr(it) => type_info(sema, config, sema.type_of_expr(&ast::Expr::UnderscoreExpr(it))?, edition, display_target),
234 ast::WildcardPat(it) => type_info(sema, config, sema.type_of_pat(&ast::Pat::WildcardPat(it))?, edition, display_target),
235 _ => None,
236 }
237 }
238}
239
240pub(super) fn keyword(
241 sema: &Semantics<'_, RootDatabase>,
242 config: &HoverConfig<'_>,
243 token: &SyntaxToken,
244 edition: Edition,
245 display_target: DisplayTarget,
246) -> Option<HoverResult> {
247 if !token.kind().is_keyword(edition) || !config.documentation || !config.keywords {
248 return None;
249 }
250 let parent = token.parent()?;
251 let famous_defs = FamousDefs(sema, sema.scope(&parent)?.krate());
252
253 let KeywordHint { description, keyword_mod, actions } =
254 keyword_hints(sema, token, parent, edition, display_target);
255
256 let doc_owner = find_std_module(&famous_defs, &keyword_mod, edition)?;
257 let docs = doc_owner.docs_with_rangemap(sema.db)?;
258 let (markup, range_map) =
259 markup(Some(Either::Left(docs)), description, None, None, String::new());
260 let markup = process_markup(sema.db, Definition::Module(doc_owner), &markup, range_map, config);
261 Some(HoverResult { markup, actions })
262}
263
264pub(super) fn struct_rest_pat(
268 sema: &Semantics<'_, RootDatabase>,
269 _config: &HoverConfig<'_>,
270 pattern: &ast::RecordPat,
271 edition: Edition,
272 display_target: DisplayTarget,
273) -> HoverResult {
274 let matched_fields = sema.record_pattern_matched_fields(pattern);
275
276 let mut res = HoverResult::default();
281 let mut targets: Vec<hir::ModuleDef> = Vec::new();
282 let mut push_new_def = |item: hir::ModuleDef| {
283 if !targets.contains(&item) {
284 targets.push(item);
285 }
286 };
287 for (_, t) in &matched_fields {
288 walk_and_push_ty(sema.db, t, &mut push_new_def);
289 }
290
291 res.markup = {
292 let mut s = String::from(".., ");
293 for (f, _) in &matched_fields {
294 s += f.display(sema.db, display_target).to_string().as_ref();
295 s += ", ";
296 }
297 s.truncate(s.len() - 2);
299
300 Markup::fenced_block(&s)
301 };
302 if let Some(actions) = HoverAction::goto_type_from_targets(sema, targets, edition) {
303 res.actions.push(actions);
304 }
305 res
306}
307
308pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<HoverResult> {
309 let (path, tt) = attr.as_simple_call()?;
310 if !tt.syntax().text_range().contains(token.text_range().start()) {
311 return None;
312 }
313 let (is_clippy, lints) = match &*path {
314 "feature" => (false, FEATURES),
315 "allow" | "deny" | "expect" | "forbid" | "warn" => {
316 let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
317 .filter(|t| t.kind() == T![:])
318 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
319 .filter(|t| t.kind() == T![:])
320 .and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
321 .is_some_and(|t| {
322 t.kind() == T![ident] && t.into_token().is_some_and(|t| t.text() == "clippy")
323 });
324 if is_clippy { (true, CLIPPY_LINTS) } else { (false, DEFAULT_LINTS) }
325 }
326 _ => return None,
327 };
328
329 let needle = if is_clippy { &format!("clippy::{}", token.text()) } else { token.text() };
330
331 let lint =
332 lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
333 Some(HoverResult {
334 markup: Markup::from(format!("```\n{}\n```\n---\n\n{}", lint.label, lint.description)),
335 ..Default::default()
336 })
337}
338
339pub(super) fn process_markup(
340 db: &RootDatabase,
341 def: Definition<'_>,
342 markup: &Markup,
343 markup_range_map: Option<hir::Docs>,
344 config: &HoverConfig<'_>,
345) -> Markup {
346 let markup = markup.as_str();
347 let markup = if config.links_in_hover {
348 rewrite_links(db, markup, def, markup_range_map.as_ref())
349 } else {
350 remove_links(markup)
351 };
352 Markup::from(markup)
353}
354
355fn definition_owner_name(
356 db: &RootDatabase,
357 def: Definition<'_>,
358 edition: Edition,
359) -> Option<String> {
360 match def {
361 Definition::Field(f) => {
362 let parent = f.parent_def(db);
363 let parent_name = parent.name(db);
364 let parent_name = parent_name.display(db, edition).to_string();
365 return match parent {
366 Variant::EnumVariant(variant) => {
367 let enum_name = variant.parent_enum(db).name(db);
368 Some(format!("{}::{parent_name}", enum_name.display(db, edition)))
369 }
370 _ => Some(parent_name),
371 };
372 }
373 Definition::EnumVariant(e) => Some(e.parent_enum(db).name(db)),
374 Definition::GenericParam(generic_param) => match generic_param.parent() {
375 hir::GenericDef::Adt(it) => Some(it.name(db)),
376 hir::GenericDef::Trait(it) => Some(it.name(db)),
377 hir::GenericDef::TypeAlias(it) => Some(it.name(db)),
378
379 hir::GenericDef::Impl(i) => i.self_ty(db).as_adt().map(|adt| adt.name(db)),
380 hir::GenericDef::Function(it) => {
381 let container = it.as_assoc_item(db).and_then(|assoc| match assoc.container(db) {
382 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
383 hir::AssocItemContainer::Impl(i) => {
384 i.self_ty(db).as_adt().map(|adt| adt.name(db))
385 }
386 });
387 match container {
388 Some(name) => {
389 return Some(format!(
390 "{}::{}",
391 name.display(db, edition),
392 it.name(db).display(db, edition)
393 ));
394 }
395 None => Some(it.name(db)),
396 }
397 }
398 hir::GenericDef::Const(it) => {
399 let container = it.as_assoc_item(db).and_then(|assoc| match assoc.container(db) {
400 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
401 hir::AssocItemContainer::Impl(i) => {
402 i.self_ty(db).as_adt().map(|adt| adt.name(db))
403 }
404 });
405 match container {
406 Some(name) => {
407 return Some(format!(
408 "{}::{}",
409 name.display(db, edition),
410 it.name(db)?.display(db, edition)
411 ));
412 }
413 None => it.name(db),
414 }
415 }
416 hir::GenericDef::Static(it) => Some(it.name(db)),
417 },
418 Definition::DeriveHelper(derive_helper) => Some(derive_helper.derive().name(db)),
419 d => {
420 if let Some(assoc_item) = d.as_assoc_item(db) {
421 match assoc_item.container(db) {
422 hir::AssocItemContainer::Trait(t) => Some(t.name(db)),
423 hir::AssocItemContainer::Impl(i) => {
424 i.self_ty(db).as_adt().map(|adt| adt.name(db))
425 }
426 }
427 } else {
428 return d.as_extern_assoc_item(db).map(|_| "<extern>".to_owned());
429 }
430 }
431 }
432 .map(|name| name.display(db, edition).to_string())
433}
434
435pub(super) fn path(
436 db: &RootDatabase,
437 module: hir::Module,
438 item_name: Option<String>,
439 edition: Edition,
440) -> String {
441 let crate_name = module.krate(db).display_name(db).as_ref().map(|it| it.to_string());
442 let module_path = module.path_segments(db).map(|it| it.display(db, edition).to_string());
443 crate_name.into_iter().chain(module_path).chain(item_name).join("::")
444}
445
446pub(super) fn definition(
447 db: &RootDatabase,
448 def: Definition<'_>,
449 famous_defs: Option<&FamousDefs<'_, '_>>,
450 notable_traits: &[(Trait, Vec<(Option<Type<'_>>, Name)>)],
451 macro_arm: Option<u32>,
452 render_extras: bool,
453 render_private_fields: bool,
454 subst_types: Option<&Vec<(Symbol, Type<'_>)>>,
455 config: &HoverConfig<'_>,
456 edition: Edition,
457 display_target: DisplayTarget,
458) -> (Markup, Option<hir::Docs>) {
459 let mod_path = definition_path(db, &def, edition);
460 let label = match def {
461 Definition::Trait(trait_) => trait_
462 .display_limited(db, config.max_trait_assoc_items_count, display_target)
463 .with_private_fields(render_private_fields)
464 .to_string(),
465 Definition::Adt(adt @ (Adt::Struct(_) | Adt::Union(_))) => adt
466 .display_limited(db, config.max_fields_count, display_target)
467 .with_private_fields(render_private_fields)
468 .to_string(),
469 Definition::EnumVariant(variant) => variant
470 .display_limited(db, config.max_fields_count, display_target)
471 .with_private_fields(render_private_fields)
472 .to_string(),
473 Definition::Adt(adt @ Adt::Enum(_)) => adt
474 .display_limited(db, config.max_enum_variants_count, display_target)
475 .with_private_fields(render_private_fields)
476 .to_string(),
477 Definition::SelfType(impl_def) => {
478 let self_ty = &impl_def.self_ty(db);
479 match self_ty.as_adt() {
480 Some(adt) => adt
481 .display_limited(db, config.max_fields_count, display_target)
482 .with_private_fields(render_private_fields)
483 .to_string(),
484 None => self_ty.display(db, display_target).to_string(),
485 }
486 }
487 Definition::Macro(it) => {
488 let mut label = it.display(db, display_target).to_string();
489 if let Some(macro_arm) = macro_arm {
490 format_to!(label, " // matched arm #{}", macro_arm);
491 }
492 label
493 }
494 Definition::Function(fn_) => {
495 fn_.display_with_container_bounds(db, true, display_target).to_string()
496 }
497 _ => def.label(db, display_target),
498 };
499 let docs = if config.documentation {
500 def.docs_with_rangemap(db, famous_defs, display_target)
501 } else {
502 None
503 };
504 let value = || match def {
505 Definition::EnumVariant(it) => {
506 if !it.parent_enum(db).is_data_carrying(db) {
507 match it.eval(db) {
508 Ok(it) => {
509 Some(if it >= 10 { format!("{it} ({it:#X})") } else { format!("{it}") })
510 }
511 Err(err) => {
512 let res = it.value(db).map(|it| it.to_string());
513 if env::var_os("RA_DEV").is_some() {
514 let res = res.as_deref().unwrap_or("");
515 Some(format!(
516 "{res} ({})",
517 render_const_eval_error(db, err, display_target)
518 ))
519 } else {
520 res
521 }
522 }
523 }
524 } else {
525 None
526 }
527 }
528 Definition::Const(it) => {
529 let body = it.eval(db);
530 Some(match body {
531 Ok(it) => match it.render_debug(db) {
532 Ok(rendered) if rendered.is_empty() => it.render(db, display_target),
533 Ok(rendered) => rendered,
534 Err(err) => {
535 let it = it.render(db, display_target);
536 if env::var_os("RA_DEV").is_some() {
537 format!(
538 "{it}\n{}",
539 render_const_eval_error(db, err.into(), display_target)
540 )
541 } else {
542 it
543 }
544 }
545 },
546 Err(err) => {
547 let source = it.source(db)?;
548 let mut body = source.value.body()?.syntax().clone();
549 if let Some(macro_file) = source.file_id.macro_file() {
550 let span_map = macro_file.expansion_span_map(db);
551 body = prettify_macro_expansion(db, body, span_map, it.krate(db).into());
552 }
553 if env::var_os("RA_DEV").is_some() {
554 format!("{body}\n{}", render_const_eval_error(db, err, display_target))
555 } else {
556 body.to_string()
557 }
558 }
559 })
560 }
561 Definition::Static(it) => {
562 let body = it.eval(db);
563 Some(match body {
564 Ok(it) => match it.render_debug(db) {
565 Ok(rendered) if rendered.is_empty() => it.render(db, display_target),
566 Ok(rendered) => rendered,
567
568 Err(err) => {
569 let it = it.render(db, display_target);
570 if env::var_os("RA_DEV").is_some() {
571 format!(
572 "{it}\n{}",
573 render_const_eval_error(db, err.into(), display_target)
574 )
575 } else {
576 it
577 }
578 }
579 },
580 Err(err) => {
581 let source = it.source(db)?;
582 let mut body = source.value.body()?.syntax().clone();
583 if let Some(macro_file) = source.file_id.macro_file() {
584 let span_map = macro_file.expansion_span_map(db);
585 body = prettify_macro_expansion(db, body, span_map, it.krate(db).into());
586 }
587 if env::var_os("RA_DEV").is_some() {
588 format!("{body}\n{}", render_const_eval_error(db, err, display_target))
589 } else {
590 body.to_string()
591 }
592 }
593 })
594 }
595 _ => None,
596 };
597
598 let layout_info = || match def {
599 Definition::Field(it) => render_memory_layout(
600 config.memory_layout,
601 || it.layout(db),
602 |_| {
603 let var_def = it.parent_def(db);
604 match var_def {
605 hir::Variant::Struct(s) => {
606 Adt::from(s).layout(db).ok().and_then(|layout| layout.field_offset(it))
607 }
608 _ => None,
609 }
610 },
611 |_| None,
612 |_| None,
613 ),
614 Definition::Adt(it @ Adt::Struct(strukt)) => render_memory_layout(
615 config.memory_layout,
616 || it.layout(db),
617 |_| None,
618 |layout| {
619 let mut field_size =
620 |i: usize| Some(strukt.fields(db).get(i)?.layout(db).ok()?.size());
621 if strukt.repr(db).is_some_and(|it| it.inhibit_struct_field_reordering()) {
622 Some(("tail padding", layout.tail_padding(&mut field_size)?))
623 } else {
624 Some(("largest padding", layout.largest_padding(&mut field_size)?))
625 }
626 },
627 |_| None,
628 ),
629 Definition::Adt(it) => render_memory_layout(
630 config.memory_layout,
631 || it.layout(db),
632 |_| None,
633 |_| None,
634 |_| None,
635 ),
636 Definition::EnumVariant(it) => render_memory_layout(
637 config.memory_layout,
638 || it.layout(db),
639 |_| None,
640 |_| None,
641 |layout| layout.enum_tag_size(),
642 ),
643 Definition::TypeAlias(it) => render_memory_layout(
644 config.memory_layout,
645 || it.ty(db).layout(db),
646 |_| None,
647 |_| None,
648 |_| None,
649 ),
650 Definition::Local(it) => render_memory_layout(
651 config.memory_layout,
652 || it.ty(db).layout(db),
653 |_| None,
654 |_| None,
655 |_| None,
656 ),
657 Definition::SelfType(it) => render_memory_layout(
658 config.memory_layout,
659 || it.self_ty(db).layout(db),
660 |_| None,
661 |_| None,
662 |_| None,
663 ),
664 _ => None,
665 };
666
667 let drop_info = || {
668 if !config.show_drop_glue {
669 return None;
670 }
671 let drop_info = match def {
672 Definition::Field(field) => {
673 DropInfo { drop_glue: field.ty(db).drop_glue(db), has_dtor: None }
674 }
675 Definition::Adt(Adt::Struct(strukt)) => {
676 let struct_drop_glue = strukt.ty(db).drop_glue(db);
677 let mut fields_drop_glue = strukt
678 .fields(db)
679 .iter()
680 .map(|field| field.ty(db).drop_glue(db))
681 .max()
682 .unwrap_or(DropGlue::None);
683 let has_dtor = match (fields_drop_glue, struct_drop_glue) {
684 (DropGlue::None, _) => struct_drop_glue != DropGlue::None,
685 (_, DropGlue::None) => {
686 fields_drop_glue = DropGlue::None;
688 false
689 }
690 (_, _) => struct_drop_glue > fields_drop_glue,
691 };
692 DropInfo { drop_glue: fields_drop_glue, has_dtor: Some(has_dtor) }
693 }
694 Definition::Adt(Adt::Union(union)) => DropInfo {
696 drop_glue: DropGlue::None,
697 has_dtor: Some(union.ty(db).drop_glue(db) != DropGlue::None),
698 },
699 Definition::Adt(Adt::Enum(enum_)) => {
700 let enum_drop_glue = enum_.ty(db).drop_glue(db);
701 let fields_drop_glue = enum_
702 .variants(db)
703 .iter()
704 .map(|variant| {
705 variant
706 .fields(db)
707 .iter()
708 .map(|field| field.ty(db).drop_glue(db))
709 .max()
710 .unwrap_or(DropGlue::None)
711 })
712 .max()
713 .unwrap_or(DropGlue::None);
714 DropInfo {
715 drop_glue: fields_drop_glue,
716 has_dtor: Some(enum_drop_glue > fields_drop_glue),
717 }
718 }
719 Definition::EnumVariant(variant) => {
720 let fields_drop_glue = variant
721 .fields(db)
722 .iter()
723 .map(|field| field.ty(db).drop_glue(db))
724 .max()
725 .unwrap_or(DropGlue::None);
726 DropInfo { drop_glue: fields_drop_glue, has_dtor: None }
727 }
728 Definition::TypeAlias(type_alias) => {
729 DropInfo { drop_glue: type_alias.ty(db).drop_glue(db), has_dtor: None }
730 }
731 Definition::Local(local) => {
732 DropInfo { drop_glue: local.ty(db).drop_glue(db), has_dtor: None }
733 }
734 _ => return None,
735 };
736 let rendered_drop_glue = if drop_info.has_dtor == Some(true) {
737 "impl Drop"
738 } else {
739 match drop_info.drop_glue {
740 DropGlue::HasDropGlue => "needs Drop",
741 DropGlue::None => "no Drop",
742 DropGlue::DependOnParams => "type param may need Drop",
743 }
744 };
745
746 Some(rendered_drop_glue.to_owned())
747 };
748
749 let dyn_compatibility_info = || match def {
750 Definition::Trait(it) => {
751 let mut dyn_compatibility_info = String::new();
752 render_dyn_compatibility(
754 db,
755 &mut dyn_compatibility_info,
756 it.dyn_compatibility_violations(db).into_iter().next(),
757 );
758 Some(dyn_compatibility_info)
759 }
760 _ => None,
761 };
762
763 let variance_info = || match def {
764 Definition::GenericParam(it) => it.variance(db).as_ref().map(ToString::to_string),
765 _ => None,
766 };
767
768 let mut extra = String::new();
769 if render_extras {
770 if let Some(notable_traits) =
771 render_notable_trait(db, notable_traits, edition, display_target)
772 {
773 extra.push_str("\n___\n");
774 extra.push_str(¬able_traits);
775 }
776 if let Some(variance_info) = variance_info() {
777 extra.push_str("\n___\n");
778 extra.push_str(&variance_info);
779 }
780 if let Some(layout_info) = layout_info() {
781 extra.push_str("\n___\n");
782 extra.push_str(&layout_info);
783 if let Some(drop_info) = drop_info() {
784 extra.push_str(", ");
785 extra.push_str(&drop_info)
786 }
787 } else if let Some(drop_info) = drop_info() {
788 extra.push_str("\n___\n");
789 extra.push_str(&drop_info);
790 }
791 if let Some(dyn_compatibility_info) = dyn_compatibility_info() {
792 extra.push_str("\n___\n");
793 extra.push_str(&dyn_compatibility_info);
794 }
795 }
796 let mut desc = String::new();
797 desc.push_str(&label);
798 if let Some(value) = value() {
799 desc.push_str(" = ");
800 desc.push_str(&value);
801 }
802
803 let subst_types = match config.max_subst_ty_len {
804 SubstTyLen::Hide => String::new(),
805 SubstTyLen::LimitTo(_) | SubstTyLen::Unlimited => {
806 let limit = if let SubstTyLen::LimitTo(limit) = config.max_subst_ty_len {
807 Some(limit)
808 } else {
809 None
810 };
811 subst_types
812 .map(|subst_type| {
813 subst_type
814 .iter()
815 .filter(|(_, ty)| !ty.is_unknown())
816 .format_with(", ", |(name, ty), fmt| {
817 fmt(&format_args!(
818 "`{name}` = `{}`",
819 ty.display_truncated(db, limit, display_target)
820 ))
821 })
822 .to_string()
823 })
824 .unwrap_or_default()
825 }
826 };
827
828 markup(docs, desc, extra.is_empty().not().then_some(extra), mod_path, subst_types)
829}
830
831#[derive(Debug)]
832struct DropInfo {
833 drop_glue: DropGlue,
834 has_dtor: Option<bool>,
835}
836
837pub(super) fn cfg_predicate(
838 sema: &Semantics<'_, RootDatabase>,
839 predicate: ast::CfgPredicate,
840) -> Option<Markup> {
841 let krate = sema.scope(predicate.syntax())?.krate();
842 let cfg = cfg::CfgExpr::parse_from_ast(predicate.clone());
843 let evaluated = krate.cfg(sema.db).check(&cfg);
844
845 let output = match evaluated {
846 Some(true) => "true",
847 Some(false) => "false",
848 None => "unknown",
849 };
850 let s = format!("cfg predicate evaluated: `{output}` (`{predicate}`)");
851 Some(s.into())
852}
853
854pub(super) fn literal(
855 sema: &Semantics<'_, RootDatabase>,
856 token: SyntaxToken,
857 display_target: DisplayTarget,
858) -> Option<Markup> {
859 let lit = token.parent().and_then(ast::Literal::cast)?;
860 let ty = if let Some(p) = lit.syntax().parent().and_then(ast::Pat::cast) {
861 sema.type_of_pat(&p)?
862 } else {
863 sema.type_of_expr(&ast::Expr::Literal(lit))?
864 }
865 .original;
866
867 let parse_float = |text: &str| {
868 if ty.as_builtin().map(|it| it.is_f16()).unwrap_or(false) {
869 match text.parse::<f16>() {
870 Ok(num) => Ok(format!("{num} (bits: 0x{:X})", num.to_bits())),
871 Err(e) => Err(e.0.to_owned()),
872 }
873 } else if ty.as_builtin().map(|it| it.is_f32()).unwrap_or(false) {
874 match text.parse::<f32>() {
875 Ok(num) => Ok(format!("{num} (bits: 0x{:X})", num.to_bits())),
876 Err(e) => Err(e.to_string()),
877 }
878 } else if ty.as_builtin().map(|it| it.is_f128()).unwrap_or(false) {
879 match text.parse::<f128>() {
880 Ok(num) => Ok(format!("{num} (bits: 0x{:X})", num.to_bits())),
881 Err(e) => Err(e.0.to_owned()),
882 }
883 } else {
884 match text.parse::<f64>() {
885 Ok(num) => Ok(format!("{num} (bits: 0x{:X})", num.to_bits())),
886 Err(e) => Err(e.to_string()),
887 }
888 }
889 };
890 let value = match_ast! {
891 match token {
892 ast::String(string) => string.value().as_ref().map_err(|e| format!("{e:?}")).map(ToString::to_string),
893 ast::ByteString(string) => string.value().as_ref().map_err(|e| format!("{e:?}")).map(|it| format!("{it:?}")),
894 ast::CString(string) => string.value().as_ref().map_err(|e| format!("{e:?}")).map(|it| std::str::from_utf8(it).map_or_else(|e| format!("{e:?}"), ToOwned::to_owned)),
895 ast::Char(char) => char .value().as_ref().map_err(|e| format!("{e:?}")).map(ToString::to_string),
896 ast::Byte(byte) => byte .value().as_ref().map_err(|e| format!("{e:?}")).map(|it| format!("0x{it:X}")),
897 ast::FloatNumber(num) => parse_float(&num.value_string()),
898 ast::IntNumber(num) if matches!(num.suffix(), Some("f16" | "f32" | "f64" | "f128")) => {
899 parse_float(&num.value_string())
900 },
901 ast::IntNumber(num) => match num.value() {
902 Ok(num) => Ok(format!("{num} (0x{num:X}|0b{num:b})")),
903 Err(e) => Err(e.to_string()),
904 },
905 _ => return None
906 }
907 };
908 let ty = ty.display(sema.db, display_target);
909
910 let mut s = format!("```rust\n{ty}\n```\n---\n\n");
911 match value {
912 Ok(value) => {
913 let backtick_len = value.chars().filter(|c| *c == '`').count();
914 let spaces_len = value.chars().filter(|c| *c == ' ').count();
915 let backticks = "`".repeat(backtick_len + 1);
916 let space_char = if spaces_len == value.len() { "" } else { " " };
917
918 if let Some(newline) = value.find('\n') {
919 format_to!(
920 s,
921 "value of literal (truncated up to newline): {backticks}{space_char}{}{space_char}{backticks}",
922 &value[..newline]
923 )
924 } else {
925 format_to!(
926 s,
927 "value of literal: {backticks}{space_char}{value}{space_char}{backticks}"
928 )
929 }
930 }
931 Err(error) => format_to!(s, "invalid literal: {error}"),
932 }
933 Some(s.into())
934}
935
936fn render_notable_trait(
937 db: &RootDatabase,
938 notable_traits: &[(Trait, Vec<(Option<Type<'_>>, Name)>)],
939 edition: Edition,
940 display_target: DisplayTarget,
941) -> Option<String> {
942 let mut desc = String::new();
943 let mut needs_impl_header = true;
944 for (trait_, assoc_types) in notable_traits {
945 desc.push_str(if mem::take(&mut needs_impl_header) {
946 "Implements notable traits: `"
947 } else {
948 "`, `"
949 });
950 format_to!(desc, "{}", trait_.name(db).display(db, edition));
951 if !assoc_types.is_empty() {
952 desc.push('<');
953 format_to!(
954 desc,
955 "{}",
956 assoc_types.iter().format_with(", ", |(ty, name), f| {
957 f(&name.display(db, edition))?;
958 f(&" = ")?;
959 match ty {
960 Some(ty) => f(&ty.display(db, display_target)),
961 None => f(&"?"),
962 }
963 })
964 );
965 desc.push('>');
966 }
967 }
968 if desc.is_empty() {
969 None
970 } else {
971 desc.push('`');
972 Some(desc)
973 }
974}
975
976fn type_info(
977 sema: &Semantics<'_, RootDatabase>,
978 config: &HoverConfig<'_>,
979 ty: TypeInfo<'_>,
980 edition: Edition,
981 display_target: DisplayTarget,
982) -> Option<HoverResult> {
983 if let Some(res) = closure_ty(sema, config, &ty, edition, display_target) {
984 return Some(res);
985 };
986 let db = sema.db;
987 let TypeInfo { original, adjusted } = ty;
988 let mut res = HoverResult::default();
989 let mut targets: Vec<hir::ModuleDef> = Vec::new();
990 let mut push_new_def = |item: hir::ModuleDef| {
991 if !targets.contains(&item) {
992 targets.push(item);
993 }
994 };
995 walk_and_push_ty(db, &original, &mut push_new_def);
996
997 res.markup = if let Some(adjusted_ty) = adjusted {
998 walk_and_push_ty(db, &adjusted_ty, &mut push_new_def);
999
1000 let notable = if let Some(notable) =
1001 render_notable_trait(db, ¬able_traits(db, &original), edition, display_target)
1002 {
1003 format!("{notable}\n")
1004 } else {
1005 String::new()
1006 };
1007
1008 let original = original.display(db, display_target).to_string();
1009 let adjusted = adjusted_ty.display(db, display_target).to_string();
1010 let static_text_diff_len = "Coerced to: ".len() - "Type: ".len();
1011 format!(
1012 "```text\nType: {:>apad$}\nCoerced to: {:>opad$}\n{notable}```\n",
1013 original,
1014 adjusted,
1015 apad = static_text_diff_len + adjusted.len().max(original.len()),
1016 opad = original.len(),
1017 )
1018 .into()
1019 } else {
1020 let mut desc = format!("```rust\n{}\n```", original.display(db, display_target));
1021 if let Some(extra) =
1022 render_notable_trait(db, ¬able_traits(db, &original), edition, display_target)
1023 {
1024 desc.push_str("\n---\n");
1025 desc.push_str(&extra);
1026 };
1027 desc.into()
1028 };
1029 if let Some(actions) = HoverAction::goto_type_from_targets(sema, targets, edition) {
1030 res.actions.push(actions);
1031 }
1032 Some(res)
1033}
1034
1035fn closure_ty(
1036 sema: &Semantics<'_, RootDatabase>,
1037 config: &HoverConfig<'_>,
1038 TypeInfo { original, adjusted }: &TypeInfo<'_>,
1039 edition: Edition,
1040 display_target: DisplayTarget,
1041) -> Option<HoverResult> {
1042 let c = original.as_closure()?;
1043 let captures = c.captured_items(sema.db);
1044 let mut captures_rendered = captures
1045 .iter()
1046 .map(|it| {
1047 let borrow_kind = match it.kind() {
1048 CaptureKind::SharedRef => "immutable borrow",
1049 CaptureKind::UniqueSharedRef => "unique immutable borrow ([read more](https://doc.rust-lang.org/stable/reference/types/closure.html#unique-immutable-borrows-in-captures))",
1050 CaptureKind::MutableRef => "mutable borrow",
1051 CaptureKind::Move => "move",
1052 };
1053 format!("* `{}` by {}", it.display_place_source_code(sema.db, display_target.edition), borrow_kind)
1054 })
1055 .join("\n");
1056 if captures_rendered.trim().is_empty() {
1057 "This closure captures nothing".clone_into(&mut captures_rendered);
1058 }
1059 let mut targets: Vec<hir::ModuleDef> = Vec::new();
1060 let mut push_new_def = |item: hir::ModuleDef| {
1061 if !targets.contains(&item) {
1062 targets.push(item);
1063 }
1064 };
1065 walk_and_push_ty(sema.db, original, &mut push_new_def);
1066 captures.iter().for_each(|capture| {
1067 walk_and_push_ty(sema.db, &capture.ty(sema.db), &mut push_new_def);
1068 });
1069
1070 let adjusted = if let Some(adjusted_ty) = adjusted {
1071 walk_and_push_ty(sema.db, adjusted_ty, &mut push_new_def);
1072 format!(
1073 "\nCoerced to: {}",
1074 adjusted_ty
1075 .display(sema.db, display_target)
1076 .with_closure_style(hir::ClosureStyle::ImplFn)
1077 )
1078 } else {
1079 String::new()
1080 };
1081 let mut markup = format!("```rust\n{}\n```", c.display_with_impl(sema.db, display_target));
1082
1083 if let Some(trait_) = c.fn_trait(sema.db).get_id(sema.db, original.krate(sema.db)) {
1084 push_new_def(trait_.into())
1085 }
1086 if let Some(layout) = render_memory_layout(
1087 config.memory_layout,
1088 || original.layout(sema.db),
1089 |_| None,
1090 |_| None,
1091 |_| None,
1092 ) {
1093 format_to!(markup, "\n---\n{layout}");
1094 }
1095 format_to!(markup, "{adjusted}\n\n## Captures\n{}", captures_rendered,);
1096
1097 let mut res = HoverResult::default();
1098 if let Some(actions) = HoverAction::goto_type_from_targets(sema, targets, edition) {
1099 res.actions.push(actions);
1100 }
1101 res.markup = markup.into();
1102 Some(res)
1103}
1104
1105fn definition_path(db: &RootDatabase, &def: &Definition<'_>, edition: Edition) -> Option<String> {
1106 if matches!(
1107 def,
1108 Definition::TupleField(_)
1109 | Definition::Label(_)
1110 | Definition::Local(_)
1111 | Definition::BuiltinAttr(_)
1112 | Definition::BuiltinLifetime(_)
1113 | Definition::BuiltinType(_)
1114 | Definition::InlineAsmRegOrRegClass(_)
1115 | Definition::InlineAsmOperand(_)
1116 ) {
1117 return None;
1118 }
1119 let rendered_parent = definition_owner_name(db, def, edition);
1120 def.module(db).map(|module| path(db, module, rendered_parent, edition))
1121}
1122
1123fn markup(
1124 docs: Option<Either<Cow<'_, hir::Docs>, Documentation<'_>>>,
1125 rust: String,
1126 extra: Option<String>,
1127 mod_path: Option<String>,
1128 subst_types: String,
1129) -> (Markup, Option<hir::Docs>) {
1130 let mut buf = String::new();
1131
1132 if let Some(mod_path) = mod_path
1133 && !mod_path.is_empty()
1134 {
1135 format_to!(buf, "```rust\n{}\n```\n\n", mod_path);
1136 }
1137 format_to!(buf, "```rust\n{}\n```", rust);
1138
1139 if let Some(extra) = extra {
1140 buf.push_str(&extra);
1141 }
1142
1143 if !subst_types.is_empty() {
1144 format_to!(buf, "\n___\n{subst_types}");
1145 }
1146
1147 if let Some(doc) = docs {
1148 format_to!(buf, "\n___\n\n");
1149 let offset = TextSize::new(buf.len() as u32);
1150 let docs_str = match &doc {
1151 Either::Left(docs) => docs.docs(),
1152 Either::Right(docs) => docs.as_str(),
1153 };
1154 format_to!(buf, "{}", docs_str);
1155 let range_map = match doc {
1156 Either::Left(range_map) => {
1157 let mut range_map = range_map.into_owned();
1158 range_map.shift_by(offset);
1159 Some(range_map)
1160 }
1161 Either::Right(_) => None,
1162 };
1163
1164 (buf.into(), range_map)
1165 } else {
1166 (buf.into(), None)
1167 }
1168}
1169
1170fn render_memory_layout<'db>(
1171 config: Option<MemoryLayoutHoverConfig>,
1172 layout: impl FnOnce() -> Result<Layout<'db>, LayoutError>,
1173 offset: impl FnOnce(&Layout<'db>) -> Option<u64>,
1174 padding: impl for<'a> FnOnce(&'a Layout<'db>) -> Option<(&'a str, u64)>,
1175 tag: impl FnOnce(&Layout<'db>) -> Option<usize>,
1176) -> Option<String> {
1177 let config = config?;
1178 let layout = layout().ok()?;
1179
1180 let mut label = String::new();
1181
1182 if let Some(render) = config.size {
1183 let size = match tag(&layout) {
1184 Some(tag) => layout.size() as usize - tag,
1185 None => layout.size() as usize,
1186 };
1187 format_to!(label, "size = ");
1188 match render {
1189 MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{size}"),
1190 MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{size:#X}"),
1191 MemoryLayoutHoverRenderKind::Both if size >= 10 => {
1192 format_to!(label, "{size} ({size:#X})")
1193 }
1194 MemoryLayoutHoverRenderKind::Both => format_to!(label, "{size}"),
1195 }
1196 format_to!(label, ", ");
1197 }
1198
1199 if let Some(render) = config.alignment {
1200 let align = layout.align();
1201 format_to!(label, "align = ");
1202 match render {
1203 MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{align}",),
1204 MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{align:#X}",),
1205 MemoryLayoutHoverRenderKind::Both if align >= 10 => {
1206 format_to!(label, "{align} ({align:#X})")
1207 }
1208 MemoryLayoutHoverRenderKind::Both => {
1209 format_to!(label, "{align}")
1210 }
1211 }
1212 format_to!(label, ", ");
1213 }
1214
1215 if let Some(render) = config.offset
1216 && let Some(offset) = offset(&layout)
1217 {
1218 format_to!(label, "offset = ");
1219 match render {
1220 MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{offset}"),
1221 MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{offset:#X}"),
1222 MemoryLayoutHoverRenderKind::Both if offset >= 10 => {
1223 format_to!(label, "{offset} ({offset:#X})")
1224 }
1225 MemoryLayoutHoverRenderKind::Both => {
1226 format_to!(label, "{offset}")
1227 }
1228 }
1229 format_to!(label, ", ");
1230 }
1231
1232 if let Some(render) = config.padding
1233 && let Some((padding_name, padding)) = padding(&layout)
1234 {
1235 format_to!(label, "{padding_name} = ");
1236 match render {
1237 MemoryLayoutHoverRenderKind::Decimal => format_to!(label, "{padding}"),
1238 MemoryLayoutHoverRenderKind::Hexadecimal => format_to!(label, "{padding:#X}"),
1239 MemoryLayoutHoverRenderKind::Both if padding >= 10 => {
1240 format_to!(label, "{padding} ({padding:#X})")
1241 }
1242 MemoryLayoutHoverRenderKind::Both => {
1243 format_to!(label, "{padding}")
1244 }
1245 }
1246 format_to!(label, ", ");
1247 }
1248
1249 if config.niches
1250 && let Some(niches) = layout.niches()
1251 {
1252 if niches > 1024 {
1253 if niches.is_power_of_two() {
1254 format_to!(label, "niches = 2{}, ", pwr2_to_exponent(niches));
1255 } else if is_pwr2plus1(niches) {
1256 format_to!(label, "niches = 2{} + 1, ", pwr2_to_exponent(niches - 1));
1257 } else if is_pwr2minus1(niches) {
1258 format_to!(label, "niches = 2{} - 1, ", pwr2_to_exponent(niches + 1));
1259 } else {
1260 format_to!(label, "niches = a lot, ");
1261 }
1262 } else {
1263 format_to!(label, "niches = {niches}, ");
1264 }
1265 }
1266 label.pop(); label.pop(); Some(label)
1269}
1270
1271struct KeywordHint {
1272 description: String,
1273 keyword_mod: String,
1274 actions: Vec<HoverAction>,
1275}
1276
1277impl KeywordHint {
1278 fn new(description: String, keyword_mod: String) -> Self {
1279 Self { description, keyword_mod, actions: Vec::default() }
1280 }
1281}
1282
1283fn keyword_hints(
1284 sema: &Semantics<'_, RootDatabase>,
1285 token: &SyntaxToken,
1286 parent: syntax::SyntaxNode,
1287 edition: Edition,
1288 display_target: DisplayTarget,
1289) -> KeywordHint {
1290 match token.kind() {
1291 T![await] | T![loop] | T![match] | T![unsafe] | T![as] | T![try] | T![if] | T![else] => {
1292 let keyword_mod = format!("{}_keyword", token.text());
1293
1294 match ast::Expr::cast(parent).and_then(|site| sema.type_of_expr(&site)) {
1295 Some(ty) if !ty.adjusted.as_ref().unwrap_or(&ty.original).is_unit() => {
1297 let mut targets: Vec<hir::ModuleDef> = Vec::new();
1298 let mut push_new_def = |item: hir::ModuleDef| {
1299 if !targets.contains(&item) {
1300 targets.push(item);
1301 }
1302 };
1303 walk_and_push_ty(sema.db, &ty.original, &mut push_new_def);
1304
1305 let ty = ty.adjusted();
1306 let description =
1307 format!("{}: {}", token.text(), ty.display(sema.db, display_target));
1308
1309 KeywordHint {
1310 description,
1311 keyword_mod,
1312 actions: HoverAction::goto_type_from_targets(sema, targets, edition)
1313 .into_iter()
1314 .collect(),
1315 }
1316 }
1317 _ => KeywordHint {
1318 description: token.text().to_owned(),
1319 keyword_mod,
1320 actions: Vec::new(),
1321 },
1322 }
1323 }
1324 T![fn] => {
1325 let module = match ast::FnPtrType::cast(parent) {
1326 Some(_) => format!("prim_{}", token.text()),
1328 None => format!("{}_keyword", token.text()),
1329 };
1330 KeywordHint::new(token.text().to_owned(), module)
1331 }
1332 T![Self] => KeywordHint::new(token.text().to_owned(), "self_upper_keyword".into()),
1333 _ => KeywordHint::new(token.text().to_owned(), format!("{}_keyword", token.text())),
1334 }
1335}
1336
1337fn render_dyn_compatibility(
1338 db: &RootDatabase,
1339 buf: &mut String,
1340 safety: Option<DynCompatibilityViolation>,
1341) {
1342 let Some(osv) = safety else {
1343 buf.push_str("Is dyn-compatible");
1344 return;
1345 };
1346 buf.push_str("Is not dyn-compatible due to ");
1347 match osv {
1348 DynCompatibilityViolation::SizedSelf => {
1349 buf.push_str("having a `Self: Sized` bound");
1350 }
1351 DynCompatibilityViolation::SupertraitSelf => {
1352 buf.push_str("having a bound that references `Self`");
1353 }
1354 DynCompatibilityViolation::ExplicitlyDynIncompatible => {
1355 buf.push_str("having opted out of dyn-compatibility")
1356 }
1357 DynCompatibilityViolation::SupertraitNonLifetimeBinder => {
1358 buf.push_str("non-lifetime `for<...>` variables")
1359 }
1360 DynCompatibilityViolation::SupertraitConst => buf.push_str("having a `const` supertrait"),
1361 DynCompatibilityViolation::Method(func, mvc) => {
1362 let name = func.name(db);
1363 format_to!(buf, "having a method `{}` that is not dispatchable due to ", name.as_str());
1364 let desc = match mvc {
1365 MethodViolation::StaticMethod => "missing a receiver",
1366 MethodViolation::ReferencesSelfInput => "having a parameter referencing `Self`",
1367 MethodViolation::ReferencesSelfOutput => "the return type referencing `Self`",
1368 MethodViolation::ReferencesImplTraitInTrait => {
1369 "the return type containing `impl Trait`"
1370 }
1371 MethodViolation::AsyncFn => "being async",
1372 MethodViolation::WhereClauseReferencesSelf => "a where clause referencing `Self`",
1373 MethodViolation::Generic => "having a const or type generic parameter",
1374 MethodViolation::UndispatchableReceiver => {
1375 "having a non-dispatchable receiver type"
1376 }
1377 MethodViolation::CVariadic => "being C-variadic",
1378 };
1379 buf.push_str(desc);
1380 }
1381 DynCompatibilityViolation::AssocConst(const_, _) => {
1382 let name = const_.name(db);
1384 if let Some(name) = name {
1385 format_to!(buf, "having an associated constant `{}`", name.as_str());
1386 } else {
1387 buf.push_str("having an associated constant");
1388 }
1389 }
1390 DynCompatibilityViolation::GenericAssocTy(alias) => {
1391 let name = alias.name(db);
1392 format_to!(buf, "having a generic associated type `{}`", name.as_str());
1393 }
1394 DynCompatibilityViolation::HasNonCompatibleSuperTrait(super_trait, _) => {
1395 let name = super_trait.name(db);
1397 format_to!(buf, "having a dyn-incompatible supertrait `{}`", name.as_str());
1398 }
1399 }
1400}
1401
1402fn is_pwr2minus1(val: u128) -> bool {
1403 val == u128::MAX || (val + 1).is_power_of_two()
1404}
1405
1406fn is_pwr2plus1(val: u128) -> bool {
1407 val != 0 && (val - 1).is_power_of_two()
1408}
1409
1410fn pwr2_to_exponent(num: u128) -> String {
1413 const DIGITS: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
1414 assert_eq!(num.count_ones(), 1);
1415 num.trailing_zeros()
1416 .to_string()
1417 .chars()
1418 .map(|c| c.to_digit(10).unwrap() as usize)
1419 .map(|idx| DIGITS[idx])
1420 .collect::<String>()
1421}
1422
1423#[cfg(test)]
1424mod tests {
1425 use super::*;
1426
1427 const TESTERS: [u128; 10] = [0, 1, 2, 3, 4, 255, 256, 257, u128::MAX - 1, u128::MAX];
1428
1429 #[test]
1430 fn test_is_pwr2minus1() {
1431 const OUTCOMES: [bool; 10] =
1432 [true, true, false, true, false, true, false, false, false, true];
1433 for (test, expected) in TESTERS.iter().zip(OUTCOMES) {
1434 let actual = is_pwr2minus1(*test);
1435 assert_eq!(actual, expected, "is_pwr2minu1({test}) gave {actual}, expected {expected}");
1436 }
1437 }
1438
1439 #[test]
1440 fn test_is_pwr2plus1() {
1441 const OUTCOMES: [bool; 10] =
1442 [false, false, true, true, false, false, false, true, false, false];
1443 for (test, expected) in TESTERS.iter().zip(OUTCOMES) {
1444 let actual = is_pwr2plus1(*test);
1445 assert_eq!(actual, expected, "is_pwr2plus1({test}) gave {actual}, expected {expected}");
1446 }
1447 }
1448
1449 #[test]
1450 fn test_pwr2_to_exponent() {
1451 const TESTERS: [u128; 9] = [
1452 1,
1453 2,
1454 4,
1455 8,
1456 16,
1457 9223372036854775808,
1458 18446744073709551616,
1459 36893488147419103232,
1460 170141183460469231731687303715884105728,
1461 ];
1462 const OUTCOMES: [&str; 9] = ["⁰", "¹", "²", "³", "⁴", "⁶³", "⁶⁴", "⁶⁵", "¹²⁷"];
1463 for (test, expected) in TESTERS.iter().zip(OUTCOMES) {
1464 let actual = pwr2_to_exponent(*test);
1465 assert_eq!(
1466 actual, expected,
1467 "pwr2_to_exponent({test}) returned {actual}, expected {expected}",
1468 );
1469 }
1470 }
1471}