1 //! Checks validity of naked functions.
3 use rustc_ast::InlineAsmOptions;
5 use rustc_hir::def::DefKind;
6 use rustc_hir::def_id::LocalDefId;
7 use rustc_hir::intravisit::Visitor;
8 use rustc_hir::{ExprKind, InlineAsmOperand, StmtKind};
9 use rustc_middle::ty::query::Providers;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_session::lint::builtin::UNDEFINED_NAKED_FUNCTION_ABI;
12 use rustc_span::symbol::sym;
14 use rustc_target::spec::abi::Abi;
17 CannotInlineNakedFunction, NakedFunctionsAsmBlock, NakedFunctionsAsmOptions,
18 NakedFunctionsMustUseNoreturn, NakedFunctionsOperands, NoPatterns, ParamsNotAllowed,
19 UndefinedNakedFunctionAbi,
22 pub(crate) fn provide(providers: &mut Providers) {
23 *providers = Providers { check_mod_naked_functions, ..*providers };
26 fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
27 let items = tcx.hir_module_items(module_def_id);
28 for def_id in items.definitions() {
29 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
33 let naked = tcx.has_attr(def_id.to_def_id(), sym::naked);
38 let (fn_header, body_id) = match tcx.hir().get_by_def_id(def_id) {
39 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })
40 | hir::Node::TraitItem(hir::TraitItem {
41 kind: hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
44 | hir::Node::ImplItem(hir::ImplItem {
45 kind: hir::ImplItemKind::Fn(sig, body_id),
47 }) => (sig.header, *body_id),
51 let body = tcx.hir().body(body_id);
52 check_abi(tcx, def_id, fn_header.abi);
53 check_no_patterns(tcx, body.params);
54 check_no_parameters_use(tcx, body);
55 check_asm(tcx, def_id, body);
56 check_inline(tcx, def_id);
60 /// Check that the function isn't inlined.
61 fn check_inline(tcx: TyCtxt<'_>, def_id: LocalDefId) {
62 let attrs = tcx.get_attrs(def_id.to_def_id(), sym::inline);
64 tcx.sess.emit_err(CannotInlineNakedFunction { span: attr.span });
68 /// Checks that function uses non-Rust ABI.
69 fn check_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, abi: Abi) {
71 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
72 let span = tcx.def_span(def_id);
73 tcx.emit_spanned_lint(
74 UNDEFINED_NAKED_FUNCTION_ABI,
77 UndefinedNakedFunctionAbi,
82 /// Checks that parameters don't use patterns. Mirrors the checks for function declarations.
83 fn check_no_patterns(tcx: TyCtxt<'_>, params: &[hir::Param<'_>]) {
85 match param.pat.kind {
87 | hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, _, None) => {}
89 tcx.sess.emit_err(NoPatterns { span: param.pat.span });
95 /// Checks that function parameters aren't used in the function body.
96 fn check_no_parameters_use<'tcx>(tcx: TyCtxt<'tcx>, body: &'tcx hir::Body<'tcx>) {
97 let mut params = hir::HirIdSet::default();
98 for param in body.params {
99 param.pat.each_binding(|_binding_mode, hir_id, _span, _ident| {
100 params.insert(hir_id);
103 CheckParameters { tcx, params }.visit_body(body);
106 struct CheckParameters<'tcx> {
108 params: hir::HirIdSet,
111 impl<'tcx> Visitor<'tcx> for CheckParameters<'tcx> {
112 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
113 if let hir::ExprKind::Path(hir::QPath::Resolved(
115 hir::Path { res: hir::def::Res::Local(var_hir_id), .. },
118 if self.params.contains(var_hir_id) {
119 self.tcx.sess.emit_err(ParamsNotAllowed { span: expr.span });
123 hir::intravisit::walk_expr(self, expr);
127 /// Checks that function body contains a single inline assembly block.
128 fn check_asm<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &'tcx hir::Body<'tcx>) {
129 let mut this = CheckInlineAssembly { tcx, items: Vec::new() };
130 this.visit_body(body);
131 if let [(ItemKind::Asm | ItemKind::Err, _)] = this.items[..] {
134 let mut must_show_error = false;
135 let mut has_asm = false;
136 let mut has_err = false;
137 let mut multiple_asms = vec![];
138 let mut non_asms = vec![];
139 for &(kind, span) in &this.items {
141 ItemKind::Asm if has_asm => {
142 must_show_error = true;
143 multiple_asms.push(span);
145 ItemKind::Asm => has_asm = true,
146 ItemKind::NonAsm => {
147 must_show_error = true;
150 ItemKind::Err => has_err = true,
154 // If the naked function only contains a single asm block and a non-zero number of
155 // errors, then don't show an additional error. This allows for appending/prepending
156 // `compile_error!("...")` statements and reduces error noise.
157 if must_show_error || !has_err {
158 tcx.sess.emit_err(NakedFunctionsAsmBlock {
159 span: tcx.def_span(def_id),
167 struct CheckInlineAssembly<'tcx> {
169 items: Vec<(ItemKind, Span)>,
172 #[derive(Copy, Clone)]
179 impl<'tcx> CheckInlineAssembly<'tcx> {
180 fn check_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, span: Span) {
183 | ExprKind::ConstBlock(..)
184 | ExprKind::Array(..)
186 | ExprKind::MethodCall(..)
188 | ExprKind::Binary(..)
189 | ExprKind::Unary(..)
194 | ExprKind::Match(..)
196 | ExprKind::Closure { .. }
197 | ExprKind::Assign(..)
198 | ExprKind::AssignOp(..)
199 | ExprKind::Field(..)
200 | ExprKind::Index(..)
202 | ExprKind::AddrOf(..)
204 | ExprKind::Break(..)
205 | ExprKind::Continue(..)
207 | ExprKind::Struct(..)
208 | ExprKind::Repeat(..)
209 | ExprKind::Yield(..) => {
210 self.items.push((ItemKind::NonAsm, span));
213 ExprKind::InlineAsm(ref asm) => {
214 self.items.push((ItemKind::Asm, span));
215 self.check_inline_asm(asm, span);
218 ExprKind::DropTemps(..) | ExprKind::Block(..) => {
219 hir::intravisit::walk_expr(self, expr);
223 self.items.push((ItemKind::Err, span));
228 fn check_inline_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) {
229 let unsupported_operands: Vec<Span> = asm
232 .filter_map(|&(ref op, op_sp)| match op {
233 InlineAsmOperand::Const { .. }
234 | InlineAsmOperand::SymFn { .. }
235 | InlineAsmOperand::SymStatic { .. } => None,
236 InlineAsmOperand::In { .. }
237 | InlineAsmOperand::Out { .. }
238 | InlineAsmOperand::InOut { .. }
239 | InlineAsmOperand::SplitInOut { .. } => Some(op_sp),
242 if !unsupported_operands.is_empty() {
243 self.tcx.sess.emit_err(NakedFunctionsOperands { unsupported_operands });
246 let unsupported_options: Vec<&'static str> = [
247 (InlineAsmOptions::MAY_UNWIND, "`may_unwind`"),
248 (InlineAsmOptions::NOMEM, "`nomem`"),
249 (InlineAsmOptions::NOSTACK, "`nostack`"),
250 (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"),
251 (InlineAsmOptions::PURE, "`pure`"),
252 (InlineAsmOptions::READONLY, "`readonly`"),
255 .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None })
258 if !unsupported_options.is_empty() {
259 self.tcx.sess.emit_err(NakedFunctionsAsmOptions {
261 unsupported_options: unsupported_options.join(", "),
265 if !asm.options.contains(InlineAsmOptions::NORETURN) {
269 .map_or_else(|| asm.template_strs.last().unwrap().2, |op| op.1)
272 self.tcx.sess.emit_err(NakedFunctionsMustUseNoreturn { span, last_span });
277 impl<'tcx> Visitor<'tcx> for CheckInlineAssembly<'tcx> {
278 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
280 StmtKind::Item(..) => {}
281 StmtKind::Local(..) => {
282 self.items.push((ItemKind::NonAsm, stmt.span));
284 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
285 self.check_expr(expr, stmt.span);
290 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
291 self.check_expr(&expr, expr.span);