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.
14 use attr::{InlineNever, InlineNone};
18 use owned_slice::OwnedSlice;
26 use std::gc::{Gc, GC};
29 pub fn path_name_i(idents: &[Ident]) -> String {
30 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
31 idents.iter().map(|i| {
32 token::get_ident(*i).get().to_string()
33 }).collect::<Vec<String>>().connect("::")
36 pub fn local_def(id: NodeId) -> DefId {
37 ast::DefId { krate: LOCAL_CRATE, node: id }
40 pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
42 pub fn stmt_id(s: &Stmt) -> NodeId {
44 StmtDecl(_, id) => id,
45 StmtExpr(_, id) => id,
46 StmtSemi(_, id) => id,
47 StmtMac(..) => fail!("attempted to analyze unexpanded stmt")
51 pub fn binop_to_str(op: BinOp) -> &'static str {
74 pub fn lazy_binop(b: BinOp) -> bool {
82 pub fn is_shift_binop(b: BinOp) -> bool {
90 pub fn unop_to_str(op: UnOp) -> &'static str {
100 pub fn is_path(e: Gc<Expr>) -> bool {
101 return match e.node { ExprPath(_) => true, _ => false };
104 // Get a string representation of a signed int type, with its value.
105 // We want to avoid "45int" and "-3int" in favor of "45" and "-3"
106 pub fn int_ty_to_str(t: IntTy, val: Option<i64>) -> String {
108 TyI if val.is_some() => "i",
117 // cast to a u64 so we can correctly print INT64_MIN. All integral types
118 // are parsed as u64, so we wouldn't want to print an extra negative
120 Some(n) => format!("{}{}", n as u64, s),
121 None => s.to_string()
125 pub fn int_ty_max(t: IntTy) -> u64 {
129 TyI | TyI32 => 0x80000000u64, // actually ni about TyI
130 TyI64 => 0x8000000000000000u64
134 // Get a string representation of an unsigned int type, with its value.
135 // We want to avoid "42uint" in favor of "42u"
136 pub fn uint_ty_to_str(t: UintTy, val: Option<u64>) -> String {
138 TyU if val.is_some() => "u",
147 Some(n) => format!("{}{}", n, s),
148 None => s.to_string()
152 pub fn uint_ty_max(t: UintTy) -> u64 {
156 TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
157 TyU64 => 0xffffffffffffffffu64
161 pub fn float_ty_to_str(t: FloatTy) -> String {
163 TyF32 => "f32".to_string(),
164 TyF64 => "f64".to_string(),
168 pub fn is_call_expr(e: Gc<Expr>) -> bool {
169 match e.node { ExprCall(..) => true, _ => false }
172 pub fn block_from_expr(e: Gc<Expr>) -> P<Block> {
174 view_items: Vec::new(),
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 lifetimes: Vec::new(),
193 types: OwnedSlice::empty(),
199 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> Gc<Pat> {
200 box(GC) ast::Pat { id: id,
201 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
205 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
206 Lifetime { id: DUMMY_NODE_ID,
207 span: codemap::DUMMY_SP,
211 pub fn is_unguarded(a: &Arm) -> bool {
218 pub fn unguarded_pat(a: &Arm) -> Option<Vec<Gc<Pat>>> {
220 Some(/* FIXME (#2543) */ a.pats.clone())
226 /// Generate a "pretty" name for an `impl` from its type and trait.
227 /// This is designed so that symbols of `impl`'d methods give some
228 /// hint of where they came from, (previously they would all just be
229 /// listed as `__extensions__::method_name::hash`, with no indication
231 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
232 let mut pretty = pprust::ty_to_str(ty);
234 Some(ref trait_ref) => {
235 pretty.push_char('.');
236 pretty.push_str(pprust::path_to_str(&trait_ref.path).as_slice());
240 token::gensym_ident(pretty.as_slice())
243 pub fn public_methods(ms: Vec<Gc<Method>> ) -> Vec<Gc<Method>> {
244 ms.move_iter().filter(|m| {
252 // extract a TypeMethod from a TraitMethod. if the TraitMethod is
253 // a default, pull out the useful fields to make a TypeMethod
254 pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod {
256 Required(ref m) => (*m).clone(),
260 attrs: m.attrs.clone(),
261 fn_style: m.fn_style,
263 generics: m.generics.clone(),
264 explicit_self: m.explicit_self,
273 pub fn split_trait_methods(trait_methods: &[TraitMethod])
274 -> (Vec<TypeMethod> , Vec<Gc<Method>> ) {
275 let mut reqd = Vec::new();
276 let mut provd = Vec::new();
277 for trt_method in trait_methods.iter() {
279 Required(ref tm) => reqd.push((*tm).clone()),
280 Provided(m) => provd.push(m)
286 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
287 match field.node.kind {
288 ast::NamedField(_, v) | ast::UnnamedField(v) => v
292 /// Maps a binary operator to its precedence
293 pub fn operator_prec(op: ast::BinOp) -> uint {
295 // 'as' sits here with 12
296 BiMul | BiDiv | BiRem => 11u,
297 BiAdd | BiSub => 10u,
302 BiLt | BiLe | BiGe | BiGt => 4u,
309 /// Precedence of the `as` operator, which is a binary operator
310 /// not appearing in the prior table.
311 pub static as_prec: uint = 12u;
313 pub fn empty_generics() -> Generics {
314 Generics {lifetimes: Vec::new(),
315 ty_params: OwnedSlice::empty()}
318 // ______________________________________________________________________
319 // Enumerating the IDs which appear in an AST
321 #[deriving(Encodable, Decodable)]
328 pub fn max() -> IdRange {
335 pub fn empty(&self) -> bool {
339 pub fn add(&mut self, id: NodeId) {
340 self.min = cmp::min(self.min, id);
341 self.max = cmp::max(self.max, id + 1);
345 pub trait IdVisitingOperation {
346 fn visit_id(&self, node_id: NodeId);
349 pub struct IdVisitor<'a, O> {
350 pub operation: &'a O,
351 pub pass_through_items: bool,
352 pub visited_outermost: bool,
355 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
356 fn visit_generics_helper(&self, generics: &Generics) {
357 for type_parameter in generics.ty_params.iter() {
358 self.operation.visit_id(type_parameter.id)
360 for lifetime in generics.lifetimes.iter() {
361 self.operation.visit_id(lifetime.id)
366 impl<'a, O: IdVisitingOperation> Visitor<()> for IdVisitor<'a, O> {
367 fn visit_mod(&mut self,
372 self.operation.visit_id(node_id);
373 visit::walk_mod(self, module, env)
376 fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
377 if !self.pass_through_items {
378 if self.visited_outermost {
381 self.visited_outermost = true;
384 match view_item.node {
385 ViewItemExternCrate(_, _, node_id) => {
386 self.operation.visit_id(node_id)
388 ViewItemUse(ref view_path) => {
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)
403 visit::walk_view_item(self, view_item, env);
404 self.visited_outermost = false;
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)
456 fn visit_expr(&mut self, expression: &Expr, env: ()) {
457 self.operation.visit_id(expression.id);
458 visit::walk_expr(self, expression, env)
461 fn visit_ty(&mut self, typ: &Ty, env: ()) {
462 self.operation.visit_id(typ.id);
464 TyPath(_, _, id) => self.operation.visit_id(id),
467 visit::walk_ty(self, typ, env)
470 fn visit_generics(&mut self, generics: &Generics, env: ()) {
471 self.visit_generics_helper(generics);
472 visit::walk_generics(self, generics, env)
475 fn visit_fn(&mut self,
476 function_kind: &visit::FnKind,
477 function_declaration: &FnDecl,
482 if !self.pass_through_items {
483 match *function_kind {
484 visit::FkMethod(..) if self.visited_outermost => return,
485 visit::FkMethod(..) => self.visited_outermost = true,
490 self.operation.visit_id(node_id);
492 match *function_kind {
493 visit::FkItemFn(_, generics, _, _) |
494 visit::FkMethod(_, generics, _) => {
495 self.visit_generics_helper(generics)
497 visit::FkFnBlock => {}
500 for argument in function_declaration.inputs.iter() {
501 self.operation.visit_id(argument.id)
506 function_declaration,
511 if !self.pass_through_items {
512 match *function_kind {
513 visit::FkMethod(..) => self.visited_outermost = false,
519 fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
520 self.operation.visit_id(struct_field.node.id);
521 visit::walk_struct_field(self, struct_field, env)
524 fn visit_struct_def(&mut self,
525 struct_def: &StructDef,
530 self.operation.visit_id(id);
531 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
532 visit::walk_struct_def(self, struct_def, ());
535 fn visit_trait_method(&mut self, tm: &ast::TraitMethod, _: ()) {
537 ast::Required(ref m) => self.operation.visit_id(m.id),
538 ast::Provided(ref m) => self.operation.visit_id(m.id),
540 visit::walk_trait_method(self, tm, ());
544 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
546 let mut id_visitor = IdVisitor {
547 operation: operation,
548 pass_through_items: true,
549 visited_outermost: false,
552 visit::walk_inlined_item(&mut id_visitor, item, ());
555 struct IdRangeComputingVisitor {
556 result: Cell<IdRange>,
559 impl IdVisitingOperation for IdRangeComputingVisitor {
560 fn visit_id(&self, id: NodeId) {
561 let mut id_range = self.result.get();
563 self.result.set(id_range)
567 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
568 let visitor = IdRangeComputingVisitor {
569 result: Cell::new(IdRange::max())
571 visit_ids_for_inlined_item(item, &visitor);
575 pub fn compute_id_range_for_fn_body(fk: &visit::FnKind,
583 * Computes the id range for a single fn body,
584 * ignoring nested items.
587 let visitor = IdRangeComputingVisitor {
588 result: Cell::new(IdRange::max())
590 let mut id_visitor = IdVisitor {
592 pass_through_items: false,
593 visited_outermost: false,
595 id_visitor.visit_fn(fk, decl, body, sp, id, ());
599 pub fn is_item_impl(item: Gc<ast::Item>) -> bool {
601 ItemImpl(..) => true,
606 pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
612 PatIdent(_, _, Some(ref p)) => walk_pat(&**p, it),
613 PatStruct(_, ref fields, _) => {
614 fields.iter().advance(|f| walk_pat(&*f.pat, |p| it(p)))
616 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
617 s.iter().advance(|p| walk_pat(&**p, |p| it(p)))
619 PatBox(ref s) | PatRegion(ref s) => {
622 PatVec(ref before, ref slice, ref after) => {
623 before.iter().advance(|p| walk_pat(&**p, |p| it(p))) &&
624 slice.iter().advance(|p| walk_pat(&**p, |p| it(p))) &&
625 after.iter().advance(|p| walk_pat(&**p, |p| it(p)))
627 PatMac(_) => fail!("attempted to analyze unexpanded pattern"),
628 PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
635 pub trait EachViewItem {
636 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool;
639 struct EachViewItemData<'a> {
640 callback: |&ast::ViewItem|: 'a -> bool,
643 impl<'a> Visitor<()> for EachViewItemData<'a> {
644 fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
645 let _ = (self.callback)(view_item);
649 impl EachViewItem for ast::Crate {
650 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
651 let mut visit = EachViewItemData {
654 visit::walk_crate(&mut visit, self, ());
659 pub fn view_path_id(p: &ViewPath) -> NodeId {
661 ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
662 | ViewPathList(_, _, id) => id
666 /// Returns true if the given struct def is tuple-like; i.e. that its fields
668 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
669 struct_def.ctor_id.is_some()
672 /// Returns true if the given pattern consists solely of an identifier
673 /// and false otherwise.
674 pub fn pat_is_ident(pat: Gc<ast::Pat>) -> bool {
676 ast::PatIdent(..) => true,
681 // are two paths equal when compared unhygienically?
682 // since I'm using this to replace ==, it seems appropriate
683 // to compare the span, global, etc. fields as well.
684 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
686 && (a.global == b.global)
687 && (segments_name_eq(a.segments.as_slice(), b.segments.as_slice()))
690 // are two arrays of segments equal when compared unhygienically?
691 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
692 if a.len() != b.len() {
695 for (idx,seg) in a.iter().enumerate() {
696 if (seg.identifier.name != b[idx].identifier.name)
697 // FIXME #7743: ident -> name problems in lifetime comparison?
698 || (seg.lifetimes != b[idx].lifetimes)
699 // can types contain idents?
700 || (seg.types != b[idx].types) {
708 // Returns true if this literal is a string and false otherwise.
709 pub fn lit_is_str(lit: Gc<Lit>) -> bool {
716 pub fn get_inner_tys(ty: P<Ty>) -> Vec<P<Ty>> {
718 ast::TyRptr(_, mut_ty) | ast::TyPtr(mut_ty) => {
724 | ast::TyFixedLengthVec(ty, _) => vec!(ty),
725 ast::TyTup(ref tys) => tys.clone(),
726 ast::TyParen(ty) => get_inner_tys(ty),
731 /// Returns true if the static with the given mutability and attributes
732 /// has a significant address and false otherwise.
733 pub fn static_has_significant_address(mutbl: ast::Mutability,
734 attrs: &[ast::Attribute])
736 if mutbl == ast::MutMutable {
739 let inline = attr::find_inline_attr(attrs);
740 inline == InlineNever || inline == InlineNone
747 use owned_slice::OwnedSlice;
749 fn ident_to_segment(id : &Ident) -> PathSegment {
750 PathSegment {identifier:id.clone(),
751 lifetimes: Vec::new(),
752 types: OwnedSlice::empty()}
755 #[test] fn idents_name_eq_test() {
756 assert!(segments_name_eq(
757 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
758 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
759 [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}]
760 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
761 assert!(!segments_name_eq(
762 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
763 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
764 [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}]
765 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));