-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
39 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,35 @@ | ||
extern crate rustc_hir; | ||
extern crate rustc_lint; | ||
extern crate rustc_middle; | ||
extern crate rustc_span; | ||
|
||
use rustc_hir::HirId; | ||
use rustc_hir::{FnDecl, FnRetTy, HirId, QPath}; | ||
use rustc_lint::LateContext; | ||
use rustc_middle::ty::Ty; | ||
use rustc_middle::ty::{Ty, TyKind}; | ||
use rustc_span::sym; | ||
|
||
/// Get the type of a node, if it exists. | ||
pub fn get_node_type_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: &HirId) -> Option<Ty<'tcx>> { | ||
cx.typeck_results().node_type_opt(*hir_id) | ||
} | ||
|
||
/// Match the type of an expression to a string. | ||
pub fn match_type_to_str(cx: &LateContext<'_>, expr_type: Ty<'_>, type_str: &str) -> bool { | ||
match expr_type.kind() { | ||
TyKind::Adt(adt_def, _) => cx.tcx.def_path_str(adt_def.did()).contains(type_str), | ||
TyKind::Ref(_, ty, _) => match_type_to_str(cx, *ty, type_str), | ||
_ => false, | ||
} | ||
} | ||
|
||
/// Check if a function returns a Result type. | ||
pub fn returns_result(decl: &FnDecl<'_>) -> bool { | ||
if let FnRetTy::Return(ty) = decl.output { | ||
matches!(ty.kind, rustc_hir::TyKind::Path(QPath::Resolved(_, path)) if path | ||
.segments | ||
.last() | ||
.map_or(false, |seg| seg.ident.name == sym::Result)) | ||
} else { | ||
false | ||
} | ||
} |