|
| 1 | +// Copyright 2015 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 | +//! labels.rs |
| 12 | +//! |
| 13 | +//! Issue #21633: Check for duplicate loop-labels anywhere in a |
| 14 | +//! function body. |
| 15 | +
|
| 16 | + |
| 17 | +use CrateCtxt; |
| 18 | + |
| 19 | +use syntax::ast; |
| 20 | +use syntax::codemap::Span; |
| 21 | +use syntax::visit::{self, Visitor}; |
| 22 | + |
| 23 | +use std::mem::replace; |
| 24 | + |
| 25 | +pub struct CheckLoopLabelsVisitor<'a, 'tcx: 'a> { |
| 26 | + ccx: &'a CrateCtxt<'a, 'tcx>, |
| 27 | + labels_in_fn: Vec<(ast::Ident, Span)>, |
| 28 | +} |
| 29 | + |
| 30 | +impl<'a, 'tcx:'a> CheckLoopLabelsVisitor<'a, 'tcx> { |
| 31 | + pub fn new(ccx: &'a CrateCtxt<'a, 'tcx>) -> CheckLoopLabelsVisitor<'a, 'tcx> { |
| 32 | + CheckLoopLabelsVisitor { ccx: ccx, labels_in_fn: vec![] } |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +impl<'a, 'tcx> Visitor<'tcx> for CheckLoopLabelsVisitor<'a, 'tcx> { |
| 37 | + fn visit_fn(&mut self, fk: visit::FnKind<'tcx>, fd: &'tcx ast::FnDecl, |
| 38 | + b: &'tcx ast::Block, s: Span, _: ast::NodeId) |
| 39 | + { |
| 40 | + let saved = replace(&mut self.labels_in_fn, vec![]); |
| 41 | + visit::walk_fn(self, fk, fd, b, s); |
| 42 | + replace(&mut self.labels_in_fn, saved); |
| 43 | + } |
| 44 | + |
| 45 | + fn visit_expr(&mut self, ex: &'tcx ast::Expr) { |
| 46 | + let opt_label = match ex.node { |
| 47 | + ast::ExprWhile(_, _, label) | |
| 48 | + ast::ExprWhileLet(_, _, _, label) | |
| 49 | + ast::ExprForLoop(_, _, _, label) | |
| 50 | + ast::ExprLoop(_, label) => label, |
| 51 | + _ => None, |
| 52 | + }; |
| 53 | + let tcx = self.ccx.tcx; |
| 54 | + if let Some(curr_id) = opt_label { |
| 55 | + // Note: non-hygienic comparision here may reject code |
| 56 | + // that should actually be accepted. |
| 57 | + if let Some(&(_, span)) = self.labels_in_fn.iter() |
| 58 | + .find(|id_span| curr_id.name == id_span.0.name ) |
| 59 | + { |
| 60 | + span_err!(tcx.sess, ex.span, E0373, |
| 61 | + "duplicate loop label {} in function", |
| 62 | + curr_id); |
| 63 | + span_note!(tcx.sess, span, "first label occurrence here"); |
| 64 | + } else { |
| 65 | + self.labels_in_fn.push((curr_id, ex.span)); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + visit::walk_expr(self, ex) |
| 70 | + } |
| 71 | +} |
0 commit comments