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 pub fn is_comparison_binop(b: BinOp_) -> bool {
90 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
95 /// Returns `true` if the binary operator takes its arguments by value
96 pub fn is_by_value_binop(b: BinOp_) -> bool {
98 BiAdd | BiSub | BiMul | BiDiv | BiRem | BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => {
105 /// Returns `true` if the unary operator takes its argument by value
106 pub fn is_by_value_unop(u: UnOp) -> bool {
108 UnNeg | UnNot => true,
113 pub fn unop_to_string(op: UnOp) -> &'static str {
122 pub fn is_path(e: P<Expr>) -> bool {
123 return match e.node { ExprPath(_) => true, _ => false };
126 /// Get a string representation of a signed int type, with its value.
127 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
128 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
130 TyIs(true) if val.is_some() => "i",
132 TyIs(false) if val.is_some() => "is",
133 TyIs(false) => "isize",
141 // cast to a u64 so we can correctly print INT64_MIN. All integral types
142 // are parsed as u64, so we wouldn't want to print an extra negative
144 Some(n) => format!("{}{}", n as u64, s),
145 None => s.to_string()
149 pub fn int_ty_max(t: IntTy) -> u64 {
153 TyIs(_) | TyI32 => 0x80000000u64, // actually ni about TyIs
154 TyI64 => 0x8000000000000000u64
158 /// Get a string representation of an unsigned int type, with its value.
159 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
160 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
162 TyUs(true) if val.is_some() => "u",
163 TyUs(true) => "uint",
164 TyUs(false) if val.is_some() => "us",
165 TyUs(false) => "usize",
173 Some(n) => format!("{}{}", n, s),
174 None => s.to_string()
178 pub fn uint_ty_max(t: UintTy) -> u64 {
182 TyUs(_) | TyU32 => 0xffffffffu64, // actually ni about TyUs
183 TyU64 => 0xffffffffffffffffu64
187 pub fn float_ty_to_string(t: FloatTy) -> String {
189 TyF32 => "f32".to_string(),
190 TyF64 => "f64".to_string(),
194 // convert a span and an identifier to the corresponding
196 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
202 identifier: identifier,
203 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
204 lifetimes: Vec::new(),
205 types: OwnedSlice::empty(),
206 bindings: OwnedSlice::empty(),
213 // If path is a single segment ident path, return that ident. Otherwise, return
215 pub fn path_to_ident(path: &Path) -> Option<Ident> {
216 if path.segments.len() != 1 {
220 let segment = &path.segments[0];
221 if !segment.parameters.is_empty() {
225 Some(segment.identifier)
228 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
231 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
236 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
237 Lifetime { id: DUMMY_NODE_ID,
238 span: codemap::DUMMY_SP,
242 /// Generate a "pretty" name for an `impl` from its type and trait.
243 /// This is designed so that symbols of `impl`'d methods give some
244 /// hint of where they came from, (previously they would all just be
245 /// listed as `__extensions__::method_name::hash`, with no indication
247 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
248 let mut pretty = pprust::ty_to_string(ty);
250 Some(ref trait_ref) => {
252 pretty.push_str(&pprust::path_to_string(&trait_ref.path)[]);
256 token::gensym_ident(&pretty[])
259 pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod {
271 attrs: method.attrs.clone(),
273 decl: (*decl).clone(),
274 generics: generics.clone(),
275 explicit_self: (*explicit_self).clone(),
282 MethMac(_) => panic!("expected non-macro method declaration")
286 /// extract a TypeMethod from a TraitItem. if the TraitItem is
287 /// a default, pull out the useful fields to make a TypeMethod
289 // NB: to be used only after expansion is complete, and macros are gone.
290 pub fn trait_item_to_ty_method(method: &TraitItem) -> TypeMethod {
292 RequiredMethod(ref m) => (*m).clone(),
293 ProvidedMethod(ref m) => trait_method_to_ty_method(&**m),
294 TypeTraitItem(_) => {
295 panic!("trait_method_to_ty_method(): expected method but found \
301 pub fn split_trait_methods(trait_methods: &[TraitItem])
302 -> (Vec<TypeMethod>, Vec<P<Method>> ) {
303 let mut reqd = Vec::new();
304 let mut provd = Vec::new();
305 for trt_method in trait_methods.iter() {
307 RequiredMethod(ref tm) => reqd.push((*tm).clone()),
308 ProvidedMethod(ref m) => provd.push((*m).clone()),
309 TypeTraitItem(_) => {}
315 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
316 match field.node.kind {
317 ast::NamedField(_, v) | ast::UnnamedField(v) => v
321 /// Maps a binary operator to its precedence
322 pub fn operator_prec(op: ast::BinOp_) -> usize {
324 // 'as' sits here with 12
325 BiMul | BiDiv | BiRem => 11us,
326 BiAdd | BiSub => 10us,
327 BiShl | BiShr => 9us,
331 BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3us,
337 /// Precedence of the `as` operator, which is a binary operator
338 /// not appearing in the prior table.
339 pub const AS_PREC: usize = 12us;
341 pub fn empty_generics() -> Generics {
343 lifetimes: Vec::new(),
344 ty_params: OwnedSlice::empty(),
345 where_clause: WhereClause {
347 predicates: Vec::new(),
352 // ______________________________________________________________________
353 // Enumerating the IDs which appear in an AST
355 #[derive(RustcEncodable, RustcDecodable, Show, Copy)]
362 pub fn max() -> IdRange {
369 pub fn empty(&self) -> bool {
373 pub fn add(&mut self, id: NodeId) {
374 self.min = cmp::min(self.min, id);
375 self.max = cmp::max(self.max, id + 1);
379 pub trait IdVisitingOperation {
380 fn visit_id(&mut self, node_id: NodeId);
383 /// A visitor that applies its operation to all of the node IDs
384 /// in a visitable thing.
386 pub struct IdVisitor<'a, O:'a> {
387 pub operation: &'a mut O,
388 pub pass_through_items: bool,
389 pub visited_outermost: bool,
392 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
393 fn visit_generics_helper(&mut self, generics: &Generics) {
394 for type_parameter in generics.ty_params.iter() {
395 self.operation.visit_id(type_parameter.id)
397 for lifetime in generics.lifetimes.iter() {
398 self.operation.visit_id(lifetime.lifetime.id)
403 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
404 fn visit_mod(&mut self,
408 self.operation.visit_id(node_id);
409 visit::walk_mod(self, module)
412 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
413 self.operation.visit_id(foreign_item.id);
414 visit::walk_foreign_item(self, foreign_item)
417 fn visit_item(&mut self, item: &Item) {
418 if !self.pass_through_items {
419 if self.visited_outermost {
422 self.visited_outermost = true
426 self.operation.visit_id(item.id);
428 ItemUse(ref view_path) => {
429 match view_path.node {
430 ViewPathSimple(_, _) |
431 ViewPathGlob(_) => {}
432 ViewPathList(_, ref paths) => {
433 for path in paths.iter() {
434 self.operation.visit_id(path.node.id())
439 ItemEnum(ref enum_definition, _) => {
440 for variant in enum_definition.variants.iter() {
441 self.operation.visit_id(variant.node.id)
447 visit::walk_item(self, item);
449 self.visited_outermost = false
452 fn visit_local(&mut self, local: &Local) {
453 self.operation.visit_id(local.id);
454 visit::walk_local(self, local)
457 fn visit_block(&mut self, block: &Block) {
458 self.operation.visit_id(block.id);
459 visit::walk_block(self, block)
462 fn visit_stmt(&mut self, statement: &Stmt) {
463 self.operation.visit_id(ast_util::stmt_id(statement));
464 visit::walk_stmt(self, statement)
467 fn visit_pat(&mut self, pattern: &Pat) {
468 self.operation.visit_id(pattern.id);
469 visit::walk_pat(self, pattern)
472 fn visit_expr(&mut self, expression: &Expr) {
473 self.operation.visit_id(expression.id);
474 visit::walk_expr(self, expression)
477 fn visit_ty(&mut self, typ: &Ty) {
478 self.operation.visit_id(typ.id);
479 if let TyPath(_, id) = typ.node {
480 self.operation.visit_id(id);
482 visit::walk_ty(self, typ)
485 fn visit_generics(&mut self, generics: &Generics) {
486 self.visit_generics_helper(generics);
487 visit::walk_generics(self, generics)
490 fn visit_fn(&mut self,
491 function_kind: visit::FnKind<'v>,
492 function_declaration: &'v FnDecl,
496 if !self.pass_through_items {
497 match function_kind {
498 visit::FkMethod(..) if self.visited_outermost => return,
499 visit::FkMethod(..) => self.visited_outermost = true,
504 self.operation.visit_id(node_id);
506 match function_kind {
507 visit::FkItemFn(_, generics, _, _) |
508 visit::FkMethod(_, generics, _) => {
509 self.visit_generics_helper(generics)
511 visit::FkFnBlock => {}
514 for argument in function_declaration.inputs.iter() {
515 self.operation.visit_id(argument.id)
520 function_declaration,
524 if !self.pass_through_items {
525 if let visit::FkMethod(..) = function_kind {
526 self.visited_outermost = false;
531 fn visit_struct_field(&mut self, struct_field: &StructField) {
532 self.operation.visit_id(struct_field.node.id);
533 visit::walk_struct_field(self, struct_field)
536 fn visit_struct_def(&mut self,
537 struct_def: &StructDef,
541 self.operation.visit_id(id);
542 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
543 visit::walk_struct_def(self, struct_def);
546 fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
548 ast::RequiredMethod(ref m) => self.operation.visit_id(m.id),
549 ast::ProvidedMethod(ref m) => self.operation.visit_id(m.id),
550 ast::TypeTraitItem(ref typ) => self.operation.visit_id(typ.ty_param.id),
552 visit::walk_trait_item(self, tm);
555 fn visit_lifetime_ref(&mut self, lifetime: &'v Lifetime) {
556 self.operation.visit_id(lifetime.id);
559 fn visit_lifetime_def(&mut self, def: &'v LifetimeDef) {
560 self.visit_lifetime_ref(&def.lifetime);
564 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
566 let mut id_visitor = IdVisitor {
567 operation: operation,
568 pass_through_items: true,
569 visited_outermost: false,
572 visit::walk_inlined_item(&mut id_visitor, item);
575 struct IdRangeComputingVisitor {
579 impl IdVisitingOperation for IdRangeComputingVisitor {
580 fn visit_id(&mut self, id: NodeId) {
585 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
586 let mut visitor = IdRangeComputingVisitor {
587 result: IdRange::max()
589 visit_ids_for_inlined_item(item, &mut visitor);
593 /// Computes the id range for a single fn body, ignoring nested items.
594 pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
601 let mut visitor = IdRangeComputingVisitor {
602 result: IdRange::max()
604 let mut id_visitor = IdVisitor {
605 operation: &mut visitor,
606 pass_through_items: false,
607 visited_outermost: false,
609 id_visitor.visit_fn(fk, decl, body, sp, id);
610 id_visitor.operation.result
613 pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
614 // FIXME(#19596) this is a workaround, but there should be a better way
615 fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
621 PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
622 PatStruct(_, ref fields, _) => {
623 fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
625 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
626 s.iter().all(|p| walk_pat_(&**p, it))
628 PatBox(ref s) | PatRegion(ref s, _) => {
631 PatVec(ref before, ref slice, ref after) => {
632 before.iter().all(|p| walk_pat_(&**p, it)) &&
633 slice.iter().all(|p| walk_pat_(&**p, it)) &&
634 after.iter().all(|p| walk_pat_(&**p, it))
636 PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
637 PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
644 walk_pat_(pat, &mut it)
647 /// Returns true if the given struct def is tuple-like; i.e. that its fields
649 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
650 struct_def.ctor_id.is_some()
653 /// Returns true if the given pattern consists solely of an identifier
654 /// and false otherwise.
655 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
657 ast::PatIdent(..) => true,
662 // are two paths equal when compared unhygienically?
663 // since I'm using this to replace ==, it seems appropriate
664 // to compare the span, global, etc. fields as well.
665 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
667 && (a.global == b.global)
668 && (segments_name_eq(&a.segments[], &b.segments[]))
671 // are two arrays of segments equal when compared unhygienically?
672 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
673 if a.len() != b.len() {
676 for (idx,seg) in a.iter().enumerate() {
677 if seg.identifier.name != b[idx].identifier.name
678 // FIXME #7743: ident -> name problems in lifetime comparison?
679 // can types contain idents?
680 || seg.parameters != b[idx].parameters
689 /// Returns true if this literal is a string and false otherwise.
690 pub fn lit_is_str(lit: &Lit) -> bool {
697 /// Macro invocations are guaranteed not to occur after expansion is complete.
698 /// Extracting fields of a method requires a dynamic check to make sure that it's
699 /// not a macro invocation. This check is guaranteed to succeed, assuming
700 /// that the invocations are indeed gone.
701 pub trait PostExpansionMethod {
702 fn pe_ident(&self) -> ast::Ident;
703 fn pe_generics<'a>(&'a self) -> &'a ast::Generics;
704 fn pe_abi(&self) -> Abi;
705 fn pe_explicit_self<'a>(&'a self) -> &'a ast::ExplicitSelf;
706 fn pe_unsafety(&self) -> ast::Unsafety;
707 fn pe_fn_decl<'a>(&'a self) -> &'a ast::FnDecl;
708 fn pe_body<'a>(&'a self) -> &'a ast::Block;
709 fn pe_vis(&self) -> ast::Visibility;
712 macro_rules! mf_method{
713 ($meth_name:ident, $field_ty:ty, $field_pat:pat, $result:expr) => {
714 fn $meth_name<'a>(&'a self) -> $field_ty {
716 $field_pat => $result,
718 panic!("expected an AST without macro invocations");
726 impl PostExpansionMethod for Method {
727 mf_method! { pe_ident,ast::Ident,MethDecl(ident,_,_,_,_,_,_,_),ident }
729 pe_generics,&'a ast::Generics,
730 MethDecl(_,ref generics,_,_,_,_,_,_),generics
732 mf_method! { pe_abi,Abi,MethDecl(_,_,abi,_,_,_,_,_),abi }
734 pe_explicit_self,&'a ast::ExplicitSelf,
735 MethDecl(_,_,_,ref explicit_self,_,_,_,_),explicit_self
737 mf_method! { pe_unsafety,ast::Unsafety,MethDecl(_,_,_,_,unsafety,_,_,_),unsafety }
738 mf_method! { pe_fn_decl,&'a ast::FnDecl,MethDecl(_,_,_,_,_,ref decl,_,_),&**decl }
739 mf_method! { pe_body,&'a ast::Block,MethDecl(_,_,_,_,_,_,ref body,_),&**body }
740 mf_method! { pe_vis,ast::Visibility,MethDecl(_,_,_,_,_,_,_,vis),vis }
748 fn ident_to_segment(id : &Ident) -> PathSegment {
749 PathSegment {identifier: id.clone(),
750 parameters: PathParameters::none()}
753 #[test] fn idents_name_eq_test() {
754 assert!(segments_name_eq(
755 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
756 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
757 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
758 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));
759 assert!(!segments_name_eq(
760 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
761 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
762 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
763 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));