1 // Copyright 2012-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.
18 use visit::{FnKind, Visitor};
24 pub fn path_name_i(idents: &[Ident]) -> String {
25 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
26 idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
29 pub fn is_path(e: P<Expr>) -> bool {
30 match e.node { ExprPath(..) => true, _ => false }
34 // convert a span and an identifier to the corresponding
36 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
42 identifier: identifier,
43 parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
44 lifetimes: Vec::new(),
53 // If path is a single segment ident path, return that ident. Otherwise, return
55 pub fn path_to_ident(path: &Path) -> Option<Ident> {
56 if path.segments.len() != 1 {
60 let segment = &path.segments[0];
61 if !segment.parameters.is_empty() {
65 Some(segment.identifier)
68 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
71 node: PatIdent(BindingMode::ByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
76 /// Generate a "pretty" name for an `impl` from its type and trait.
77 /// This is designed so that symbols of `impl`'d methods give some
78 /// hint of where they came from, (previously they would all just be
79 /// listed as `__extensions__::method_name::hash`, with no indication
81 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
82 let mut pretty = match ty {
83 Some(t) => pprust::ty_to_string(t),
84 None => String::from("..")
88 Some(ref trait_ref) => {
90 pretty.push_str(&pprust::path_to_string(&trait_ref.path));
94 token::gensym_ident(&pretty[..])
97 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
98 match field.node.kind {
99 ast::NamedField(_, v) | ast::UnnamedField(v) => v
103 // ______________________________________________________________________
104 // Enumerating the IDs which appear in an AST
106 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
113 pub fn max() -> IdRange {
120 pub fn empty(&self) -> bool {
124 pub fn add(&mut self, id: NodeId) {
125 self.min = cmp::min(self.min, id);
126 self.max = cmp::max(self.max, id + 1);
130 pub trait IdVisitingOperation {
131 fn visit_id(&mut self, node_id: NodeId);
134 /// A visitor that applies its operation to all of the node IDs
135 /// in a visitable thing.
137 pub struct IdVisitor<'a, O:'a> {
138 pub operation: &'a mut O,
139 pub visited_outermost: bool,
142 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
143 fn visit_generics_helper(&mut self, generics: &Generics) {
144 for type_parameter in generics.ty_params.iter() {
145 self.operation.visit_id(type_parameter.id)
147 for lifetime in &generics.lifetimes {
148 self.operation.visit_id(lifetime.lifetime.id)
153 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
154 fn visit_mod(&mut self,
158 self.operation.visit_id(node_id);
159 visit::walk_mod(self, module)
162 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
163 self.operation.visit_id(foreign_item.id);
164 visit::walk_foreign_item(self, foreign_item)
167 fn visit_item(&mut self, item: &Item) {
168 if self.visited_outermost {
171 self.visited_outermost = true
174 self.operation.visit_id(item.id);
176 ItemUse(ref view_path) => {
177 match view_path.node {
178 ViewPathSimple(_, _) |
179 ViewPathGlob(_) => {}
180 ViewPathList(_, ref paths) => {
182 self.operation.visit_id(path.node.id())
190 visit::walk_item(self, item);
192 self.visited_outermost = false
195 fn visit_local(&mut self, local: &Local) {
196 self.operation.visit_id(local.id);
197 visit::walk_local(self, local)
200 fn visit_block(&mut self, block: &Block) {
201 self.operation.visit_id(block.id);
202 visit::walk_block(self, block)
205 fn visit_stmt(&mut self, statement: &Stmt) {
207 .visit_id(statement.node.id().expect("attempted to visit unexpanded stmt"));
208 visit::walk_stmt(self, statement)
211 fn visit_pat(&mut self, pattern: &Pat) {
212 self.operation.visit_id(pattern.id);
213 visit::walk_pat(self, pattern)
216 fn visit_expr(&mut self, expression: &Expr) {
217 self.operation.visit_id(expression.id);
218 visit::walk_expr(self, expression)
221 fn visit_ty(&mut self, typ: &Ty) {
222 self.operation.visit_id(typ.id);
223 visit::walk_ty(self, typ)
226 fn visit_generics(&mut self, generics: &Generics) {
227 self.visit_generics_helper(generics);
228 visit::walk_generics(self, generics)
231 fn visit_fn(&mut self,
232 function_kind: visit::FnKind<'v>,
233 function_declaration: &'v FnDecl,
237 match function_kind {
238 FnKind::Method(..) if self.visited_outermost => return,
239 FnKind::Method(..) => self.visited_outermost = true,
243 self.operation.visit_id(node_id);
245 match function_kind {
246 FnKind::ItemFn(_, generics, _, _, _, _) => {
247 self.visit_generics_helper(generics)
249 FnKind::Method(_, sig, _) => {
250 self.visit_generics_helper(&sig.generics)
252 FnKind::Closure => {}
255 for argument in &function_declaration.inputs {
256 self.operation.visit_id(argument.id)
261 function_declaration,
265 if let FnKind::Method(..) = function_kind {
266 self.visited_outermost = false;
270 fn visit_struct_field(&mut self, struct_field: &StructField) {
271 self.operation.visit_id(struct_field.node.id);
272 visit::walk_struct_field(self, struct_field)
275 fn visit_variant_data(&mut self,
276 struct_def: &VariantData,
281 self.operation.visit_id(struct_def.id());
282 visit::walk_struct_def(self, struct_def);
285 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
286 self.operation.visit_id(ti.id);
287 visit::walk_trait_item(self, ti);
290 fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
291 self.operation.visit_id(ii.id);
292 visit::walk_impl_item(self, ii);
295 fn visit_lifetime(&mut self, lifetime: &Lifetime) {
296 self.operation.visit_id(lifetime.id);
299 fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
300 self.visit_lifetime(&def.lifetime);
303 fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
304 self.operation.visit_id(trait_ref.ref_id);
305 visit::walk_trait_ref(self, trait_ref);
309 pub struct IdRangeComputingVisitor {
313 impl IdRangeComputingVisitor {
314 pub fn new() -> IdRangeComputingVisitor {
315 IdRangeComputingVisitor { result: IdRange::max() }
318 pub fn result(&self) -> IdRange {
323 impl IdVisitingOperation for IdRangeComputingVisitor {
324 fn visit_id(&mut self, id: NodeId) {
329 /// Computes the id range for a single fn body, ignoring nested items.
330 pub fn compute_id_range_for_fn_body(fk: FnKind,
337 let mut visitor = IdRangeComputingVisitor::new();
338 let mut id_visitor = IdVisitor {
339 operation: &mut visitor,
340 visited_outermost: false,
342 id_visitor.visit_fn(fk, decl, body, sp, id);
343 id_visitor.operation.result
346 /// Returns true if the given pattern consists solely of an identifier
347 /// and false otherwise.
348 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
350 ast::PatIdent(..) => true,
355 // are two paths equal when compared unhygienically?
356 // since I'm using this to replace ==, it seems appropriate
357 // to compare the span, global, etc. fields as well.
358 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
360 && (a.global == b.global)
361 && (segments_name_eq(&a.segments[..], &b.segments[..]))
364 // are two arrays of segments equal when compared unhygienically?
365 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
366 a.len() == b.len() &&
367 a.iter().zip(b).all(|(s, t)| {
368 s.identifier.name == t.identifier.name &&
369 // FIXME #7743: ident -> name problems in lifetime comparison?
370 // can types contain idents?
371 s.parameters == t.parameters
380 fn ident_to_segment(id: Ident) -> PathSegment {
381 PathSegment {identifier: id,
382 parameters: PathParameters::none()}
385 #[test] fn idents_name_eq_test() {
386 assert!(segments_name_eq(
387 &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
388 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
389 &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(78),SyntaxContext(182))]
390 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));
391 assert!(!segments_name_eq(
392 &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
393 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
394 &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(77),SyntaxContext(182))]
395 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));