]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_util.rs
Auto merge of #30286 - oli-obk:const_error_span, r=nikomatsakis
[rust.git] / src / libsyntax / ast_util.rs
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.
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 use ast::*;
12 use ast;
13 use codemap;
14 use codemap::Span;
15 use owned_slice::OwnedSlice;
16 use parse::token;
17 use print::pprust;
18 use ptr::P;
19 use visit::{FnKind, Visitor};
20 use visit;
21
22 use std::cmp;
23 use std::u32;
24
25 pub fn path_name_i(idents: &[Ident]) -> String {
26     // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
27     idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
28 }
29
30 pub fn is_path(e: P<Expr>) -> bool {
31     match e.node { ExprPath(..) => true, _ => false }
32 }
33
34
35 // convert a span and an identifier to the corresponding
36 // 1-segment path
37 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
38     ast::Path {
39         span: s,
40         global: false,
41         segments: vec!(
42             ast::PathSegment {
43                 identifier: identifier,
44                 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
45                     lifetimes: Vec::new(),
46                     types: OwnedSlice::empty(),
47                     bindings: OwnedSlice::empty(),
48                 })
49             }
50         ),
51     }
52 }
53
54 // If path is a single segment ident path, return that ident. Otherwise, return
55 // None.
56 pub fn path_to_ident(path: &Path) -> Option<Ident> {
57     if path.segments.len() != 1 {
58         return None;
59     }
60
61     let segment = &path.segments[0];
62     if !segment.parameters.is_empty() {
63         return None;
64     }
65
66     Some(segment.identifier)
67 }
68
69 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
70     P(Pat {
71         id: id,
72         node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
73         span: s
74     })
75 }
76
77 /// Generate a "pretty" name for an `impl` from its type and trait.
78 /// This is designed so that symbols of `impl`'d methods give some
79 /// hint of where they came from, (previously they would all just be
80 /// listed as `__extensions__::method_name::hash`, with no indication
81 /// of the type).
82 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
83     let mut pretty = match ty {
84         Some(t) => pprust::ty_to_string(t),
85         None => String::from("..")
86     };
87
88     match *trait_ref {
89         Some(ref trait_ref) => {
90             pretty.push('.');
91             pretty.push_str(&pprust::path_to_string(&trait_ref.path));
92         }
93         None => {}
94     }
95     token::gensym_ident(&pretty[..])
96 }
97
98 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
99     match field.node.kind {
100         ast::NamedField(_, v) | ast::UnnamedField(v) => v
101     }
102 }
103
104 // ______________________________________________________________________
105 // Enumerating the IDs which appear in an AST
106
107 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
108 pub struct IdRange {
109     pub min: NodeId,
110     pub max: NodeId,
111 }
112
113 impl IdRange {
114     pub fn max() -> IdRange {
115         IdRange {
116             min: u32::MAX,
117             max: u32::MIN,
118         }
119     }
120
121     pub fn empty(&self) -> bool {
122         self.min >= self.max
123     }
124
125     pub fn add(&mut self, id: NodeId) {
126         self.min = cmp::min(self.min, id);
127         self.max = cmp::max(self.max, id + 1);
128     }
129 }
130
131 pub trait IdVisitingOperation {
132     fn visit_id(&mut self, node_id: NodeId);
133 }
134
135 /// A visitor that applies its operation to all of the node IDs
136 /// in a visitable thing.
137
138 pub struct IdVisitor<'a, O:'a> {
139     pub operation: &'a mut O,
140     pub visited_outermost: bool,
141 }
142
143 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
144     fn visit_generics_helper(&mut self, generics: &Generics) {
145         for type_parameter in generics.ty_params.iter() {
146             self.operation.visit_id(type_parameter.id)
147         }
148         for lifetime in &generics.lifetimes {
149             self.operation.visit_id(lifetime.lifetime.id)
150         }
151     }
152 }
153
154 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
155     fn visit_mod(&mut self,
156                  module: &Mod,
157                  _: Span,
158                  node_id: NodeId) {
159         self.operation.visit_id(node_id);
160         visit::walk_mod(self, module)
161     }
162
163     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
164         self.operation.visit_id(foreign_item.id);
165         visit::walk_foreign_item(self, foreign_item)
166     }
167
168     fn visit_item(&mut self, item: &Item) {
169         if self.visited_outermost {
170             return
171         } else {
172             self.visited_outermost = true
173         }
174
175         self.operation.visit_id(item.id);
176         match item.node {
177             ItemUse(ref view_path) => {
178                 match view_path.node {
179                     ViewPathSimple(_, _) |
180                     ViewPathGlob(_) => {}
181                     ViewPathList(_, ref paths) => {
182                         for path in paths {
183                             self.operation.visit_id(path.node.id())
184                         }
185                     }
186                 }
187             }
188             _ => {}
189         }
190
191         visit::walk_item(self, item);
192
193         self.visited_outermost = false
194     }
195
196     fn visit_local(&mut self, local: &Local) {
197         self.operation.visit_id(local.id);
198         visit::walk_local(self, local)
199     }
200
201     fn visit_block(&mut self, block: &Block) {
202         self.operation.visit_id(block.id);
203         visit::walk_block(self, block)
204     }
205
206     fn visit_stmt(&mut self, statement: &Stmt) {
207         self.operation
208             .visit_id(statement.node.id().expect("attempted to visit unexpanded stmt"));
209         visit::walk_stmt(self, statement)
210     }
211
212     fn visit_pat(&mut self, pattern: &Pat) {
213         self.operation.visit_id(pattern.id);
214         visit::walk_pat(self, pattern)
215     }
216
217     fn visit_expr(&mut self, expression: &Expr) {
218         self.operation.visit_id(expression.id);
219         visit::walk_expr(self, expression)
220     }
221
222     fn visit_ty(&mut self, typ: &Ty) {
223         self.operation.visit_id(typ.id);
224         visit::walk_ty(self, typ)
225     }
226
227     fn visit_generics(&mut self, generics: &Generics) {
228         self.visit_generics_helper(generics);
229         visit::walk_generics(self, generics)
230     }
231
232     fn visit_fn(&mut self,
233                 function_kind: visit::FnKind<'v>,
234                 function_declaration: &'v FnDecl,
235                 block: &'v Block,
236                 span: Span,
237                 node_id: NodeId) {
238         match function_kind {
239             FnKind::Method(..) if self.visited_outermost => return,
240             FnKind::Method(..) => self.visited_outermost = true,
241             _ => {}
242         }
243
244         self.operation.visit_id(node_id);
245
246         match function_kind {
247             FnKind::ItemFn(_, generics, _, _, _, _) => {
248                 self.visit_generics_helper(generics)
249             }
250             FnKind::Method(_, sig, _) => {
251                 self.visit_generics_helper(&sig.generics)
252             }
253             FnKind::Closure => {}
254         }
255
256         for argument in &function_declaration.inputs {
257             self.operation.visit_id(argument.id)
258         }
259
260         visit::walk_fn(self,
261                        function_kind,
262                        function_declaration,
263                        block,
264                        span);
265
266         if let FnKind::Method(..) = function_kind {
267             self.visited_outermost = false;
268         }
269     }
270
271     fn visit_struct_field(&mut self, struct_field: &StructField) {
272         self.operation.visit_id(struct_field.node.id);
273         visit::walk_struct_field(self, struct_field)
274     }
275
276     fn visit_variant_data(&mut self,
277                         struct_def: &VariantData,
278                         _: ast::Ident,
279                         _: &ast::Generics,
280                         _: NodeId,
281                         _: Span) {
282         self.operation.visit_id(struct_def.id());
283         visit::walk_struct_def(self, struct_def);
284     }
285
286     fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
287         self.operation.visit_id(ti.id);
288         visit::walk_trait_item(self, ti);
289     }
290
291     fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
292         self.operation.visit_id(ii.id);
293         visit::walk_impl_item(self, ii);
294     }
295
296     fn visit_lifetime(&mut self, lifetime: &Lifetime) {
297         self.operation.visit_id(lifetime.id);
298     }
299
300     fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
301         self.visit_lifetime(&def.lifetime);
302     }
303
304     fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
305         self.operation.visit_id(trait_ref.ref_id);
306         visit::walk_trait_ref(self, trait_ref);
307     }
308 }
309
310 pub struct IdRangeComputingVisitor {
311     pub result: IdRange,
312 }
313
314 impl IdRangeComputingVisitor {
315     pub fn new() -> IdRangeComputingVisitor {
316         IdRangeComputingVisitor { result: IdRange::max() }
317     }
318
319     pub fn result(&self) -> IdRange {
320         self.result
321     }
322 }
323
324 impl IdVisitingOperation for IdRangeComputingVisitor {
325     fn visit_id(&mut self, id: NodeId) {
326         self.result.add(id);
327     }
328 }
329
330 /// Computes the id range for a single fn body, ignoring nested items.
331 pub fn compute_id_range_for_fn_body(fk: FnKind,
332                                     decl: &FnDecl,
333                                     body: &Block,
334                                     sp: Span,
335                                     id: NodeId)
336                                     -> IdRange
337 {
338     let mut visitor = IdRangeComputingVisitor::new();
339     let mut id_visitor = IdVisitor {
340         operation: &mut visitor,
341         visited_outermost: false,
342     };
343     id_visitor.visit_fn(fk, decl, body, sp, id);
344     id_visitor.operation.result
345 }
346
347 /// Returns true if the given pattern consists solely of an identifier
348 /// and false otherwise.
349 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
350     match pat.node {
351         ast::PatIdent(..) => true,
352         _ => false,
353     }
354 }
355
356 // are two paths equal when compared unhygienically?
357 // since I'm using this to replace ==, it seems appropriate
358 // to compare the span, global, etc. fields as well.
359 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
360     (a.span == b.span)
361     && (a.global == b.global)
362     && (segments_name_eq(&a.segments[..], &b.segments[..]))
363 }
364
365 // are two arrays of segments equal when compared unhygienically?
366 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
367     a.len() == b.len() &&
368     a.iter().zip(b).all(|(s, t)| {
369         s.identifier.name == t.identifier.name &&
370         // FIXME #7743: ident -> name problems in lifetime comparison?
371         // can types contain idents?
372         s.parameters == t.parameters
373     })
374 }
375
376 #[cfg(test)]
377 mod tests {
378     use ast::*;
379     use super::*;
380
381     fn ident_to_segment(id: Ident) -> PathSegment {
382         PathSegment {identifier: id,
383                      parameters: PathParameters::none()}
384     }
385
386     #[test] fn idents_name_eq_test() {
387         assert!(segments_name_eq(
388             &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
389                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
390             &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(78),SyntaxContext(182))]
391                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));
392         assert!(!segments_name_eq(
393             &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
394                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
395             &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(77),SyntaxContext(182))]
396                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));
397     }
398 }