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;
20 use visit::{FnKind, Visitor};
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 stmt_id(s: &Stmt) -> NodeId {
33 StmtDecl(_, id) => id,
34 StmtExpr(_, id) => id,
35 StmtSemi(_, id) => id,
36 StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
40 pub fn binop_to_string(op: BinOp_) -> &'static str {
63 pub fn lazy_binop(b: BinOp_) -> bool {
71 pub fn is_shift_binop(b: BinOp_) -> bool {
79 pub fn is_comparison_binop(b: BinOp_) -> bool {
81 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
83 BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
84 BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
89 /// Returns `true` if the binary operator takes its arguments by value
90 pub fn is_by_value_binop(b: BinOp_) -> bool {
91 !is_comparison_binop(b)
94 /// Returns `true` if the unary operator takes its argument by value
95 pub fn is_by_value_unop(u: UnOp) -> bool {
97 UnNeg | UnNot => true,
102 pub fn unop_to_string(op: UnOp) -> &'static str {
110 pub fn is_path(e: P<Expr>) -> bool {
111 match e.node { ExprPath(..) => true, _ => false }
114 /// Get a string representation of a signed int type, with its value.
115 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
116 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
126 // cast to a u64 so we can correctly print INT64_MIN. All integral types
127 // are parsed as u64, so we wouldn't want to print an extra negative
129 Some(n) => format!("{}{}", n as u64, s),
130 None => s.to_string()
134 pub fn int_ty_max(t: IntTy) -> u64 {
138 TyIs | TyI32 => 0x80000000, // actually ni about TyIs
139 TyI64 => 0x8000000000000000
143 /// Get a string representation of an unsigned int type, with its value.
144 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
145 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
155 Some(n) => format!("{}{}", n, s),
156 None => s.to_string()
160 pub fn uint_ty_max(t: UintTy) -> u64 {
164 TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
165 TyU64 => 0xffffffffffffffff
169 pub fn float_ty_to_string(t: FloatTy) -> String {
171 TyF32 => "f32".to_string(),
172 TyF64 => "f64".to_string(),
176 // convert a span and an identifier to the corresponding
178 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
184 identifier: identifier,
185 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
186 lifetimes: Vec::new(),
187 types: OwnedSlice::empty(),
188 bindings: OwnedSlice::empty(),
195 // If path is a single segment ident path, return that ident. Otherwise, return
197 pub fn path_to_ident(path: &Path) -> Option<Ident> {
198 if path.segments.len() != 1 {
202 let segment = &path.segments[0];
203 if !segment.parameters.is_empty() {
207 Some(segment.identifier)
210 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
213 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
218 /// Generate a "pretty" name for an `impl` from its type and trait.
219 /// This is designed so that symbols of `impl`'d methods give some
220 /// hint of where they came from, (previously they would all just be
221 /// listed as `__extensions__::method_name::hash`, with no indication
223 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
224 let mut pretty = match ty {
225 Some(t) => pprust::ty_to_string(t),
226 None => String::from("..")
230 Some(ref trait_ref) => {
232 pretty.push_str(&pprust::path_to_string(&trait_ref.path));
236 token::gensym_ident(&pretty[..])
239 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
240 match field.node.kind {
241 ast::NamedField(_, v) | ast::UnnamedField(v) => v
245 /// Maps a binary operator to its precedence
246 pub fn operator_prec(op: ast::BinOp_) -> usize {
248 // 'as' sits here with 12
249 BiMul | BiDiv | BiRem => 11,
255 BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
261 /// Precedence of the `as` operator, which is a binary operator
262 /// not appearing in the prior table.
263 pub const AS_PREC: usize = 12;
265 pub fn empty_generics() -> Generics {
267 lifetimes: Vec::new(),
268 ty_params: OwnedSlice::empty(),
269 where_clause: WhereClause {
271 predicates: Vec::new(),
276 // ______________________________________________________________________
277 // Enumerating the IDs which appear in an AST
279 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
286 pub fn max() -> IdRange {
293 pub fn empty(&self) -> bool {
297 pub fn add(&mut self, id: NodeId) {
298 self.min = cmp::min(self.min, id);
299 self.max = cmp::max(self.max, id + 1);
303 pub trait IdVisitingOperation {
304 fn visit_id(&mut self, node_id: NodeId);
307 /// A visitor that applies its operation to all of the node IDs
308 /// in a visitable thing.
310 pub struct IdVisitor<'a, O:'a> {
311 pub operation: &'a mut O,
312 pub pass_through_items: bool,
313 pub visited_outermost: bool,
316 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
317 fn visit_generics_helper(&mut self, generics: &Generics) {
318 for type_parameter in generics.ty_params.iter() {
319 self.operation.visit_id(type_parameter.id)
321 for lifetime in &generics.lifetimes {
322 self.operation.visit_id(lifetime.lifetime.id)
327 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
328 fn visit_mod(&mut self,
332 self.operation.visit_id(node_id);
333 visit::walk_mod(self, module)
336 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
337 self.operation.visit_id(foreign_item.id);
338 visit::walk_foreign_item(self, foreign_item)
341 fn visit_item(&mut self, item: &Item) {
342 if !self.pass_through_items {
343 if self.visited_outermost {
346 self.visited_outermost = true
350 self.operation.visit_id(item.id);
352 ItemUse(ref view_path) => {
353 match view_path.node {
354 ViewPathSimple(_, _) |
355 ViewPathGlob(_) => {}
356 ViewPathList(_, ref paths) => {
358 self.operation.visit_id(path.node.id())
363 ItemEnum(ref enum_definition, _) => {
364 for variant in &enum_definition.variants {
365 self.operation.visit_id(variant.node.id)
371 visit::walk_item(self, item);
373 self.visited_outermost = false
376 fn visit_local(&mut self, local: &Local) {
377 self.operation.visit_id(local.id);
378 visit::walk_local(self, local)
381 fn visit_block(&mut self, block: &Block) {
382 self.operation.visit_id(block.id);
383 visit::walk_block(self, block)
386 fn visit_stmt(&mut self, statement: &Stmt) {
387 self.operation.visit_id(ast_util::stmt_id(statement));
388 visit::walk_stmt(self, statement)
391 fn visit_pat(&mut self, pattern: &Pat) {
392 self.operation.visit_id(pattern.id);
393 visit::walk_pat(self, pattern)
396 fn visit_expr(&mut self, expression: &Expr) {
397 self.operation.visit_id(expression.id);
398 visit::walk_expr(self, expression)
401 fn visit_ty(&mut self, typ: &Ty) {
402 self.operation.visit_id(typ.id);
403 visit::walk_ty(self, typ)
406 fn visit_generics(&mut self, generics: &Generics) {
407 self.visit_generics_helper(generics);
408 visit::walk_generics(self, generics)
411 fn visit_fn(&mut self,
412 function_kind: visit::FnKind<'v>,
413 function_declaration: &'v FnDecl,
417 if !self.pass_through_items {
418 match function_kind {
419 FnKind::Method(..) if self.visited_outermost => return,
420 FnKind::Method(..) => self.visited_outermost = true,
425 self.operation.visit_id(node_id);
427 match function_kind {
428 FnKind::ItemFn(_, generics, _, _, _, _) => {
429 self.visit_generics_helper(generics)
431 FnKind::Method(_, sig, _) => {
432 self.visit_generics_helper(&sig.generics)
434 FnKind::Closure => {}
437 for argument in &function_declaration.inputs {
438 self.operation.visit_id(argument.id)
443 function_declaration,
447 if !self.pass_through_items {
448 if let FnKind::Method(..) = function_kind {
449 self.visited_outermost = false;
454 fn visit_struct_field(&mut self, struct_field: &StructField) {
455 self.operation.visit_id(struct_field.node.id);
456 visit::walk_struct_field(self, struct_field)
459 fn visit_struct_def(&mut self,
460 struct_def: &StructDef,
464 self.operation.visit_id(id);
465 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
466 visit::walk_struct_def(self, struct_def);
469 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
470 self.operation.visit_id(ti.id);
471 visit::walk_trait_item(self, ti);
474 fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
475 self.operation.visit_id(ii.id);
476 visit::walk_impl_item(self, ii);
479 fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
480 self.operation.visit_id(lifetime.id);
483 fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
484 self.visit_lifetime_ref(&def.lifetime);
487 fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
488 self.operation.visit_id(trait_ref.ref_id);
489 visit::walk_trait_ref(self, trait_ref);
493 pub struct IdRangeComputingVisitor {
497 impl IdRangeComputingVisitor {
498 pub fn new() -> IdRangeComputingVisitor {
499 IdRangeComputingVisitor { result: IdRange::max() }
502 pub fn result(&self) -> IdRange {
507 impl IdVisitingOperation for IdRangeComputingVisitor {
508 fn visit_id(&mut self, id: NodeId) {
513 /// Computes the id range for a single fn body, ignoring nested items.
514 pub fn compute_id_range_for_fn_body(fk: FnKind,
521 let mut visitor = IdRangeComputingVisitor::new();
522 let mut id_visitor = IdVisitor {
523 operation: &mut visitor,
524 pass_through_items: false,
525 visited_outermost: false,
527 id_visitor.visit_fn(fk, decl, body, sp, id);
528 id_visitor.operation.result
531 /// Returns true if the given struct def is tuple-like; i.e. that its fields
533 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
534 struct_def.ctor_id.is_some()
537 /// Returns true if the given pattern consists solely of an identifier
538 /// and false otherwise.
539 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
541 ast::PatIdent(..) => true,
546 // are two paths equal when compared unhygienically?
547 // since I'm using this to replace ==, it seems appropriate
548 // to compare the span, global, etc. fields as well.
549 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
551 && (a.global == b.global)
552 && (segments_name_eq(&a.segments[..], &b.segments[..]))
555 // are two arrays of segments equal when compared unhygienically?
556 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
557 a.len() == b.len() &&
558 a.iter().zip(b).all(|(s, t)| {
559 s.identifier.name == t.identifier.name &&
560 // FIXME #7743: ident -> name problems in lifetime comparison?
561 // can types contain idents?
562 s.parameters == t.parameters
566 /// Returns true if this literal is a string and false otherwise.
567 pub fn lit_is_str(lit: &Lit) -> bool {
579 fn ident_to_segment(id : &Ident) -> PathSegment {
580 PathSegment {identifier: id.clone(),
581 parameters: PathParameters::none()}
584 #[test] fn idents_name_eq_test() {
585 assert!(segments_name_eq(
586 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
587 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
588 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
589 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));
590 assert!(!segments_name_eq(
591 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
592 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
593 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
594 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));