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, TyCtxt};
20 use hir::{self, PatKind};
22 use hir::intravisit::{self, FnKind, Visitor, NestedVisitorMap};
24 #[derive(Copy, Clone)]
25 struct UnsafeContext {
26 push_unsafe_count: usize,
27 root: RootUnsafeContext,
31 fn new(root: RootUnsafeContext) -> UnsafeContext {
32 UnsafeContext { root: root, push_unsafe_count: 0 }
36 #[derive(Copy, Clone, PartialEq)]
37 enum RootUnsafeContext {
40 UnsafeBlock(ast::NodeId),
43 struct EffectCheckVisitor<'a, 'tcx: 'a> {
44 tcx: TyCtxt<'a, 'tcx, 'tcx>,
45 tables: &'a ty::TypeckTables<'tcx>,
48 /// Whether we're in an unsafe context.
49 unsafe_context: UnsafeContext,
52 impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
53 fn require_unsafe_ext(&mut self, node_id: ast::NodeId, span: Span,
54 description: &str, is_lint: bool) {
55 if self.unsafe_context.push_unsafe_count > 0 { return; }
56 match self.unsafe_context.root {
59 self.tcx.lint_node(lint::builtin::SAFE_EXTERN_STATICS,
62 &format!("{} requires unsafe function or \
63 block (error E0133)", description));
67 self.tcx.sess, span, E0133,
68 "{} requires unsafe function or block", description)
69 .span_label(span, description)
73 UnsafeBlock(block_id) => {
74 // OK, but record this.
75 debug!("effect: recording unsafe block as used: {}", block_id);
76 self.tcx.used_unsafe.borrow_mut().insert(block_id);
82 fn require_unsafe(&mut self, span: Span, description: &str) {
83 self.require_unsafe_ext(ast::DUMMY_NODE_ID, span, description, false)
87 impl<'a, 'tcx> Visitor<'tcx> for EffectCheckVisitor<'a, 'tcx> {
88 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
89 NestedVisitorMap::None
92 fn visit_nested_body(&mut self, body: hir::BodyId) {
93 let old_tables = self.tables;
94 let old_body_id = self.body_id;
95 self.tables = self.tcx.body_tables(body);
97 let body = self.tcx.hir.body(body);
98 self.visit_body(body);
99 self.tables = old_tables;
100 self.body_id = old_body_id;
103 fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, fn_decl: &'tcx hir::FnDecl,
104 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
106 let (is_item_fn, is_unsafe_fn) = match fn_kind {
107 FnKind::ItemFn(_, _, unsafety, ..) =>
108 (true, unsafety == hir::Unsafety::Unsafe),
109 FnKind::Method(_, sig, ..) =>
110 (true, sig.unsafety == hir::Unsafety::Unsafe),
114 let old_unsafe_context = self.unsafe_context;
116 self.unsafe_context = UnsafeContext::new(UnsafeFn)
117 } else if is_item_fn {
118 self.unsafe_context = UnsafeContext::new(SafeContext)
121 intravisit::walk_fn(self, fn_kind, fn_decl, body_id, span, id);
123 self.unsafe_context = old_unsafe_context
126 fn visit_block(&mut self, block: &'tcx hir::Block) {
127 let old_unsafe_context = self.unsafe_context;
129 hir::UnsafeBlock(source) => {
130 // By default only the outermost `unsafe` block is
131 // "used" and so nested unsafe blocks are pointless
132 // (the inner ones are unnecessary and we actually
133 // warn about them). As such, there are two cases when
134 // we need to create a new context, when we're
135 // - outside `unsafe` and found a `unsafe` block
137 // - inside `unsafe`, found an `unsafe` block
138 // created internally to the compiler
140 // The second case is necessary to ensure that the
141 // compiler `unsafe` blocks don't accidentally "use"
142 // external blocks (e.g. `unsafe { println("") }`,
143 // expands to `unsafe { ... unsafe { ... } }` where
144 // the inner one is compiler generated).
145 if self.unsafe_context.root == SafeContext || source == hir::CompilerGenerated {
146 self.unsafe_context.root = UnsafeBlock(block.id)
149 hir::PushUnsafeBlock(..) => {
150 self.unsafe_context.push_unsafe_count =
151 self.unsafe_context.push_unsafe_count.checked_add(1).unwrap();
153 hir::PopUnsafeBlock(..) => {
154 self.unsafe_context.push_unsafe_count =
155 self.unsafe_context.push_unsafe_count.checked_sub(1).unwrap();
157 hir::DefaultBlock => {}
160 intravisit::walk_block(self, block);
162 self.unsafe_context = old_unsafe_context
165 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
167 hir::ExprMethodCall(..) => {
168 let def_id = self.tables.type_dependent_defs[&expr.id].def_id();
169 let sig = self.tcx.fn_sig(def_id);
170 debug!("effect: method call case, signature is {:?}",
173 if sig.0.unsafety == hir::Unsafety::Unsafe {
174 self.require_unsafe(expr.span,
175 "invocation of unsafe method")
178 hir::ExprCall(ref base, _) => {
179 let base_type = self.tables.expr_ty_adjusted(base);
180 debug!("effect: call case, base type is {:?}",
182 match base_type.sty {
183 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
184 if base_type.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
185 self.require_unsafe(expr.span, "call to unsafe function")
191 hir::ExprUnary(hir::UnDeref, ref base) => {
192 let base_type = self.tables.expr_ty_adjusted(base);
193 debug!("effect: unary case, base type is {:?}",
195 if let ty::TyRawPtr(_) = base_type.sty {
196 self.require_unsafe(expr.span, "dereference of raw pointer")
199 hir::ExprInlineAsm(..) => {
200 self.require_unsafe(expr.span, "use of inline assembly");
202 hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
203 if let Def::Static(def_id, mutbl) = path.def {
205 self.require_unsafe(expr.span, "use of mutable static");
206 } else if match self.tcx.hir.get_if_local(def_id) {
207 Some(hir::map::NodeForeignItem(..)) => true,
209 None => self.tcx.is_foreign_item(def_id),
211 self.require_unsafe_ext(expr.id, expr.span, "use of extern static", true);
215 hir::ExprField(ref base_expr, field) => {
216 if let ty::TyAdt(adt, ..) = self.tables.expr_ty_adjusted(base_expr).sty {
218 self.require_unsafe(field.span, "access to union field");
222 hir::ExprAssign(ref lhs, ref rhs) => {
223 if let hir::ExprField(ref base_expr, field) = lhs.node {
224 if let ty::TyAdt(adt, ..) = self.tables.expr_ty_adjusted(base_expr).sty {
226 let field_ty = self.tables.expr_ty_adjusted(lhs);
227 let owner_def_id = self.tcx.hir.body_owner_def_id(self.body_id);
228 let param_env = self.tcx.param_env(owner_def_id);
229 if field_ty.moves_by_default(self.tcx, param_env, field.span) {
230 self.require_unsafe(field.span,
231 "assignment to non-`Copy` union field");
233 // Do not walk the field expr again.
234 intravisit::walk_expr(self, base_expr);
235 intravisit::walk_expr(self, rhs);
244 intravisit::walk_expr(self, expr);
247 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
248 if let PatKind::Struct(_, ref fields, _) = pat.node {
249 if let ty::TyAdt(adt, ..) = self.tables.pat_ty(pat).sty {
251 for field in fields {
252 self.require_unsafe(field.span, "matching on union field");
258 intravisit::walk_pat(self, pat);
262 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
263 let mut visitor = EffectCheckVisitor {
265 tables: &ty::TypeckTables::empty(),
266 body_id: hir::BodyId { node_id: ast::CRATE_NODE_ID },
267 unsafe_context: UnsafeContext::new(SafeContext),
270 tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());