1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Enforces the Rust effect system. Currently there is just one effect,
13 use self::RootUnsafeContext::*;
15 use ty::{self, Ty, TyCtxt};
21 use hir::{self, PatKind};
23 use hir::intravisit::{self, FnKind, Visitor, NestedVisitorMap};
25 #[derive(Copy, Clone)]
26 struct UnsafeContext {
27 push_unsafe_count: usize,
28 root: RootUnsafeContext,
32 fn new(root: RootUnsafeContext) -> UnsafeContext {
33 UnsafeContext { root: root, push_unsafe_count: 0 }
37 #[derive(Copy, Clone, PartialEq)]
38 enum RootUnsafeContext {
41 UnsafeBlock(ast::NodeId),
44 fn type_is_unsafe_function(ty: Ty) -> bool {
47 ty::TyFnPtr(f) => f.unsafety() == hir::Unsafety::Unsafe,
52 struct EffectCheckVisitor<'a, 'tcx: 'a> {
53 tcx: TyCtxt<'a, 'tcx, 'tcx>,
54 tables: &'a ty::TypeckTables<'tcx>,
57 /// Whether we're in an unsafe context.
58 unsafe_context: UnsafeContext,
61 impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
62 fn require_unsafe_ext(&mut self, node_id: ast::NodeId, span: Span,
63 description: &str, is_lint: bool) {
64 if self.unsafe_context.push_unsafe_count > 0 { return; }
65 match self.unsafe_context.root {
68 self.tcx.sess.add_lint(lint::builtin::SAFE_EXTERN_STATICS,
71 format!("{} requires unsafe function or \
72 block (error E0133)", description));
76 self.tcx.sess, span, E0133,
77 "{} requires unsafe function or block", description)
78 .span_label(span, description)
82 UnsafeBlock(block_id) => {
83 // OK, but record this.
84 debug!("effect: recording unsafe block as used: {}", block_id);
85 self.tcx.used_unsafe.borrow_mut().insert(block_id);
91 fn require_unsafe(&mut self, span: Span, description: &str) {
92 self.require_unsafe_ext(ast::DUMMY_NODE_ID, span, description, false)
96 impl<'a, 'tcx> Visitor<'tcx> for EffectCheckVisitor<'a, 'tcx> {
97 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
98 NestedVisitorMap::None
101 fn visit_nested_body(&mut self, body: hir::BodyId) {
102 let old_tables = self.tables;
103 let old_body_id = self.body_id;
104 self.tables = self.tcx.body_tables(body);
106 let body = self.tcx.hir.body(body);
107 self.visit_body(body);
108 self.tables = old_tables;
109 self.body_id = old_body_id;
112 fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, fn_decl: &'tcx hir::FnDecl,
113 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
115 let (is_item_fn, is_unsafe_fn) = match fn_kind {
116 FnKind::ItemFn(_, _, unsafety, ..) =>
117 (true, unsafety == hir::Unsafety::Unsafe),
118 FnKind::Method(_, sig, ..) =>
119 (true, sig.unsafety == hir::Unsafety::Unsafe),
123 let old_unsafe_context = self.unsafe_context;
125 self.unsafe_context = UnsafeContext::new(UnsafeFn)
126 } else if is_item_fn {
127 self.unsafe_context = UnsafeContext::new(SafeContext)
130 intravisit::walk_fn(self, fn_kind, fn_decl, body_id, span, id);
132 self.unsafe_context = old_unsafe_context
135 fn visit_block(&mut self, block: &'tcx hir::Block) {
136 let old_unsafe_context = self.unsafe_context;
138 hir::UnsafeBlock(source) => {
139 // By default only the outermost `unsafe` block is
140 // "used" and so nested unsafe blocks are pointless
141 // (the inner ones are unnecessary and we actually
142 // warn about them). As such, there are two cases when
143 // we need to create a new context, when we're
144 // - outside `unsafe` and found a `unsafe` block
146 // - inside `unsafe`, found an `unsafe` block
147 // created internally to the compiler
149 // The second case is necessary to ensure that the
150 // compiler `unsafe` blocks don't accidentally "use"
151 // external blocks (e.g. `unsafe { println("") }`,
152 // expands to `unsafe { ... unsafe { ... } }` where
153 // the inner one is compiler generated).
154 if self.unsafe_context.root == SafeContext || source == hir::CompilerGenerated {
155 self.unsafe_context.root = UnsafeBlock(block.id)
158 hir::PushUnsafeBlock(..) => {
159 self.unsafe_context.push_unsafe_count =
160 self.unsafe_context.push_unsafe_count.checked_add(1).unwrap();
162 hir::PopUnsafeBlock(..) => {
163 self.unsafe_context.push_unsafe_count =
164 self.unsafe_context.push_unsafe_count.checked_sub(1).unwrap();
166 hir::DefaultBlock => {}
169 intravisit::walk_block(self, block);
171 self.unsafe_context = old_unsafe_context
174 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
176 hir::ExprMethodCall(..) => {
177 let method_call = MethodCall::expr(expr.id);
178 let base_type = self.tables.method_map[&method_call].ty;
179 debug!("effect: method call case, base type is {:?}",
181 if type_is_unsafe_function(base_type) {
182 self.require_unsafe(expr.span,
183 "invocation of unsafe method")
186 hir::ExprCall(ref base, _) => {
187 let base_type = self.tables.expr_ty_adjusted(base);
188 debug!("effect: call case, base type is {:?}",
190 if type_is_unsafe_function(base_type) {
191 self.require_unsafe(expr.span, "call to unsafe function")
194 hir::ExprUnary(hir::UnDeref, ref base) => {
195 let base_type = self.tables.expr_ty_adjusted(base);
196 debug!("effect: unary case, base type is {:?}",
198 if let ty::TyRawPtr(_) = base_type.sty {
199 self.require_unsafe(expr.span, "dereference of raw pointer")
202 hir::ExprInlineAsm(..) => {
203 self.require_unsafe(expr.span, "use of inline assembly");
205 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
206 if let Def::Static(def_id, mutbl) = path.def {
208 self.require_unsafe(expr.span, "use of mutable static");
209 } else if match self.tcx.hir.get_if_local(def_id) {
210 Some(hir::map::NodeForeignItem(..)) => true,
212 None => self.tcx.is_foreign_item(def_id),
214 self.require_unsafe_ext(expr.id, expr.span, "use of extern static", true);
218 hir::ExprField(ref base_expr, field) => {
219 if let ty::TyAdt(adt, ..) = self.tables.expr_ty_adjusted(base_expr).sty {
221 self.require_unsafe(field.span, "access to union field");
225 hir::ExprAssign(ref lhs, ref rhs) => {
226 if let hir::ExprField(ref base_expr, field) = lhs.node {
227 if let ty::TyAdt(adt, ..) = self.tables.expr_ty_adjusted(base_expr).sty {
229 let field_ty = self.tables.expr_ty_adjusted(lhs);
230 let owner_def_id = self.tcx.hir.body_owner_def_id(self.body_id);
231 let param_env = self.tcx.param_env(owner_def_id);
232 if field_ty.moves_by_default(self.tcx, param_env, field.span) {
233 self.require_unsafe(field.span,
234 "assignment to non-`Copy` union field");
236 // Do not walk the field expr again.
237 intravisit::walk_expr(self, base_expr);
238 intravisit::walk_expr(self, rhs);
247 intravisit::walk_expr(self, expr);
250 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
251 if let PatKind::Struct(_, ref fields, _) = pat.node {
252 if let ty::TyAdt(adt, ..) = self.tables.pat_ty(pat).sty {
254 for field in fields {
255 self.require_unsafe(field.span, "matching on union field");
261 intravisit::walk_pat(self, pat);
265 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
266 let mut visitor = EffectCheckVisitor {
268 tables: &ty::TypeckTables::empty(),
269 body_id: hir::BodyId { node_id: ast::CRATE_NODE_ID },
270 unsafe_context: UnsafeContext::new(SafeContext),
273 tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());