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