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]) -> StrBuf {
28 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
29 idents.iter().map(|i| {
30 token::get_ident(*i).get().to_strbuf()
31 }).collect::<Vec<StrBuf>>().connect("::").to_strbuf()
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 enum SuffixMode {
140 // Get a string representation of a signed int type, with its value.
141 // We want to avoid "45int" and "-3int" in favor of "45" and "-3"
142 pub fn int_ty_to_str(t: IntTy, val: Option<i64>, mode: SuffixMode) -> StrBuf {
144 TyI if val.is_some() => match mode {
156 // cast to a u64 so we can correctly print INT64_MIN. All integral types
157 // are parsed as u64, so we wouldn't want to print an extra negative
159 Some(n) => format!("{}{}", n as u64, s).to_strbuf(),
160 None => s.to_strbuf()
164 pub fn int_ty_max(t: IntTy) -> u64 {
168 TyI | TyI32 => 0x80000000u64, // actually ni about TyI
169 TyI64 => 0x8000000000000000u64
173 // Get a string representation of an unsigned int type, with its value.
174 // We want to avoid "42uint" in favor of "42u"
175 pub fn uint_ty_to_str(t: UintTy, val: Option<u64>, mode: SuffixMode) -> StrBuf {
177 TyU if val.is_some() => match mode {
189 Some(n) => format!("{}{}", n, s).to_strbuf(),
190 None => s.to_strbuf()
194 pub fn uint_ty_max(t: UintTy) -> u64 {
198 TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
199 TyU64 => 0xffffffffffffffffu64
203 pub fn float_ty_to_str(t: FloatTy) -> StrBuf {
205 TyF32 => "f32".to_strbuf(),
206 TyF64 => "f64".to_strbuf(),
207 TyF128 => "f128".to_strbuf(),
211 pub fn is_call_expr(e: @Expr) -> bool {
212 match e.node { ExprCall(..) => true, _ => false }
215 pub fn block_from_expr(e: @Expr) -> P<Block> {
217 view_items: Vec::new(),
226 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
232 identifier: identifier,
233 lifetimes: Vec::new(),
234 types: OwnedSlice::empty(),
240 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> @Pat {
242 node: PatIdent(BindByValue(MutImmutable), ident_to_path(s, i), None),
246 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
247 Lifetime { id: DUMMY_NODE_ID,
248 span: codemap::DUMMY_SP,
252 pub fn is_unguarded(a: &Arm) -> bool {
259 pub fn unguarded_pat(a: &Arm) -> Option<Vec<@Pat> > {
261 Some(/* FIXME (#2543) */ a.pats.clone())
267 /// Generate a "pretty" name for an `impl` from its type and trait.
268 /// This is designed so that symbols of `impl`'d methods give some
269 /// hint of where they came from, (previously they would all just be
270 /// listed as `__extensions__::method_name::hash`, with no indication
272 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
273 let mut pretty = pprust::ty_to_str(ty);
275 Some(ref trait_ref) => {
276 pretty.push_char('.');
277 pretty.push_str(pprust::path_to_str(&trait_ref.path).as_slice());
281 token::gensym_ident(pretty.as_slice())
284 pub fn public_methods(ms: Vec<@Method> ) -> Vec<@Method> {
285 ms.move_iter().filter(|m| {
293 // extract a TypeMethod from a TraitMethod. if the TraitMethod is
294 // a default, pull out the useful fields to make a TypeMethod
295 pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod {
297 Required(ref m) => (*m).clone(),
301 attrs: m.attrs.clone(),
302 fn_style: m.fn_style,
304 generics: m.generics.clone(),
305 explicit_self: m.explicit_self,
313 pub fn split_trait_methods(trait_methods: &[TraitMethod])
314 -> (Vec<TypeMethod> , Vec<@Method> ) {
315 let mut reqd = Vec::new();
316 let mut provd = Vec::new();
317 for trt_method in trait_methods.iter() {
319 Required(ref tm) => reqd.push((*tm).clone()),
320 Provided(m) => provd.push(m)
326 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
327 match field.node.kind {
328 ast::NamedField(_, v) | ast::UnnamedField(v) => v
332 /// Maps a binary operator to its precedence
333 pub fn operator_prec(op: ast::BinOp) -> uint {
335 // 'as' sits here with 12
336 BiMul | BiDiv | BiRem => 11u,
337 BiAdd | BiSub => 10u,
342 BiLt | BiLe | BiGe | BiGt => 4u,
349 /// Precedence of the `as` operator, which is a binary operator
350 /// not appearing in the prior table.
351 pub static as_prec: uint = 12u;
353 pub fn empty_generics() -> Generics {
354 Generics {lifetimes: Vec::new(),
355 ty_params: OwnedSlice::empty()}
358 // ______________________________________________________________________
359 // Enumerating the IDs which appear in an AST
361 #[deriving(Encodable, Decodable)]
368 pub fn max() -> IdRange {
375 pub fn empty(&self) -> bool {
379 pub fn add(&mut self, id: NodeId) {
380 self.min = cmp::min(self.min, id);
381 self.max = cmp::max(self.max, id + 1);
385 pub trait IdVisitingOperation {
386 fn visit_id(&self, node_id: NodeId);
389 pub struct IdVisitor<'a, O> {
390 pub operation: &'a O,
391 pub pass_through_items: bool,
392 pub visited_outermost: bool,
395 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
396 fn visit_generics_helper(&self, generics: &Generics) {
397 for type_parameter in generics.ty_params.iter() {
398 self.operation.visit_id(type_parameter.id)
400 for lifetime in generics.lifetimes.iter() {
401 self.operation.visit_id(lifetime.id)
406 impl<'a, O: IdVisitingOperation> Visitor<()> for IdVisitor<'a, O> {
407 fn visit_mod(&mut self,
412 self.operation.visit_id(node_id);
413 visit::walk_mod(self, module, env)
416 fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
417 if !self.pass_through_items {
418 if self.visited_outermost {
421 self.visited_outermost = true;
424 match view_item.node {
425 ViewItemExternCrate(_, _, node_id) => {
426 self.operation.visit_id(node_id)
428 ViewItemUse(ref view_path) => {
429 match view_path.node {
430 ViewPathSimple(_, _, node_id) |
431 ViewPathGlob(_, node_id) => {
432 self.operation.visit_id(node_id)
434 ViewPathList(_, ref paths, node_id) => {
435 self.operation.visit_id(node_id);
436 for path in paths.iter() {
437 self.operation.visit_id(path.node.id)
443 visit::walk_view_item(self, view_item, env);
444 self.visited_outermost = false;
447 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem, env: ()) {
448 self.operation.visit_id(foreign_item.id);
449 visit::walk_foreign_item(self, foreign_item, env)
452 fn visit_item(&mut self, item: &Item, env: ()) {
453 if !self.pass_through_items {
454 if self.visited_outermost {
457 self.visited_outermost = true
461 self.operation.visit_id(item.id);
463 ItemEnum(ref enum_definition, _) => {
464 for variant in enum_definition.variants.iter() {
465 self.operation.visit_id(variant.node.id)
471 visit::walk_item(self, item, env);
473 self.visited_outermost = false
476 fn visit_local(&mut self, local: &Local, env: ()) {
477 self.operation.visit_id(local.id);
478 visit::walk_local(self, local, env)
481 fn visit_block(&mut self, block: &Block, env: ()) {
482 self.operation.visit_id(block.id);
483 visit::walk_block(self, block, env)
486 fn visit_stmt(&mut self, statement: &Stmt, env: ()) {
487 self.operation.visit_id(ast_util::stmt_id(statement));
488 visit::walk_stmt(self, statement, env)
491 fn visit_pat(&mut self, pattern: &Pat, env: ()) {
492 self.operation.visit_id(pattern.id);
493 visit::walk_pat(self, pattern, env)
496 fn visit_expr(&mut self, expression: &Expr, env: ()) {
497 self.operation.visit_id(expression.id);
498 visit::walk_expr(self, expression, env)
501 fn visit_ty(&mut self, typ: &Ty, env: ()) {
502 self.operation.visit_id(typ.id);
504 TyPath(_, _, id) => self.operation.visit_id(id),
507 visit::walk_ty(self, typ, env)
510 fn visit_generics(&mut self, generics: &Generics, env: ()) {
511 self.visit_generics_helper(generics);
512 visit::walk_generics(self, generics, env)
515 fn visit_fn(&mut self,
516 function_kind: &visit::FnKind,
517 function_declaration: &FnDecl,
522 if !self.pass_through_items {
523 match *function_kind {
524 visit::FkMethod(..) if self.visited_outermost => return,
525 visit::FkMethod(..) => self.visited_outermost = true,
530 self.operation.visit_id(node_id);
532 match *function_kind {
533 visit::FkItemFn(_, generics, _, _) |
534 visit::FkMethod(_, generics, _) => {
535 self.visit_generics_helper(generics)
537 visit::FkFnBlock => {}
540 for argument in function_declaration.inputs.iter() {
541 self.operation.visit_id(argument.id)
546 function_declaration,
551 if !self.pass_through_items {
552 match *function_kind {
553 visit::FkMethod(..) => self.visited_outermost = false,
559 fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
560 self.operation.visit_id(struct_field.node.id);
561 visit::walk_struct_field(self, struct_field, env)
564 fn visit_struct_def(&mut self,
565 struct_def: &StructDef,
570 self.operation.visit_id(id);
571 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
572 visit::walk_struct_def(self, struct_def, ());
575 fn visit_trait_method(&mut self, tm: &ast::TraitMethod, _: ()) {
577 ast::Required(ref m) => self.operation.visit_id(m.id),
578 ast::Provided(ref m) => self.operation.visit_id(m.id),
580 visit::walk_trait_method(self, tm, ());
584 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
586 let mut id_visitor = IdVisitor {
587 operation: operation,
588 pass_through_items: true,
589 visited_outermost: false,
592 visit::walk_inlined_item(&mut id_visitor, item, ());
595 struct IdRangeComputingVisitor {
596 result: Cell<IdRange>,
599 impl IdVisitingOperation for IdRangeComputingVisitor {
600 fn visit_id(&self, id: NodeId) {
601 let mut id_range = self.result.get();
603 self.result.set(id_range)
607 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
608 let visitor = IdRangeComputingVisitor {
609 result: Cell::new(IdRange::max())
611 visit_ids_for_inlined_item(item, &visitor);
615 pub fn compute_id_range_for_fn_body(fk: &visit::FnKind,
623 * Computes the id range for a single fn body,
624 * ignoring nested items.
627 let visitor = IdRangeComputingVisitor {
628 result: Cell::new(IdRange::max())
630 let mut id_visitor = IdVisitor {
632 pass_through_items: false,
633 visited_outermost: false,
635 id_visitor.visit_fn(fk, decl, body, sp, id, ());
639 pub fn is_item_impl(item: @ast::Item) -> bool {
641 ItemImpl(..) => true,
646 pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
652 PatIdent(_, _, Some(p)) => walk_pat(p, it),
653 PatStruct(_, ref fields, _) => {
654 fields.iter().advance(|f| walk_pat(f.pat, |p| it(p)))
656 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
657 s.iter().advance(|&p| walk_pat(p, |p| it(p)))
659 PatUniq(s) | PatRegion(s) => {
662 PatVec(ref before, ref slice, ref after) => {
663 before.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
664 slice.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
665 after.iter().advance(|&p| walk_pat(p, |p| it(p)))
667 PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
674 pub trait EachViewItem {
675 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool;
678 struct EachViewItemData<'a> {
679 callback: |&ast::ViewItem|: 'a -> bool,
682 impl<'a> Visitor<()> for EachViewItemData<'a> {
683 fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
684 let _ = (self.callback)(view_item);
688 impl EachViewItem for ast::Crate {
689 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
690 let mut visit = EachViewItemData {
693 visit::walk_crate(&mut visit, self, ());
698 pub fn view_path_id(p: &ViewPath) -> NodeId {
700 ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
701 | ViewPathList(_, _, id) => id
705 /// Returns true if the given struct def is tuple-like; i.e. that its fields
707 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
708 struct_def.ctor_id.is_some()
711 /// Returns true if the given pattern consists solely of an identifier
712 /// and false otherwise.
713 pub fn pat_is_ident(pat: @ast::Pat) -> bool {
715 ast::PatIdent(..) => true,
720 // are two paths equal when compared unhygienically?
721 // since I'm using this to replace ==, it seems appropriate
722 // to compare the span, global, etc. fields as well.
723 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
725 && (a.global == b.global)
726 && (segments_name_eq(a.segments.as_slice(), b.segments.as_slice()))
729 // are two arrays of segments equal when compared unhygienically?
730 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
731 if a.len() != b.len() {
734 for (idx,seg) in a.iter().enumerate() {
735 if (seg.identifier.name != b[idx].identifier.name)
736 // FIXME #7743: ident -> name problems in lifetime comparison?
737 || (seg.lifetimes != b[idx].lifetimes)
738 // can types contain idents?
739 || (seg.types != b[idx].types) {
747 // Returns true if this literal is a string and false otherwise.
748 pub fn lit_is_str(lit: @Lit) -> bool {
755 pub fn get_inner_tys(ty: P<Ty>) -> Vec<P<Ty>> {
757 ast::TyRptr(_, mut_ty) | ast::TyPtr(mut_ty) => {
763 | ast::TyFixedLengthVec(ty, _) => vec!(ty),
764 ast::TyTup(ref tys) => tys.clone(),
774 use owned_slice::OwnedSlice;
776 fn ident_to_segment(id : &Ident) -> PathSegment {
777 PathSegment {identifier:id.clone(),
778 lifetimes: Vec::new(),
779 types: OwnedSlice::empty()}
782 #[test] fn idents_name_eq_test() {
783 assert!(segments_name_eq(
784 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
785 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
786 [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}]
787 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
788 assert!(!segments_name_eq(
789 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
790 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
791 [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}]
792 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));