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.
16 use owned_slice::OwnedSlice;
24 use std::strbuf::StrBuf;
27 pub fn path_name_i(idents: &[Ident]) -> ~str {
28 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
29 idents.iter().map(|i| {
30 token::get_ident(*i).get().to_str()
31 }).collect::<Vec<~str>>().connect("::")
34 // totally scary function: ignores all but the last element, should have
36 pub fn path_to_ident(path: &Path) -> Ident {
37 path.segments.last().unwrap().identifier
40 pub fn local_def(id: NodeId) -> DefId {
41 ast::DefId { krate: LOCAL_CRATE, node: id }
44 pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
46 pub fn stmt_id(s: &Stmt) -> NodeId {
48 StmtDecl(_, id) => id,
49 StmtExpr(_, id) => id,
50 StmtSemi(_, id) => id,
51 StmtMac(..) => fail!("attempted to analyze unexpanded stmt")
55 pub fn variant_def_ids(d: Def) -> Option<(DefId, DefId)> {
57 DefVariant(enum_id, var_id, _) => {
58 Some((enum_id, var_id))
64 pub fn def_id_of_def(d: Def) -> DefId {
66 DefFn(id, _) | DefStaticMethod(id, _, _) | DefMod(id) |
67 DefForeignMod(id) | DefStatic(id, _) |
68 DefVariant(_, id, _) | DefTy(id) | DefTyParam(id, _) |
69 DefUse(id) | DefStruct(id) | DefTrait(id) | DefMethod(id, _) => {
72 DefArg(id, _) | DefLocal(id, _) | DefSelfTy(id)
73 | DefUpvar(id, _, _, _) | DefBinding(id, _) | DefRegion(id)
74 | DefTyParamBinder(id) | DefLabel(id) => {
78 DefPrimTy(_) => fail!()
82 pub fn binop_to_str(op: BinOp) -> &'static str {
105 pub fn lazy_binop(b: BinOp) -> bool {
113 pub fn is_shift_binop(b: BinOp) -> bool {
121 pub fn unop_to_str(op: UnOp) -> &'static str {
131 pub fn is_path(e: @Expr) -> bool {
132 return match e.node { ExprPath(_) => true, _ => false };
135 // Get a string representation of a signed int type, with its value.
136 // We want to avoid "45int" and "-3int" in favor of "45" and "-3"
137 pub fn int_ty_to_str(t: IntTy, val: Option<i64>) -> ~str {
139 TyI if val.is_some() => "",
148 Some(n) => format!("{}{}", n, s),
153 pub fn int_ty_max(t: IntTy) -> u64 {
157 TyI | TyI32 => 0x80000000u64, // actually ni about TyI
158 TyI64 => 0x8000000000000000u64
162 // Get a string representation of an unsigned int type, with its value.
163 // We want to avoid "42uint" in favor of "42u"
164 pub fn uint_ty_to_str(t: UintTy, val: Option<u64>) -> ~str {
166 TyU if val.is_some() => "u",
175 Some(n) => format!("{}{}", n, s),
180 pub fn uint_ty_max(t: UintTy) -> u64 {
184 TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
185 TyU64 => 0xffffffffffffffffu64
189 pub fn float_ty_to_str(t: FloatTy) -> ~str {
190 match t { TyF32 => "f32".to_owned(), TyF64 => "f64".to_owned(), TyF128 => "f128".to_owned() }
193 pub fn is_call_expr(e: @Expr) -> bool {
194 match e.node { ExprCall(..) => true, _ => false }
197 pub fn block_from_expr(e: @Expr) -> P<Block> {
199 view_items: Vec::new(),
208 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
214 identifier: identifier,
215 lifetimes: Vec::new(),
216 types: OwnedSlice::empty(),
222 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> @Pat {
224 node: PatIdent(BindByValue(MutImmutable), ident_to_path(s, i), None),
228 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
229 Lifetime { id: DUMMY_NODE_ID,
230 span: codemap::DUMMY_SP,
234 pub fn is_unguarded(a: &Arm) -> bool {
241 pub fn unguarded_pat(a: &Arm) -> Option<Vec<@Pat> > {
243 Some(/* FIXME (#2543) */ a.pats.clone())
249 /// Generate a "pretty" name for an `impl` from its type and trait.
250 /// This is designed so that symbols of `impl`'d methods give some
251 /// hint of where they came from, (previously they would all just be
252 /// listed as `__extensions__::method_name::hash`, with no indication
254 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
255 let mut pretty = StrBuf::from_owned_str(pprust::ty_to_str(ty));
257 Some(ref trait_ref) => {
258 pretty.push_char('.');
259 pretty.push_str(pprust::path_to_str(&trait_ref.path));
263 token::gensym_ident(pretty.as_slice())
266 pub fn public_methods(ms: Vec<@Method> ) -> Vec<@Method> {
267 ms.move_iter().filter(|m| {
275 // extract a TypeMethod from a TraitMethod. if the TraitMethod is
276 // a default, pull out the useful fields to make a TypeMethod
277 pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod {
279 Required(ref m) => (*m).clone(),
283 attrs: m.attrs.clone(),
284 fn_style: m.fn_style,
286 generics: m.generics.clone(),
287 explicit_self: m.explicit_self,
295 pub fn split_trait_methods(trait_methods: &[TraitMethod])
296 -> (Vec<TypeMethod> , Vec<@Method> ) {
297 let mut reqd = Vec::new();
298 let mut provd = Vec::new();
299 for trt_method in trait_methods.iter() {
301 Required(ref tm) => reqd.push((*tm).clone()),
302 Provided(m) => provd.push(m)
308 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
309 match field.node.kind {
310 ast::NamedField(_, v) | ast::UnnamedField(v) => v
314 /// Maps a binary operator to its precedence
315 pub fn operator_prec(op: ast::BinOp) -> uint {
317 // 'as' sits here with 12
318 BiMul | BiDiv | BiRem => 11u,
319 BiAdd | BiSub => 10u,
324 BiLt | BiLe | BiGe | BiGt => 4u,
331 /// Precedence of the `as` operator, which is a binary operator
332 /// not appearing in the prior table.
333 pub static as_prec: uint = 12u;
335 pub fn empty_generics() -> Generics {
336 Generics {lifetimes: Vec::new(),
337 ty_params: OwnedSlice::empty()}
340 // ______________________________________________________________________
341 // Enumerating the IDs which appear in an AST
343 #[deriving(Encodable, Decodable)]
350 pub fn max() -> IdRange {
357 pub fn empty(&self) -> bool {
361 pub fn add(&mut self, id: NodeId) {
362 self.min = cmp::min(self.min, id);
363 self.max = cmp::max(self.max, id + 1);
367 pub trait IdVisitingOperation {
368 fn visit_id(&self, node_id: NodeId);
371 pub struct IdVisitor<'a, O> {
372 pub operation: &'a O,
373 pub pass_through_items: bool,
374 pub visited_outermost: bool,
377 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
378 fn visit_generics_helper(&self, generics: &Generics) {
379 for type_parameter in generics.ty_params.iter() {
380 self.operation.visit_id(type_parameter.id)
382 for lifetime in generics.lifetimes.iter() {
383 self.operation.visit_id(lifetime.id)
388 impl<'a, O: IdVisitingOperation> Visitor<()> for IdVisitor<'a, O> {
389 fn visit_mod(&mut self,
394 self.operation.visit_id(node_id);
395 visit::walk_mod(self, module, env)
398 fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
399 if !self.pass_through_items {
400 if self.visited_outermost {
403 self.visited_outermost = true;
406 match view_item.node {
407 ViewItemExternCrate(_, _, node_id) => {
408 self.operation.visit_id(node_id)
410 ViewItemUse(ref view_paths) => {
411 for view_path in view_paths.iter() {
412 match view_path.node {
413 ViewPathSimple(_, _, node_id) |
414 ViewPathGlob(_, node_id) => {
415 self.operation.visit_id(node_id)
417 ViewPathList(_, ref paths, node_id) => {
418 self.operation.visit_id(node_id);
419 for path in paths.iter() {
420 self.operation.visit_id(path.node.id)
427 visit::walk_view_item(self, view_item, env);
428 self.visited_outermost = false;
431 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem, env: ()) {
432 self.operation.visit_id(foreign_item.id);
433 visit::walk_foreign_item(self, foreign_item, env)
436 fn visit_item(&mut self, item: &Item, env: ()) {
437 if !self.pass_through_items {
438 if self.visited_outermost {
441 self.visited_outermost = true
445 self.operation.visit_id(item.id);
447 ItemEnum(ref enum_definition, _) => {
448 for variant in enum_definition.variants.iter() {
449 self.operation.visit_id(variant.node.id)
455 visit::walk_item(self, item, env);
457 self.visited_outermost = false
460 fn visit_local(&mut self, local: &Local, env: ()) {
461 self.operation.visit_id(local.id);
462 visit::walk_local(self, local, env)
465 fn visit_block(&mut self, block: &Block, env: ()) {
466 self.operation.visit_id(block.id);
467 visit::walk_block(self, block, env)
470 fn visit_stmt(&mut self, statement: &Stmt, env: ()) {
471 self.operation.visit_id(ast_util::stmt_id(statement));
472 visit::walk_stmt(self, statement, env)
475 fn visit_pat(&mut self, pattern: &Pat, env: ()) {
476 self.operation.visit_id(pattern.id);
477 visit::walk_pat(self, pattern, env)
481 fn visit_expr(&mut self, expression: &Expr, env: ()) {
482 self.operation.visit_id(expression.id);
483 visit::walk_expr(self, expression, env)
486 fn visit_ty(&mut self, typ: &Ty, env: ()) {
487 self.operation.visit_id(typ.id);
489 TyPath(_, _, id) => self.operation.visit_id(id),
492 visit::walk_ty(self, typ, env)
495 fn visit_generics(&mut self, generics: &Generics, env: ()) {
496 self.visit_generics_helper(generics);
497 visit::walk_generics(self, generics, env)
500 fn visit_fn(&mut self,
501 function_kind: &visit::FnKind,
502 function_declaration: &FnDecl,
507 if !self.pass_through_items {
508 match *function_kind {
509 visit::FkMethod(..) if self.visited_outermost => return,
510 visit::FkMethod(..) => self.visited_outermost = true,
515 self.operation.visit_id(node_id);
517 match *function_kind {
518 visit::FkItemFn(_, generics, _, _) |
519 visit::FkMethod(_, generics, _) => {
520 self.visit_generics_helper(generics)
522 visit::FkFnBlock => {}
525 for argument in function_declaration.inputs.iter() {
526 self.operation.visit_id(argument.id)
531 function_declaration,
537 if !self.pass_through_items {
538 match *function_kind {
539 visit::FkMethod(..) => self.visited_outermost = false,
545 fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
546 self.operation.visit_id(struct_field.node.id);
547 visit::walk_struct_field(self, struct_field, env)
550 fn visit_struct_def(&mut self,
551 struct_def: &StructDef,
553 generics: &ast::Generics,
556 self.operation.visit_id(id);
557 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
558 visit::walk_struct_def(self, struct_def, ident, generics, id, ());
561 fn visit_trait_method(&mut self, tm: &ast::TraitMethod, _: ()) {
563 ast::Required(ref m) => self.operation.visit_id(m.id),
564 ast::Provided(ref m) => self.operation.visit_id(m.id),
566 visit::walk_trait_method(self, tm, ());
570 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
572 let mut id_visitor = IdVisitor {
573 operation: operation,
574 pass_through_items: true,
575 visited_outermost: false,
578 visit::walk_inlined_item(&mut id_visitor, item, ());
581 struct IdRangeComputingVisitor {
582 result: Cell<IdRange>,
585 impl IdVisitingOperation for IdRangeComputingVisitor {
586 fn visit_id(&self, id: NodeId) {
587 let mut id_range = self.result.get();
589 self.result.set(id_range)
593 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
594 let visitor = IdRangeComputingVisitor {
595 result: Cell::new(IdRange::max())
597 visit_ids_for_inlined_item(item, &visitor);
601 pub fn is_item_impl(item: @ast::Item) -> bool {
603 ItemImpl(..) => true,
608 pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
614 PatIdent(_, _, Some(p)) => walk_pat(p, it),
615 PatStruct(_, ref fields, _) => {
616 fields.iter().advance(|f| walk_pat(f.pat, |p| it(p)))
618 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
619 s.iter().advance(|&p| walk_pat(p, |p| it(p)))
621 PatUniq(s) | PatRegion(s) => {
624 PatVec(ref before, ref slice, ref after) => {
625 before.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
626 slice.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
627 after.iter().advance(|&p| walk_pat(p, |p| it(p)))
629 PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
636 pub trait EachViewItem {
637 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool;
640 struct EachViewItemData<'a> {
641 callback: |&ast::ViewItem|: 'a -> bool,
644 impl<'a> Visitor<()> for EachViewItemData<'a> {
645 fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
646 let _ = (self.callback)(view_item);
650 impl EachViewItem for ast::Crate {
651 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
652 let mut visit = EachViewItemData {
655 visit::walk_crate(&mut visit, self, ());
660 pub fn view_path_id(p: &ViewPath) -> NodeId {
662 ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
663 | ViewPathList(_, _, id) => id
667 /// Returns true if the given struct def is tuple-like; i.e. that its fields
669 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
670 struct_def.ctor_id.is_some()
673 /// Returns true if the given pattern consists solely of an identifier
674 /// and false otherwise.
675 pub fn pat_is_ident(pat: @ast::Pat) -> bool {
677 ast::PatIdent(..) => true,
682 // are two paths equal when compared unhygienically?
683 // since I'm using this to replace ==, it seems appropriate
684 // to compare the span, global, etc. fields as well.
685 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
687 && (a.global == b.global)
688 && (segments_name_eq(a.segments.as_slice(), b.segments.as_slice()))
691 // are two arrays of segments equal when compared unhygienically?
692 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
693 if a.len() != b.len() {
696 for (idx,seg) in a.iter().enumerate() {
697 if (seg.identifier.name != b[idx].identifier.name)
698 // FIXME #7743: ident -> name problems in lifetime comparison?
699 || (seg.lifetimes != b[idx].lifetimes)
700 // can types contain idents?
701 || (seg.types != b[idx].types) {
709 // Returns true if this literal is a string and false otherwise.
710 pub fn lit_is_str(lit: @Lit) -> bool {
717 pub fn get_inner_tys(ty: P<Ty>) -> Vec<P<Ty>> {
719 ast::TyRptr(_, mut_ty) | ast::TyPtr(mut_ty) => {
725 | ast::TyFixedLengthVec(ty, _) => vec!(ty),
726 ast::TyTup(ref tys) => tys.clone(),
736 use owned_slice::OwnedSlice;
738 fn ident_to_segment(id : &Ident) -> PathSegment {
739 PathSegment {identifier:id.clone(),
740 lifetimes: Vec::new(),
741 types: OwnedSlice::empty()}
744 #[test] fn idents_name_eq_test() {
745 assert!(segments_name_eq(
746 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
747 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
748 [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}]
749 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
750 assert!(!segments_name_eq(
751 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
752 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
753 [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}]
754 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));