]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/effect.rs
mk: The beta channel produces things called 'beta'
[rust.git] / src / librustc / middle / effect.rs
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.
4 //
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.
10
11 //! Enforces the Rust effect system. Currently there is just one effect,
12 /// `unsafe`.
13 use self::UnsafeContext::*;
14
15 use middle::def;
16 use middle::ty::{self, Ty};
17 use middle::ty::MethodCall;
18 use util::ppaux;
19
20 use syntax::ast;
21 use syntax::ast_util::PostExpansionMethod;
22 use syntax::codemap::Span;
23 use syntax::visit;
24 use syntax::visit::Visitor;
25
26 #[derive(Copy, PartialEq)]
27 enum UnsafeContext {
28     SafeContext,
29     UnsafeFn,
30     UnsafeBlock(ast::NodeId),
31 }
32
33 fn type_is_unsafe_function(ty: Ty) -> bool {
34     match ty.sty {
35         ty::ty_bare_fn(_, ref f) => f.unsafety == ast::Unsafety::Unsafe,
36         _ => false,
37     }
38 }
39
40 struct EffectCheckVisitor<'a, 'tcx: 'a> {
41     tcx: &'a ty::ctxt<'tcx>,
42
43     /// Whether we're in an unsafe context.
44     unsafe_context: UnsafeContext,
45 }
46
47 impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
48     fn require_unsafe(&mut self, span: Span, description: &str) {
49         match self.unsafe_context {
50             SafeContext => {
51                 // Report an error.
52                 span_err!(self.tcx.sess, span, E0133,
53                           "{} requires unsafe function or block",
54                           description);
55             }
56             UnsafeBlock(block_id) => {
57                 // OK, but record this.
58                 debug!("effect: recording unsafe block as used: {}", block_id);
59                 self.tcx.used_unsafe.borrow_mut().insert(block_id);
60             }
61             UnsafeFn => {}
62         }
63     }
64
65     fn check_str_index(&mut self, e: &ast::Expr) {
66         let base_type = match e.node {
67             ast::ExprIndex(ref base, _) => ty::node_id_to_type(self.tcx, base.id),
68             _ => return
69         };
70         debug!("effect: checking index with base type {}",
71                 ppaux::ty_to_string(self.tcx, base_type));
72         match base_type.sty {
73             ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => if ty::ty_str == ty.sty {
74                 span_err!(self.tcx.sess, e.span, E0134,
75                           "modification of string types is not allowed");
76             },
77             ty::ty_str => {
78                 span_err!(self.tcx.sess, e.span, E0135,
79                           "modification of string types is not allowed");
80             }
81             _ => {}
82         }
83     }
84 }
85
86 impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
87     fn visit_fn(&mut self, fn_kind: visit::FnKind<'v>, fn_decl: &'v ast::FnDecl,
88                 block: &'v ast::Block, span: Span, _: ast::NodeId) {
89
90         let (is_item_fn, is_unsafe_fn) = match fn_kind {
91             visit::FkItemFn(_, _, fn_style, _) =>
92                 (true, fn_style == ast::Unsafety::Unsafe),
93             visit::FkMethod(_, _, method) =>
94                 (true, method.pe_unsafety() == ast::Unsafety::Unsafe),
95             _ => (false, false),
96         };
97
98         let old_unsafe_context = self.unsafe_context;
99         if is_unsafe_fn {
100             self.unsafe_context = UnsafeFn
101         } else if is_item_fn {
102             self.unsafe_context = SafeContext
103         }
104
105         visit::walk_fn(self, fn_kind, fn_decl, block, span);
106
107         self.unsafe_context = old_unsafe_context
108     }
109
110     fn visit_block(&mut self, block: &ast::Block) {
111         let old_unsafe_context = self.unsafe_context;
112         match block.rules {
113             ast::DefaultBlock => {}
114             ast::UnsafeBlock(source) => {
115                 // By default only the outermost `unsafe` block is
116                 // "used" and so nested unsafe blocks are pointless
117                 // (the inner ones are unnecessary and we actually
118                 // warn about them). As such, there are two cases when
119                 // we need to create a new context, when we're
120                 // - outside `unsafe` and found a `unsafe` block
121                 //   (normal case)
122                 // - inside `unsafe`, found an `unsafe` block
123                 //   created internally to the compiler
124                 //
125                 // The second case is necessary to ensure that the
126                 // compiler `unsafe` blocks don't accidentally "use"
127                 // external blocks (e.g. `unsafe { println("") }`,
128                 // expands to `unsafe { ... unsafe { ... } }` where
129                 // the inner one is compiler generated).
130                 if self.unsafe_context == SafeContext || source == ast::CompilerGenerated {
131                     self.unsafe_context = UnsafeBlock(block.id)
132                 }
133             }
134         }
135
136         visit::walk_block(self, block);
137
138         self.unsafe_context = old_unsafe_context
139     }
140
141     fn visit_expr(&mut self, expr: &ast::Expr) {
142         match expr.node {
143             ast::ExprMethodCall(_, _, _) => {
144                 let method_call = MethodCall::expr(expr.id);
145                 let base_type = (*self.tcx.method_map.borrow())[method_call].ty;
146                 debug!("effect: method call case, base type is {}",
147                        ppaux::ty_to_string(self.tcx, base_type));
148                 if type_is_unsafe_function(base_type) {
149                     self.require_unsafe(expr.span,
150                                         "invocation of unsafe method")
151                 }
152             }
153             ast::ExprCall(ref base, _) => {
154                 let base_type = ty::node_id_to_type(self.tcx, base.id);
155                 debug!("effect: call case, base type is {}",
156                        ppaux::ty_to_string(self.tcx, base_type));
157                 if type_is_unsafe_function(base_type) {
158                     self.require_unsafe(expr.span, "call to unsafe function")
159                 }
160             }
161             ast::ExprUnary(ast::UnDeref, ref base) => {
162                 let base_type = ty::node_id_to_type(self.tcx, base.id);
163                 debug!("effect: unary case, base type is {}",
164                        ppaux::ty_to_string(self.tcx, base_type));
165                 if let ty::ty_ptr(_) = base_type.sty {
166                     self.require_unsafe(expr.span, "dereference of unsafe pointer")
167                 }
168             }
169             ast::ExprAssign(ref base, _) | ast::ExprAssignOp(_, ref base, _) => {
170                 self.check_str_index(&**base);
171             }
172             ast::ExprAddrOf(ast::MutMutable, ref base) => {
173                 self.check_str_index(&**base);
174             }
175             ast::ExprInlineAsm(..) => {
176                 self.require_unsafe(expr.span, "use of inline assembly");
177             }
178             ast::ExprPath(..) => {
179                 if let def::DefStatic(_, true) = ty::resolve_expr(self.tcx, expr) {
180                     self.require_unsafe(expr.span, "use of mutable static");
181                 }
182             }
183             _ => {}
184         }
185
186         visit::walk_expr(self, expr);
187     }
188 }
189
190 pub fn check_crate(tcx: &ty::ctxt) {
191     let mut visitor = EffectCheckVisitor {
192         tcx: tcx,
193         unsafe_context: SafeContext,
194     };
195
196     visit::walk_crate(&mut visitor, tcx.map.krate());
197 }