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.
17 use owned_slice::OwnedSlice;
27 pub fn path_name_i(idents: &[Ident]) -> String {
28 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
29 idents.iter().map(|i| {
30 token::get_ident(*i).get().to_string()
31 }).collect::<Vec<String>>().connect("::")
34 pub fn local_def(id: NodeId) -> DefId {
35 ast::DefId { krate: LOCAL_CRATE, node: id }
38 pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
40 pub fn stmt_id(s: &Stmt) -> NodeId {
42 StmtDecl(_, id) => id,
43 StmtExpr(_, id) => id,
44 StmtSemi(_, id) => id,
45 StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
49 pub fn binop_to_string(op: BinOp) -> &'static str {
72 pub fn lazy_binop(b: BinOp) -> bool {
80 pub fn is_shift_binop(b: BinOp) -> bool {
88 /// Returns `true` if the binary operator takes its arguments by value
89 pub fn is_by_value_binop(b: BinOp) -> bool {
91 BiAdd | BiSub | BiMul | BiDiv | BiRem | BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => {
98 /// Returns `true` if the unary operator takes its argument by value
99 pub fn is_by_value_unop(u: UnOp) -> bool {
101 UnNeg | UnNot => true,
106 pub fn unop_to_string(op: UnOp) -> &'static str {
115 pub fn is_path(e: P<Expr>) -> bool {
116 return match e.node { ExprPath(_) => true, _ => false };
119 /// Get a string representation of a signed int type, with its value.
120 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
121 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
123 TyI if val.is_some() => "i",
132 // cast to a u64 so we can correctly print INT64_MIN. All integral types
133 // are parsed as u64, so we wouldn't want to print an extra negative
135 Some(n) => format!("{}{}", n as u64, s),
136 None => s.to_string()
140 pub fn int_ty_max(t: IntTy) -> u64 {
144 TyI | TyI32 => 0x80000000u64, // actually ni about TyI
145 TyI64 => 0x8000000000000000u64
149 /// Get a string representation of an unsigned int type, with its value.
150 /// We want to avoid "42uint" in favor of "42u"
151 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
153 TyU if val.is_some() => "u",
162 Some(n) => format!("{}{}", n, s),
163 None => s.to_string()
167 pub fn uint_ty_max(t: UintTy) -> u64 {
171 TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
172 TyU64 => 0xffffffffffffffffu64
176 pub fn float_ty_to_string(t: FloatTy) -> String {
178 TyF32 => "f32".to_string(),
179 TyF64 => "f64".to_string(),
183 // convert a span and an identifier to the corresponding
185 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
191 identifier: identifier,
192 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
193 lifetimes: Vec::new(),
194 types: OwnedSlice::empty(),
195 bindings: OwnedSlice::empty(),
202 // If path is a single segment ident path, return that ident. Otherwise, return
204 pub fn path_to_ident(path: &Path) -> Option<Ident> {
205 if path.segments.len() != 1 {
209 let segment = &path.segments[0];
210 if !segment.parameters.is_empty() {
214 Some(segment.identifier)
217 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
220 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
225 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
226 Lifetime { id: DUMMY_NODE_ID,
227 span: codemap::DUMMY_SP,
231 /// Generate a "pretty" name for an `impl` from its type and trait.
232 /// This is designed so that symbols of `impl`'d methods give some
233 /// hint of where they came from, (previously they would all just be
234 /// listed as `__extensions__::method_name::hash`, with no indication
236 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
237 let mut pretty = pprust::ty_to_string(ty);
239 Some(ref trait_ref) => {
241 pretty.push_str(pprust::path_to_string(&trait_ref.path)[]);
245 token::gensym_ident(pretty[])
248 pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod {
260 attrs: method.attrs.clone(),
262 decl: (*decl).clone(),
263 generics: generics.clone(),
264 explicit_self: (*explicit_self).clone(),
271 MethMac(_) => panic!("expected non-macro method declaration")
275 /// extract a TypeMethod from a TraitItem. if the TraitItem is
276 /// a default, pull out the useful fields to make a TypeMethod
278 // NB: to be used only after expansion is complete, and macros are gone.
279 pub fn trait_item_to_ty_method(method: &TraitItem) -> TypeMethod {
281 RequiredMethod(ref m) => (*m).clone(),
282 ProvidedMethod(ref m) => trait_method_to_ty_method(&**m),
283 TypeTraitItem(_) => {
284 panic!("trait_method_to_ty_method(): expected method but found \
290 pub fn split_trait_methods(trait_methods: &[TraitItem])
291 -> (Vec<TypeMethod>, Vec<P<Method>> ) {
292 let mut reqd = Vec::new();
293 let mut provd = Vec::new();
294 for trt_method in trait_methods.iter() {
296 RequiredMethod(ref tm) => reqd.push((*tm).clone()),
297 ProvidedMethod(ref m) => provd.push((*m).clone()),
298 TypeTraitItem(_) => {}
304 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
305 match field.node.kind {
306 ast::NamedField(_, v) | ast::UnnamedField(v) => v
310 /// Maps a binary operator to its precedence
311 pub fn operator_prec(op: ast::BinOp) -> uint {
313 // 'as' sits here with 12
314 BiMul | BiDiv | BiRem => 11u,
315 BiAdd | BiSub => 10u,
320 BiLt | BiLe | BiGe | BiGt => 4u,
327 /// Precedence of the `as` operator, which is a binary operator
328 /// not appearing in the prior table.
329 #[allow(non_upper_case_globals)]
330 pub static as_prec: uint = 12u;
332 pub fn empty_generics() -> Generics {
334 lifetimes: Vec::new(),
335 ty_params: OwnedSlice::empty(),
336 where_clause: WhereClause {
338 predicates: Vec::new(),
343 // ______________________________________________________________________
344 // Enumerating the IDs which appear in an AST
346 #[derive(RustcEncodable, RustcDecodable, Show, Copy)]
353 pub fn max() -> IdRange {
360 pub fn empty(&self) -> bool {
364 pub fn add(&mut self, id: NodeId) {
365 self.min = cmp::min(self.min, id);
366 self.max = cmp::max(self.max, id + 1);
370 pub trait IdVisitingOperation {
371 fn visit_id(&mut self, node_id: NodeId);
374 /// A visitor that applies its operation to all of the node IDs
375 /// in a visitable thing.
377 pub struct IdVisitor<'a, O:'a> {
378 pub operation: &'a mut O,
379 pub pass_through_items: bool,
380 pub visited_outermost: bool,
383 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
384 fn visit_generics_helper(&mut self, generics: &Generics) {
385 for type_parameter in generics.ty_params.iter() {
386 self.operation.visit_id(type_parameter.id)
388 for lifetime in generics.lifetimes.iter() {
389 self.operation.visit_id(lifetime.lifetime.id)
394 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
395 fn visit_mod(&mut self,
399 self.operation.visit_id(node_id);
400 visit::walk_mod(self, module)
403 fn visit_view_item(&mut self, view_item: &ViewItem) {
404 if !self.pass_through_items {
405 if self.visited_outermost {
408 self.visited_outermost = true;
411 match view_item.node {
412 ViewItemExternCrate(_, _, node_id) => {
413 self.operation.visit_id(node_id)
415 ViewItemUse(ref view_path) => {
416 match view_path.node {
417 ViewPathSimple(_, _, node_id) |
418 ViewPathGlob(_, node_id) => {
419 self.operation.visit_id(node_id)
421 ViewPathList(_, ref paths, node_id) => {
422 self.operation.visit_id(node_id);
423 for path in paths.iter() {
424 self.operation.visit_id(path.node.id())
430 visit::walk_view_item(self, view_item);
431 self.visited_outermost = false;
434 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
435 self.operation.visit_id(foreign_item.id);
436 visit::walk_foreign_item(self, foreign_item)
439 fn visit_item(&mut self, item: &Item) {
440 if !self.pass_through_items {
441 if self.visited_outermost {
444 self.visited_outermost = true
448 self.operation.visit_id(item.id);
449 if let ItemEnum(ref enum_definition, _) = item.node {
450 for variant in enum_definition.variants.iter() {
451 self.operation.visit_id(variant.node.id)
455 visit::walk_item(self, item);
457 self.visited_outermost = false
460 fn visit_local(&mut self, local: &Local) {
461 self.operation.visit_id(local.id);
462 visit::walk_local(self, local)
465 fn visit_block(&mut self, block: &Block) {
466 self.operation.visit_id(block.id);
467 visit::walk_block(self, block)
470 fn visit_stmt(&mut self, statement: &Stmt) {
471 self.operation.visit_id(ast_util::stmt_id(statement));
472 visit::walk_stmt(self, statement)
475 fn visit_pat(&mut self, pattern: &Pat) {
476 self.operation.visit_id(pattern.id);
477 visit::walk_pat(self, pattern)
480 fn visit_expr(&mut self, expression: &Expr) {
481 self.operation.visit_id(expression.id);
482 visit::walk_expr(self, expression)
485 fn visit_ty(&mut self, typ: &Ty) {
486 self.operation.visit_id(typ.id);
487 if let TyPath(_, id) = typ.node {
488 self.operation.visit_id(id);
490 visit::walk_ty(self, typ)
493 fn visit_generics(&mut self, generics: &Generics) {
494 self.visit_generics_helper(generics);
495 visit::walk_generics(self, generics)
498 fn visit_fn(&mut self,
499 function_kind: visit::FnKind<'v>,
500 function_declaration: &'v FnDecl,
504 if !self.pass_through_items {
505 match function_kind {
506 visit::FkMethod(..) if self.visited_outermost => return,
507 visit::FkMethod(..) => self.visited_outermost = true,
512 self.operation.visit_id(node_id);
514 match function_kind {
515 visit::FkItemFn(_, generics, _, _) |
516 visit::FkMethod(_, generics, _) => {
517 self.visit_generics_helper(generics)
519 visit::FkFnBlock => {}
522 for argument in function_declaration.inputs.iter() {
523 self.operation.visit_id(argument.id)
528 function_declaration,
532 if !self.pass_through_items {
533 if let visit::FkMethod(..) = function_kind {
534 self.visited_outermost = false;
539 fn visit_struct_field(&mut self, struct_field: &StructField) {
540 self.operation.visit_id(struct_field.node.id);
541 visit::walk_struct_field(self, struct_field)
544 fn visit_struct_def(&mut self,
545 struct_def: &StructDef,
549 self.operation.visit_id(id);
550 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
551 visit::walk_struct_def(self, struct_def);
554 fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
556 ast::RequiredMethod(ref m) => self.operation.visit_id(m.id),
557 ast::ProvidedMethod(ref m) => self.operation.visit_id(m.id),
558 ast::TypeTraitItem(ref typ) => self.operation.visit_id(typ.ty_param.id),
560 visit::walk_trait_item(self, tm);
563 fn visit_lifetime_ref(&mut self, lifetime: &'v Lifetime) {
564 self.operation.visit_id(lifetime.id);
567 fn visit_lifetime_def(&mut self, def: &'v LifetimeDef) {
568 self.visit_lifetime_ref(&def.lifetime);
572 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
574 let mut id_visitor = IdVisitor {
575 operation: operation,
576 pass_through_items: true,
577 visited_outermost: false,
580 visit::walk_inlined_item(&mut id_visitor, item);
583 struct IdRangeComputingVisitor {
587 impl IdVisitingOperation for IdRangeComputingVisitor {
588 fn visit_id(&mut self, id: NodeId) {
593 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
594 let mut visitor = IdRangeComputingVisitor {
595 result: IdRange::max()
597 visit_ids_for_inlined_item(item, &mut visitor);
601 /// Computes the id range for a single fn body, ignoring nested items.
602 pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
609 let mut visitor = IdRangeComputingVisitor {
610 result: IdRange::max()
612 let mut id_visitor = IdVisitor {
613 operation: &mut visitor,
614 pass_through_items: false,
615 visited_outermost: false,
617 id_visitor.visit_fn(fk, decl, body, sp, id);
618 id_visitor.operation.result
621 pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
622 // FIXME(#19596) this is a workaround, but there should be a better way
623 fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
629 PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
630 PatStruct(_, ref fields, _) => {
631 fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
633 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
634 s.iter().all(|p| walk_pat_(&**p, it))
636 PatBox(ref s) | PatRegion(ref s) => {
639 PatVec(ref before, ref slice, ref after) => {
640 before.iter().all(|p| walk_pat_(&**p, it)) &&
641 slice.iter().all(|p| walk_pat_(&**p, it)) &&
642 after.iter().all(|p| walk_pat_(&**p, it))
644 PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
645 PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
652 walk_pat_(pat, &mut it)
655 pub trait EachViewItem {
656 fn each_view_item<F>(&self, f: F) -> bool where F: FnMut(&ast::ViewItem) -> bool;
659 struct EachViewItemData<F> where F: FnMut(&ast::ViewItem) -> bool {
663 impl<'v, F> Visitor<'v> for EachViewItemData<F> where F: FnMut(&ast::ViewItem) -> bool {
664 fn visit_view_item(&mut self, view_item: &ast::ViewItem) {
665 let _ = (self.callback)(view_item);
669 impl EachViewItem for ast::Crate {
670 fn each_view_item<F>(&self, f: F) -> bool where F: FnMut(&ast::ViewItem) -> bool {
671 let mut visit = EachViewItemData {
674 visit::walk_crate(&mut visit, self);
679 pub fn view_path_id(p: &ViewPath) -> NodeId {
681 ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
682 | ViewPathList(_, _, id) => id
686 /// Returns true if the given struct def is tuple-like; i.e. that its fields
688 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
689 struct_def.ctor_id.is_some()
692 /// Returns true if the given pattern consists solely of an identifier
693 /// and false otherwise.
694 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
696 ast::PatIdent(..) => true,
701 // are two paths equal when compared unhygienically?
702 // since I'm using this to replace ==, it seems appropriate
703 // to compare the span, global, etc. fields as well.
704 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
706 && (a.global == b.global)
707 && (segments_name_eq(a.segments[], b.segments[]))
710 // are two arrays of segments equal when compared unhygienically?
711 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
712 if a.len() != b.len() {
715 for (idx,seg) in a.iter().enumerate() {
716 if seg.identifier.name != b[idx].identifier.name
717 // FIXME #7743: ident -> name problems in lifetime comparison?
718 // can types contain idents?
719 || seg.parameters != b[idx].parameters
728 /// Returns true if this literal is a string and false otherwise.
729 pub fn lit_is_str(lit: &Lit) -> bool {
736 /// Macro invocations are guaranteed not to occur after expansion is complete.
737 /// Extracting fields of a method requires a dynamic check to make sure that it's
738 /// not a macro invocation. This check is guaranteed to succeed, assuming
739 /// that the invocations are indeed gone.
740 pub trait PostExpansionMethod {
741 fn pe_ident(&self) -> ast::Ident;
742 fn pe_generics<'a>(&'a self) -> &'a ast::Generics;
743 fn pe_abi(&self) -> Abi;
744 fn pe_explicit_self<'a>(&'a self) -> &'a ast::ExplicitSelf;
745 fn pe_unsafety(&self) -> ast::Unsafety;
746 fn pe_fn_decl<'a>(&'a self) -> &'a ast::FnDecl;
747 fn pe_body<'a>(&'a self) -> &'a ast::Block;
748 fn pe_vis(&self) -> ast::Visibility;
751 macro_rules! mf_method{
752 ($meth_name:ident, $field_ty:ty, $field_pat:pat, $result:expr) => {
753 fn $meth_name<'a>(&'a self) -> $field_ty {
755 $field_pat => $result,
757 panic!("expected an AST without macro invocations");
765 impl PostExpansionMethod for Method {
766 mf_method! { pe_ident,ast::Ident,MethDecl(ident,_,_,_,_,_,_,_),ident }
768 pe_generics,&'a ast::Generics,
769 MethDecl(_,ref generics,_,_,_,_,_,_),generics
771 mf_method! { pe_abi,Abi,MethDecl(_,_,abi,_,_,_,_,_),abi }
773 pe_explicit_self,&'a ast::ExplicitSelf,
774 MethDecl(_,_,_,ref explicit_self,_,_,_,_),explicit_self
776 mf_method! { pe_unsafety,ast::Unsafety,MethDecl(_,_,_,_,unsafety,_,_,_),unsafety }
777 mf_method! { pe_fn_decl,&'a ast::FnDecl,MethDecl(_,_,_,_,_,ref decl,_,_),&**decl }
778 mf_method! { pe_body,&'a ast::Block,MethDecl(_,_,_,_,_,_,ref body,_),&**body }
779 mf_method! { pe_vis,ast::Visibility,MethDecl(_,_,_,_,_,_,_,vis),vis }
787 fn ident_to_segment(id : &Ident) -> PathSegment {
788 PathSegment {identifier: id.clone(),
789 parameters: PathParameters::none()}
792 #[test] fn idents_name_eq_test() {
793 assert!(segments_name_eq(
794 [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
795 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
796 [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
797 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));
798 assert!(!segments_name_eq(
799 [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
800 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
801 [Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
802 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));