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 // 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() }
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 match view_item.node {
400 ViewItemExternCrate(_, _, node_id) => {
401 self.operation.visit_id(node_id)
403 ViewItemUse(ref view_paths) => {
404 for view_path in view_paths.iter() {
405 match view_path.node {
406 ViewPathSimple(_, _, node_id) |
407 ViewPathGlob(_, node_id) => {
408 self.operation.visit_id(node_id)
410 ViewPathList(_, ref paths, node_id) => {
411 self.operation.visit_id(node_id);
412 for path in paths.iter() {
413 self.operation.visit_id(path.node.id)
420 visit::walk_view_item(self, view_item, env)
423 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem, env: ()) {
424 self.operation.visit_id(foreign_item.id);
425 visit::walk_foreign_item(self, foreign_item, env)
428 fn visit_item(&mut self, item: &Item, env: ()) {
429 if !self.pass_through_items {
430 if self.visited_outermost {
433 self.visited_outermost = true
437 self.operation.visit_id(item.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, env);
449 self.visited_outermost = false
452 fn visit_local(&mut self, local: &Local, env: ()) {
453 self.operation.visit_id(local.id);
454 visit::walk_local(self, local, env)
457 fn visit_block(&mut self, block: &Block, env: ()) {
458 self.operation.visit_id(block.id);
459 visit::walk_block(self, block, env)
462 fn visit_stmt(&mut self, statement: &Stmt, env: ()) {
463 self.operation.visit_id(ast_util::stmt_id(statement));
464 visit::walk_stmt(self, statement, env)
467 fn visit_pat(&mut self, pattern: &Pat, env: ()) {
468 self.operation.visit_id(pattern.id);
469 visit::walk_pat(self, pattern, env)
473 fn visit_expr(&mut self, expression: &Expr, env: ()) {
474 self.operation.visit_id(expression.id);
475 visit::walk_expr(self, expression, env)
478 fn visit_ty(&mut self, typ: &Ty, env: ()) {
479 self.operation.visit_id(typ.id);
481 TyPath(_, _, id) => self.operation.visit_id(id),
484 visit::walk_ty(self, typ, env)
487 fn visit_generics(&mut self, generics: &Generics, env: ()) {
488 self.visit_generics_helper(generics);
489 visit::walk_generics(self, generics, env)
492 fn visit_fn(&mut self,
493 function_kind: &visit::FnKind,
494 function_declaration: &FnDecl,
499 if !self.pass_through_items {
500 match *function_kind {
501 visit::FkMethod(..) if self.visited_outermost => return,
502 visit::FkMethod(..) => self.visited_outermost = true,
507 self.operation.visit_id(node_id);
509 match *function_kind {
510 visit::FkItemFn(_, generics, _, _) |
511 visit::FkMethod(_, generics, _) => {
512 self.visit_generics_helper(generics)
514 visit::FkFnBlock => {}
517 for argument in function_declaration.inputs.iter() {
518 self.operation.visit_id(argument.id)
523 function_declaration,
529 if !self.pass_through_items {
530 match *function_kind {
531 visit::FkMethod(..) => self.visited_outermost = false,
537 fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
538 self.operation.visit_id(struct_field.node.id);
539 visit::walk_struct_field(self, struct_field, env)
542 fn visit_struct_def(&mut self,
543 struct_def: &StructDef,
545 generics: &ast::Generics,
548 self.operation.visit_id(id);
549 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
550 visit::walk_struct_def(self, struct_def, ident, generics, id, ());
553 fn visit_trait_method(&mut self, tm: &ast::TraitMethod, _: ()) {
555 ast::Required(ref m) => self.operation.visit_id(m.id),
556 ast::Provided(ref m) => self.operation.visit_id(m.id),
558 visit::walk_trait_method(self, tm, ());
562 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
564 let mut id_visitor = IdVisitor {
565 operation: operation,
566 pass_through_items: true,
567 visited_outermost: false,
570 visit::walk_inlined_item(&mut id_visitor, item, ());
573 struct IdRangeComputingVisitor {
574 result: Cell<IdRange>,
577 impl IdVisitingOperation for IdRangeComputingVisitor {
578 fn visit_id(&self, id: NodeId) {
579 let mut id_range = self.result.get();
581 self.result.set(id_range)
585 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
586 let visitor = IdRangeComputingVisitor {
587 result: Cell::new(IdRange::max())
589 visit_ids_for_inlined_item(item, &visitor);
593 pub fn is_item_impl(item: @ast::Item) -> bool {
595 ItemImpl(..) => true,
600 pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
606 PatIdent(_, _, Some(p)) => walk_pat(p, it),
607 PatStruct(_, ref fields, _) => {
608 fields.iter().advance(|f| walk_pat(f.pat, |p| it(p)))
610 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
611 s.iter().advance(|&p| walk_pat(p, |p| it(p)))
613 PatUniq(s) | PatRegion(s) => {
616 PatVec(ref before, ref slice, ref after) => {
617 before.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
618 slice.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
619 after.iter().advance(|&p| walk_pat(p, |p| it(p)))
621 PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
628 pub trait EachViewItem {
629 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool;
632 struct EachViewItemData<'a> {
633 callback: |&ast::ViewItem|: 'a -> bool,
636 impl<'a> Visitor<()> for EachViewItemData<'a> {
637 fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
638 let _ = (self.callback)(view_item);
642 impl EachViewItem for ast::Crate {
643 fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
644 let mut visit = EachViewItemData {
647 visit::walk_crate(&mut visit, self, ());
652 pub fn view_path_id(p: &ViewPath) -> NodeId {
654 ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
655 | ViewPathList(_, _, id) => id
659 /// Returns true if the given struct def is tuple-like; i.e. that its fields
661 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
662 struct_def.ctor_id.is_some()
665 /// Returns true if the given pattern consists solely of an identifier
666 /// and false otherwise.
667 pub fn pat_is_ident(pat: @ast::Pat) -> bool {
669 ast::PatIdent(..) => true,
674 // are two paths equal when compared unhygienically?
675 // since I'm using this to replace ==, it seems appropriate
676 // to compare the span, global, etc. fields as well.
677 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
679 && (a.global == b.global)
680 && (segments_name_eq(a.segments.as_slice(), b.segments.as_slice()))
683 // are two arrays of segments equal when compared unhygienically?
684 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
685 if a.len() != b.len() {
688 for (idx,seg) in a.iter().enumerate() {
689 if (seg.identifier.name != b[idx].identifier.name)
690 // FIXME #7743: ident -> name problems in lifetime comparison?
691 || (seg.lifetimes != b[idx].lifetimes)
692 // can types contain idents?
693 || (seg.types != b[idx].types) {
701 // Returns true if this literal is a string and false otherwise.
702 pub fn lit_is_str(lit: @Lit) -> bool {
709 pub fn get_inner_tys(ty: P<Ty>) -> Vec<P<Ty>> {
711 ast::TyRptr(_, mut_ty) | ast::TyPtr(mut_ty) => {
717 | ast::TyFixedLengthVec(ty, _) => vec!(ty),
718 ast::TyTup(ref tys) => tys.clone(),
728 use owned_slice::OwnedSlice;
730 fn ident_to_segment(id : &Ident) -> PathSegment {
731 PathSegment {identifier:id.clone(),
732 lifetimes: Vec::new(),
733 types: OwnedSlice::empty()}
736 #[test] fn idents_name_eq_test() {
737 assert!(segments_name_eq(
738 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
739 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
740 [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}]
741 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
742 assert!(!segments_name_eq(
743 [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
744 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
745 [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}]
746 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));