1 // Copyright 2014 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 // This compiler pass detects static items that refer to themselves
15 use middle::def::{DefStatic, DefConst, DefMap};
18 use syntax::{ast_util, ast_map};
19 use syntax::visit::Visitor;
22 struct CheckCrateVisitor<'a, 'ast: 'a> {
25 ast_map: &'a ast_map::Map<'ast>
28 impl<'v, 'a, 'ast> Visitor<'v> for CheckCrateVisitor<'a, 'ast> {
29 fn visit_item(&mut self, i: &ast::Item) {
34 pub fn check_crate<'ast>(sess: &Session,
37 ast_map: &ast_map::Map<'ast>) {
38 let mut visitor = CheckCrateVisitor {
43 visit::walk_crate(&mut visitor, krate);
44 sess.abort_if_errors();
47 fn check_item(v: &mut CheckCrateVisitor, it: &ast::Item) {
49 ast::ItemStatic(_, _, ref ex) |
50 ast::ItemConst(_, ref ex) => {
51 check_item_recursion(v.sess, v.ast_map, v.def_map, it);
52 visit::walk_expr(v, &**ex)
54 _ => visit::walk_item(v, it)
58 struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
59 root_it: &'a ast::Item,
61 ast_map: &'a ast_map::Map<'ast>,
63 idstack: Vec<ast::NodeId>
66 // Make sure a const item doesn't recursively refer to itself
67 // FIXME: Should use the dependency graph when it's available (#1356)
68 pub fn check_item_recursion<'a>(sess: &'a Session,
69 ast_map: &'a ast_map::Map,
73 let mut visitor = CheckItemRecursionVisitor {
80 visitor.visit_item(it);
83 impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> {
84 fn visit_item(&mut self, it: &ast::Item) {
85 if self.idstack.iter().any(|x| x == &(it.id)) {
86 self.sess.span_err(self.root_it.span, "recursive constant");
89 self.idstack.push(it.id);
90 visit::walk_item(self, it);
94 fn visit_expr(&mut self, e: &ast::Expr) {
96 ast::ExprPath(_) | ast::ExprQPath(_) => {
97 match self.def_map.borrow().get(&e.id) {
98 Some(&DefStatic(def_id, _)) |
99 Some(&DefConst(def_id)) if
100 ast_util::is_local(def_id) => {
101 match self.ast_map.get(def_id.node) {
102 ast_map::NodeItem(item) =>
103 self.visit_item(item),
104 ast_map::NodeForeignItem(_) => {},
106 self.sess.span_err(e.span,
107 &format!("expected item, found {}",
108 self.ast_map.node_to_string(def_id.node))[]);
118 visit::walk_expr(self, e);