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