1 // Copyright 2012-2013 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 pub fn int_ty_to_str(t: IntTy) -> ~str {
145 pub fn int_ty_max(t: IntTy) -> u64 {
149 TyI | TyI32 => 0x80000000u64, // actually ni about TyI
150 TyI64 => 0x8000000000000000u64
154 pub fn uint_ty_to_str(t: UintTy) -> ~str {
164 pub fn uint_ty_max(t: UintTy) -> u64 {
168 TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
169 TyU64 => 0xffffffffffffffffu64
173 pub fn float_ty_to_str(t: FloatTy) -> ~str {
174 match t { TyF32 => ~"f32", TyF64 => ~"f64" }
177 pub fn is_call_expr(e: @Expr) -> bool {
178 match e.node { ExprCall(..) => true, _ => false }
181 pub fn block_from_expr(e: @Expr) -> P<Block> {
183 view_items: Vec::new(),
192 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
198 identifier: identifier,
199 lifetimes: Vec::new(),
200 types: OwnedSlice::empty(),
206 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> @Pat {
208 node: PatIdent(BindByValue(MutImmutable), ident_to_path(s, i), None),
212 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
213 Lifetime { id: DUMMY_NODE_ID,
214 span: codemap::DUMMY_SP,
218 pub fn is_unguarded(a: &Arm) -> bool {
225 pub fn unguarded_pat(a: &Arm) -> Option<Vec<@Pat> > {
227 Some(/* FIXME (#2543) */ a.pats.clone())
233 /// Generate a "pretty" name for an `impl` from its type and trait.
234 /// This is designed so that symbols of `impl`'d methods give some
235 /// hint of where they came from, (previously they would all just be
236 /// listed as `__extensions__::method_name::hash`, with no indication
238 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
239 let mut pretty = StrBuf::from_owned_str(pprust::ty_to_str(ty));
241 Some(ref trait_ref) => {
242 pretty.push_char('.');
243 pretty.push_str(pprust::path_to_str(&trait_ref.path));
247 token::gensym_ident(pretty.as_slice())
250 pub fn public_methods(ms: Vec<@Method> ) -> Vec<@Method> {
251 ms.move_iter().filter(|m| {
259 // extract a TypeMethod from a TraitMethod. if the TraitMethod is
260 // a default, pull out the useful fields to make a TypeMethod
261 pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod {
263 Required(ref m) => (*m).clone(),
267 attrs: m.attrs.clone(),
270 generics: m.generics.clone(),
271 explicit_self: m.explicit_self,
279 pub fn split_trait_methods(trait_methods: &[TraitMethod])
280 -> (Vec<TypeMethod> , Vec<@Method> ) {
281 let mut reqd = Vec::new();
282 let mut provd = Vec::new();
283 for trt_method in trait_methods.iter() {
285 Required(ref tm) => reqd.push((*tm).clone()),
286 Provided(m) => provd.push(m)
292 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
293 match field.node.kind {
294 ast::NamedField(_, v) | ast::UnnamedField(v) => v
298 /// Maps a binary operator to its precedence
299 pub fn operator_prec(op: ast::BinOp) -> uint {
301 // 'as' sits here with 12
302 BiMul | BiDiv | BiRem => 11u,
303 BiAdd | BiSub => 10u,
308 BiLt | BiLe | BiGe | BiGt => 4u,
315 /// Precedence of the `as` operator, which is a binary operator
316 /// not appearing in the prior table.
317 pub static as_prec: uint = 12u;
319 pub fn empty_generics() -> Generics {
320 Generics {lifetimes: Vec::new(),
321 ty_params: OwnedSlice::empty()}
324 // ______________________________________________________________________
325 // Enumerating the IDs which appear in an AST
327 #[deriving(Encodable, Decodable)]
334 pub fn max() -> IdRange {
341 pub fn empty(&self) -> bool {
345 pub fn add(&mut self, id: NodeId) {
346 self.min = cmp::min(self.min, id);
347 self.max = cmp::max(self.max, id + 1);
351 pub trait IdVisitingOperation {
352 fn visit_id(&self, node_id: NodeId);
355 pub struct IdVisitor<'a, O> {
356 pub operation: &'a O,
357 pub pass_through_items: bool,
358 pub visited_outermost: bool,
361 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
362 fn visit_generics_helper(&self, generics: &Generics) {
363 for type_parameter in generics.ty_params.iter() {
364 self.operation.visit_id(type_parameter.id)
366 for lifetime in generics.lifetimes.iter() {
367 self.operation.visit_id(lifetime.id)
372 impl<'a, O: IdVisitingOperation> Visitor<()> for IdVisitor<'a, O> {
373 fn visit_mod(&mut self,
378 self.operation.visit_id(node_id);
379 visit::walk_mod(self, module, env)
382 fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
383 match view_item.node {
384 ViewItemExternCrate(_, _, node_id) => {
385 self.operation.visit_id(node_id)
387 ViewItemUse(ref view_paths) => {
388 for view_path in view_paths.iter() {
389 match view_path.node {
390 ViewPathSimple(_, _, node_id) |
391 ViewPathGlob(_, node_id) => {
392 self.operation.visit_id(node_id)
394 ViewPathList(_, ref paths, node_id) => {
395 self.operation.visit_id(node_id);
396 for path in paths.iter() {
397 self.operation.visit_id(path.node.id)
404 visit::walk_view_item(self, view_item, env)
407 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem, env: ()) {
408 self.operation.visit_id(foreign_item.id);
409 visit::walk_foreign_item(self, foreign_item, env)
412 fn visit_item(&mut self, item: &Item, env: ()) {
413 if !self.pass_through_items {
414 if self.visited_outermost {
417 self.visited_outermost = true
421 self.operation.visit_id(item.id);
423 ItemEnum(ref enum_definition, _) => {
424 for variant in enum_definition.variants.iter() {
425 self.operation.visit_id(variant.node.id)
431 visit::walk_item(self, item, env);
433 self.visited_outermost = false
436 fn visit_local(&mut self, local: &Local, env: ()) {
437 self.operation.visit_id(local.id);
438 visit::walk_local(self, local, env)
441 fn visit_block(&mut self, block: &Block, env: ()) {
442 self.operation.visit_id(block.id);
443 visit::walk_block(self, block, env)
446 fn visit_stmt(&mut self, statement: &Stmt, env: ()) {
447 self.operation.visit_id(ast_util::stmt_id(statement));
448 visit::walk_stmt(self, statement, env)
451 fn visit_pat(&mut self, pattern: &Pat, env: ()) {
452 self.operation.visit_id(pattern.id);
453 visit::walk_pat(self, pattern, env)
457 fn visit_expr(&mut self, expression: &Expr, env: ()) {
458 self.operation.visit_id(expression.id);
459 visit::walk_expr(self, expression, env)
462 fn visit_ty(&mut self, typ: &Ty, env: ()) {
463 self.operation.visit_id(typ.id);
465 TyPath(_, _, id) => self.operation.visit_id(id),
468 visit::walk_ty(self, typ, env)
471 fn visit_generics(&mut self, generics: &Generics, env: ()) {
472 self.visit_generics_helper(generics);
473 visit::walk_generics(self, generics, env)
476 fn visit_fn(&mut self,
477 function_kind: &visit::FnKind,
478 function_declaration: &FnDecl,
483 if !self.pass_through_items {
484 match *function_kind {
485 visit::FkMethod(..) if self.visited_outermost => return,
486 visit::FkMethod(..) => self.visited_outermost = true,
491 self.operation.visit_id(node_id);
493 match *function_kind {
494 visit::FkItemFn(_, generics, _, _) |
495 visit::FkMethod(_, generics, _) => {
496 self.visit_generics_helper(generics)
498 visit::FkFnBlock => {}
501 for argument in function_declaration.inputs.iter() {
502 self.operation.visit_id(argument.id)
507 function_declaration,
513 if !self.pass_through_items {
514 match *function_kind {
515 visit::FkMethod(..) => self.visited_outermost = false,
521 fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
522 self.operation.visit_id(struct_field.node.id);
523 visit::walk_struct_field(self, struct_field, env)
526 fn visit_struct_def(&mut self,
527 struct_def: &StructDef,
529 generics: &ast::Generics,
532 self.operation.visit_id(id);
533 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
534 visit::walk_struct_def(self, struct_def, ident, generics, id, ());
537 fn visit_trait_method(&mut self, tm: &ast::TraitMethod, _: ()) {
539 ast::Required(ref m) => self.operation.visit_id(m.id),
540 ast::Provided(ref m) => self.operation.visit_id(m.id),
542 visit::walk_trait_method(self, tm, ());
546 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
548 let mut id_visitor = IdVisitor {
549 operation: operation,
550 pass_through_items: true,
551 visited_outermost: false,
554 visit::walk_inlined_item(&mut id_visitor, item, ());
557 struct IdRangeComputingVisitor {
558 result: Cell<IdRange>,
561 impl IdVisitingOperation for IdRangeComputingVisitor {
562 fn visit_id(&self, id: NodeId) {
563 let mut id_range = self.result.get();
565 self.result.set(id_range)
569 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
570 let visitor = IdRangeComputingVisitor {
571 result: Cell::new(IdRange::max())
573 visit_ids_for_inlined_item(item, &visitor);
577 pub fn is_item_impl(item: @ast::Item) -> bool {
579 ItemImpl(..) => true,
584 pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
590 PatIdent(_, _, Some(p)) => walk_pat(p, it),
591 PatStruct(_, ref fields, _) => {
592 fields.iter().advance(|f| walk_pat(f.pat, |p| it(p)))
594 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
595 s.iter().advance(|&p| walk_pat(p, |p| it(p)))
597 PatUniq(s) | PatRegion(s) => {
600 PatVec(ref before, ref slice, ref after) => {
601 before.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
602 slice.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
603 after.iter().advance(|&p| walk_pat(p, |p| it(p)))
605 PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
612 pub trait EachViewItem {
613 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool;
616 struct EachViewItemData<'a> {
617 callback: |&ast::ViewItem|: 'a -> bool,
620 impl<'a> Visitor<()> for EachViewItemData<'a> {
621 fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
622 let _ = (self.callback)(view_item);
626 impl EachViewItem for ast::Crate {
627 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
628 let mut visit = EachViewItemData {
631 visit::walk_crate(&mut visit, self, ());
636 pub fn view_path_id(p: &ViewPath) -> NodeId {
638 ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
639 | ViewPathList(_, _, id) => id
643 /// Returns true if the given struct def is tuple-like; i.e. that its fields
645 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
646 struct_def.ctor_id.is_some()
649 /// Returns true if the given pattern consists solely of an identifier
650 /// and false otherwise.
651 pub fn pat_is_ident(pat: @ast::Pat) -> bool {
653 ast::PatIdent(..) => true,
658 // are two paths equal when compared unhygienically?
659 // since I'm using this to replace ==, it seems appropriate
660 // to compare the span, global, etc. fields as well.
661 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
663 && (a.global == b.global)
664 && (segments_name_eq(a.segments.as_slice(), b.segments.as_slice()))
667 // are two arrays of segments equal when compared unhygienically?
668 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
669 if a.len() != b.len() {
672 for (idx,seg) in a.iter().enumerate() {
673 if (seg.identifier.name != b[idx].identifier.name)
674 // FIXME #7743: ident -> name problems in lifetime comparison?
675 || (seg.lifetimes != b[idx].lifetimes)
676 // can types contain idents?
677 || (seg.types != b[idx].types) {
685 // Returns true if this literal is a string and false otherwise.
686 pub fn lit_is_str(lit: @Lit) -> bool {
693 pub fn get_inner_tys(ty: P<Ty>) -> Vec<P<Ty>> {
695 ast::TyRptr(_, mut_ty) | ast::TyPtr(mut_ty) => {
701 | ast::TyFixedLengthVec(ty, _) => vec!(ty),
702 ast::TyTup(ref tys) => tys.clone(),
712 use owned_slice::OwnedSlice;
714 fn ident_to_segment(id : &Ident) -> PathSegment {
715 PathSegment {identifier:id.clone(),
716 lifetimes: Vec::new(),
717 types: OwnedSlice::empty()}
720 #[test] fn idents_name_eq_test() {
721 assert!(segments_name_eq(
722 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
723 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
724 [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}]
725 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
726 assert!(!segments_name_eq(
727 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
728 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
729 [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}]
730 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));