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;
26 pub fn path_name_i(idents: &[Ident]) -> String {
27 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
28 idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
31 pub fn local_def(id: NodeId) -> DefId {
32 ast::DefId { krate: LOCAL_CRATE, node: id }
35 pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
37 pub fn stmt_id(s: &Stmt) -> NodeId {
39 StmtDecl(_, id) => id,
40 StmtExpr(_, id) => id,
41 StmtSemi(_, id) => id,
42 StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
46 pub fn binop_to_string(op: BinOp_) -> &'static str {
69 pub fn lazy_binop(b: BinOp_) -> bool {
77 pub fn is_shift_binop(b: BinOp_) -> bool {
85 pub fn is_comparison_binop(b: BinOp_) -> bool {
87 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
89 BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
90 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
95 /// Returns `true` if the binary operator takes its arguments by value
96 pub fn is_by_value_binop(b: BinOp_) -> bool {
97 !is_comparison_binop(b)
100 /// Returns `true` if the unary operator takes its argument by value
101 pub fn is_by_value_unop(u: UnOp) -> bool {
103 UnNeg | UnNot => true,
108 pub fn unop_to_string(op: UnOp) -> &'static str {
117 pub fn is_path(e: P<Expr>) -> bool {
118 match e.node { ExprPath(..) => true, _ => false }
121 /// Get a string representation of a signed int type, with its value.
122 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
123 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
133 // cast to a u64 so we can correctly print INT64_MIN. All integral types
134 // are parsed as u64, so we wouldn't want to print an extra negative
136 Some(n) => format!("{}{}", n as u64, s),
137 None => s.to_string()
141 pub fn int_ty_max(t: IntTy) -> u64 {
145 TyIs | TyI32 => 0x80000000, // actually ni about TyIs
146 TyI64 => 0x8000000000000000
150 /// Get a string representation of an unsigned int type, with its value.
151 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
152 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
162 Some(n) => format!("{}{}", n, s),
163 None => s.to_string()
167 pub fn uint_ty_max(t: UintTy) -> u64 {
171 TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
172 TyU64 => 0xffffffffffffffff
176 pub fn float_ty_to_string(t: FloatTy) -> String {
178 TyF32 => "f32".to_string(),
179 TyF64 => "f64".to_string(),
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 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
193 lifetimes: Vec::new(),
194 types: OwnedSlice::empty(),
195 bindings: OwnedSlice::empty(),
202 // If path is a single segment ident path, return that ident. Otherwise, return
204 pub fn path_to_ident(path: &Path) -> Option<Ident> {
205 if path.segments.len() != 1 {
209 let segment = &path.segments[0];
210 if !segment.parameters.is_empty() {
214 Some(segment.identifier)
217 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
220 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
225 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
226 Lifetime { id: DUMMY_NODE_ID,
227 span: codemap::DUMMY_SP,
231 /// Generate a "pretty" name for an `impl` from its type and trait.
232 /// This is designed so that symbols of `impl`'d methods give some
233 /// hint of where they came from, (previously they would all just be
234 /// listed as `__extensions__::method_name::hash`, with no indication
236 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
237 let mut pretty = match ty {
238 Some(t) => pprust::ty_to_string(t),
239 None => String::from("..")
243 Some(ref trait_ref) => {
245 pretty.push_str(&pprust::path_to_string(&trait_ref.path));
249 token::gensym_ident(&pretty[..])
252 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
253 match field.node.kind {
254 ast::NamedField(_, v) | ast::UnnamedField(v) => v
258 /// Maps a binary operator to its precedence
259 pub fn operator_prec(op: ast::BinOp_) -> usize {
261 // 'as' sits here with 12
262 BiMul | BiDiv | BiRem => 11,
268 BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
274 /// Precedence of the `as` operator, which is a binary operator
275 /// not appearing in the prior table.
276 pub const AS_PREC: usize = 12;
278 pub fn empty_generics() -> Generics {
280 lifetimes: Vec::new(),
281 ty_params: OwnedSlice::empty(),
282 where_clause: WhereClause {
284 predicates: Vec::new(),
289 // ______________________________________________________________________
290 // Enumerating the IDs which appear in an AST
292 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
299 pub fn max() -> IdRange {
306 pub fn empty(&self) -> bool {
310 pub fn add(&mut self, id: NodeId) {
311 self.min = cmp::min(self.min, id);
312 self.max = cmp::max(self.max, id + 1);
316 pub trait IdVisitingOperation {
317 fn visit_id(&mut self, node_id: NodeId);
320 /// A visitor that applies its operation to all of the node IDs
321 /// in a visitable thing.
323 pub struct IdVisitor<'a, O:'a> {
324 pub operation: &'a mut O,
325 pub pass_through_items: bool,
326 pub visited_outermost: bool,
329 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
330 fn visit_generics_helper(&mut self, generics: &Generics) {
331 for type_parameter in generics.ty_params.iter() {
332 self.operation.visit_id(type_parameter.id)
334 for lifetime in &generics.lifetimes {
335 self.operation.visit_id(lifetime.lifetime.id)
340 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
341 fn visit_mod(&mut self,
345 self.operation.visit_id(node_id);
346 visit::walk_mod(self, module)
349 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
350 self.operation.visit_id(foreign_item.id);
351 visit::walk_foreign_item(self, foreign_item)
354 fn visit_item(&mut self, item: &Item) {
355 if !self.pass_through_items {
356 if self.visited_outermost {
359 self.visited_outermost = true
363 self.operation.visit_id(item.id);
365 ItemUse(ref view_path) => {
366 match view_path.node {
367 ViewPathSimple(_, _) |
368 ViewPathGlob(_) => {}
369 ViewPathList(_, ref paths) => {
371 self.operation.visit_id(path.node.id())
376 ItemEnum(ref enum_definition, _) => {
377 for variant in &enum_definition.variants {
378 self.operation.visit_id(variant.node.id)
384 visit::walk_item(self, item);
386 self.visited_outermost = false
389 fn visit_local(&mut self, local: &Local) {
390 self.operation.visit_id(local.id);
391 visit::walk_local(self, local)
394 fn visit_block(&mut self, block: &Block) {
395 self.operation.visit_id(block.id);
396 visit::walk_block(self, block)
399 fn visit_stmt(&mut self, statement: &Stmt) {
400 self.operation.visit_id(ast_util::stmt_id(statement));
401 visit::walk_stmt(self, statement)
404 fn visit_pat(&mut self, pattern: &Pat) {
405 self.operation.visit_id(pattern.id);
406 visit::walk_pat(self, pattern)
409 fn visit_expr(&mut self, expression: &Expr) {
410 self.operation.visit_id(expression.id);
411 visit::walk_expr(self, expression)
414 fn visit_ty(&mut self, typ: &Ty) {
415 self.operation.visit_id(typ.id);
416 visit::walk_ty(self, typ)
419 fn visit_generics(&mut self, generics: &Generics) {
420 self.visit_generics_helper(generics);
421 visit::walk_generics(self, generics)
424 fn visit_fn(&mut self,
425 function_kind: visit::FnKind<'v>,
426 function_declaration: &'v FnDecl,
430 if !self.pass_through_items {
431 match function_kind {
432 visit::FkMethod(..) if self.visited_outermost => return,
433 visit::FkMethod(..) => self.visited_outermost = true,
438 self.operation.visit_id(node_id);
440 match function_kind {
441 visit::FkItemFn(_, generics, _, _, _, _) => {
442 self.visit_generics_helper(generics)
444 visit::FkMethod(_, sig, _) => {
445 self.visit_generics_helper(&sig.generics)
447 visit::FkFnBlock => {}
450 for argument in &function_declaration.inputs {
451 self.operation.visit_id(argument.id)
456 function_declaration,
460 if !self.pass_through_items {
461 if let visit::FkMethod(..) = function_kind {
462 self.visited_outermost = false;
467 fn visit_struct_field(&mut self, struct_field: &StructField) {
468 self.operation.visit_id(struct_field.node.id);
469 visit::walk_struct_field(self, struct_field)
472 fn visit_struct_def(&mut self,
473 struct_def: &StructDef,
477 self.operation.visit_id(id);
478 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
479 visit::walk_struct_def(self, struct_def);
482 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
483 self.operation.visit_id(ti.id);
484 visit::walk_trait_item(self, ti);
487 fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
488 self.operation.visit_id(ii.id);
489 visit::walk_impl_item(self, ii);
492 fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
493 self.operation.visit_id(lifetime.id);
496 fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
497 self.visit_lifetime_ref(&def.lifetime);
500 fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
501 self.operation.visit_id(trait_ref.ref_id);
502 visit::walk_trait_ref(self, trait_ref);
506 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
508 let mut id_visitor = IdVisitor {
509 operation: operation,
510 pass_through_items: true,
511 visited_outermost: false,
514 visit::walk_inlined_item(&mut id_visitor, item);
517 struct IdRangeComputingVisitor {
521 impl IdVisitingOperation for IdRangeComputingVisitor {
522 fn visit_id(&mut self, id: NodeId) {
527 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
528 let mut visitor = IdRangeComputingVisitor {
529 result: IdRange::max()
531 visit_ids_for_inlined_item(item, &mut visitor);
535 /// Computes the id range for a single fn body, ignoring nested items.
536 pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
543 let mut visitor = IdRangeComputingVisitor {
544 result: IdRange::max()
546 let mut id_visitor = IdVisitor {
547 operation: &mut visitor,
548 pass_through_items: false,
549 visited_outermost: false,
551 id_visitor.visit_fn(fk, decl, body, sp, id);
552 id_visitor.operation.result
555 pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
556 // FIXME(#19596) this is a workaround, but there should be a better way
557 fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
563 PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
564 PatStruct(_, ref fields, _) => {
565 fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
567 PatEnum(_, Some(ref s)) | PatTup(ref s) => {
568 s.iter().all(|p| walk_pat_(&**p, it))
570 PatBox(ref s) | PatRegion(ref s, _) => {
573 PatVec(ref before, ref slice, ref after) => {
574 before.iter().all(|p| walk_pat_(&**p, it)) &&
575 slice.iter().all(|p| walk_pat_(&**p, it)) &&
576 after.iter().all(|p| walk_pat_(&**p, it))
578 PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
579 PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
580 PatEnum(_, _) | PatQPath(_, _) => {
586 walk_pat_(pat, &mut it)
589 /// Returns true if the given struct def is tuple-like; i.e. that its fields
591 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
592 struct_def.ctor_id.is_some()
595 /// Returns true if the given pattern consists solely of an identifier
596 /// and false otherwise.
597 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
599 ast::PatIdent(..) => true,
604 // are two paths equal when compared unhygienically?
605 // since I'm using this to replace ==, it seems appropriate
606 // to compare the span, global, etc. fields as well.
607 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
609 && (a.global == b.global)
610 && (segments_name_eq(&a.segments[..], &b.segments[..]))
613 // are two arrays of segments equal when compared unhygienically?
614 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
615 a.len() == b.len() &&
616 a.iter().zip(b).all(|(s, t)| {
617 s.identifier.name == t.identifier.name &&
618 // FIXME #7743: ident -> name problems in lifetime comparison?
619 // can types contain idents?
620 s.parameters == t.parameters
624 /// Returns true if this literal is a string and false otherwise.
625 pub fn lit_is_str(lit: &Lit) -> bool {
637 fn ident_to_segment(id : &Ident) -> PathSegment {
638 PathSegment {identifier: id.clone(),
639 parameters: PathParameters::none()}
642 #[test] fn idents_name_eq_test() {
643 assert!(segments_name_eq(
644 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
645 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
646 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
647 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));
648 assert!(!segments_name_eq(
649 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
650 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
651 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
652 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));