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) -> Option<NodeId> {
33 StmtDecl(_, id) => Some(id),
34 StmtExpr(_, id) => Some(id),
35 StmtSemi(_, id) => Some(id),
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 {
111 pub fn is_path(e: P<Expr>) -> bool {
112 match e.node { ExprPath(..) => true, _ => false }
115 /// Get a string representation of a signed int type, with its value.
116 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
117 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
127 // cast to a u64 so we can correctly print INT64_MIN. All integral types
128 // are parsed as u64, so we wouldn't want to print an extra negative
130 Some(n) => format!("{}{}", n as u64, s),
131 None => s.to_string()
135 pub fn int_ty_max(t: IntTy) -> u64 {
139 TyIs | TyI32 => 0x80000000, // actually ni about TyIs
140 TyI64 => 0x8000000000000000
144 /// Get a string representation of an unsigned int type, with its value.
145 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
146 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
156 Some(n) => format!("{}{}", n, s),
157 None => s.to_string()
161 pub fn uint_ty_max(t: UintTy) -> u64 {
165 TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
166 TyU64 => 0xffffffffffffffff
170 pub fn float_ty_to_string(t: FloatTy) -> String {
172 TyF32 => "f32".to_string(),
173 TyF64 => "f64".to_string(),
177 // convert a span and an identifier to the corresponding
179 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
185 identifier: identifier,
186 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
187 lifetimes: Vec::new(),
188 types: OwnedSlice::empty(),
189 bindings: OwnedSlice::empty(),
196 // If path is a single segment ident path, return that ident. Otherwise, return
198 pub fn path_to_ident(path: &Path) -> Option<Ident> {
199 if path.segments.len() != 1 {
203 let segment = &path.segments[0];
204 if !segment.parameters.is_empty() {
208 Some(segment.identifier)
211 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
214 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
219 /// Generate a "pretty" name for an `impl` from its type and trait.
220 /// This is designed so that symbols of `impl`'d methods give some
221 /// hint of where they came from, (previously they would all just be
222 /// listed as `__extensions__::method_name::hash`, with no indication
224 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
225 let mut pretty = match ty {
226 Some(t) => pprust::ty_to_string(t),
227 None => String::from("..")
231 Some(ref trait_ref) => {
233 pretty.push_str(&pprust::path_to_string(&trait_ref.path));
237 token::gensym_ident(&pretty[..])
240 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
241 match field.node.kind {
242 ast::NamedField(_, v) | ast::UnnamedField(v) => v
246 /// Maps a binary operator to its precedence
247 pub fn operator_prec(op: ast::BinOp_) -> usize {
249 // 'as' sits here with 12
250 BiMul | BiDiv | BiRem => 11,
256 BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
262 /// Precedence of the `as` operator, which is a binary operator
263 /// not appearing in the prior table.
264 pub const AS_PREC: usize = 12;
266 pub fn empty_generics() -> Generics {
268 lifetimes: Vec::new(),
269 ty_params: OwnedSlice::empty(),
270 where_clause: WhereClause {
272 predicates: Vec::new(),
277 // ______________________________________________________________________
278 // Enumerating the IDs which appear in an AST
280 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
287 pub fn max() -> IdRange {
294 pub fn empty(&self) -> bool {
298 pub fn add(&mut self, id: NodeId) {
299 self.min = cmp::min(self.min, id);
300 self.max = cmp::max(self.max, id + 1);
304 pub trait IdVisitingOperation {
305 fn visit_id(&mut self, node_id: NodeId);
308 /// A visitor that applies its operation to all of the node IDs
309 /// in a visitable thing.
311 pub struct IdVisitor<'a, O:'a> {
312 pub operation: &'a mut O,
313 pub pass_through_items: bool,
314 pub visited_outermost: bool,
317 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
318 fn visit_generics_helper(&mut self, generics: &Generics) {
319 for type_parameter in generics.ty_params.iter() {
320 self.operation.visit_id(type_parameter.id)
322 for lifetime in &generics.lifetimes {
323 self.operation.visit_id(lifetime.lifetime.id)
328 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
329 fn visit_mod(&mut self,
333 self.operation.visit_id(node_id);
334 visit::walk_mod(self, module)
337 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
338 self.operation.visit_id(foreign_item.id);
339 visit::walk_foreign_item(self, foreign_item)
342 fn visit_item(&mut self, item: &Item) {
343 if !self.pass_through_items {
344 if self.visited_outermost {
347 self.visited_outermost = true
351 self.operation.visit_id(item.id);
353 ItemUse(ref view_path) => {
354 match view_path.node {
355 ViewPathSimple(_, _) |
356 ViewPathGlob(_) => {}
357 ViewPathList(_, ref paths) => {
359 self.operation.visit_id(path.node.id())
364 ItemEnum(ref enum_definition, _) => {
365 for variant in &enum_definition.variants {
366 self.operation.visit_id(variant.node.id)
372 visit::walk_item(self, item);
374 self.visited_outermost = false
377 fn visit_local(&mut self, local: &Local) {
378 self.operation.visit_id(local.id);
379 visit::walk_local(self, local)
382 fn visit_block(&mut self, block: &Block) {
383 self.operation.visit_id(block.id);
384 visit::walk_block(self, block)
387 fn visit_stmt(&mut self, statement: &Stmt) {
389 .visit_id(ast_util::stmt_id(statement).expect("attempted to visit unexpanded stmt"));
390 visit::walk_stmt(self, statement)
393 fn visit_pat(&mut self, pattern: &Pat) {
394 self.operation.visit_id(pattern.id);
395 visit::walk_pat(self, pattern)
398 fn visit_expr(&mut self, expression: &Expr) {
399 self.operation.visit_id(expression.id);
400 visit::walk_expr(self, expression)
403 fn visit_ty(&mut self, typ: &Ty) {
404 self.operation.visit_id(typ.id);
405 visit::walk_ty(self, typ)
408 fn visit_generics(&mut self, generics: &Generics) {
409 self.visit_generics_helper(generics);
410 visit::walk_generics(self, generics)
413 fn visit_fn(&mut self,
414 function_kind: visit::FnKind<'v>,
415 function_declaration: &'v FnDecl,
419 if !self.pass_through_items {
420 match function_kind {
421 FnKind::Method(..) if self.visited_outermost => return,
422 FnKind::Method(..) => self.visited_outermost = true,
427 self.operation.visit_id(node_id);
429 match function_kind {
430 FnKind::ItemFn(_, generics, _, _, _, _) => {
431 self.visit_generics_helper(generics)
433 FnKind::Method(_, sig, _) => {
434 self.visit_generics_helper(&sig.generics)
436 FnKind::Closure => {}
439 for argument in &function_declaration.inputs {
440 self.operation.visit_id(argument.id)
445 function_declaration,
449 if !self.pass_through_items {
450 if let FnKind::Method(..) = function_kind {
451 self.visited_outermost = false;
456 fn visit_struct_field(&mut self, struct_field: &StructField) {
457 self.operation.visit_id(struct_field.node.id);
458 visit::walk_struct_field(self, struct_field)
461 fn visit_struct_def(&mut self,
462 struct_def: &StructDef,
466 self.operation.visit_id(id);
467 struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
468 visit::walk_struct_def(self, struct_def);
471 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
472 self.operation.visit_id(ti.id);
473 visit::walk_trait_item(self, ti);
476 fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
477 self.operation.visit_id(ii.id);
478 visit::walk_impl_item(self, ii);
481 fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
482 self.operation.visit_id(lifetime.id);
485 fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
486 self.visit_lifetime_ref(&def.lifetime);
489 fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
490 self.operation.visit_id(trait_ref.ref_id);
491 visit::walk_trait_ref(self, trait_ref);
495 pub struct IdRangeComputingVisitor {
499 impl IdRangeComputingVisitor {
500 pub fn new() -> IdRangeComputingVisitor {
501 IdRangeComputingVisitor { result: IdRange::max() }
504 pub fn result(&self) -> IdRange {
509 impl IdVisitingOperation for IdRangeComputingVisitor {
510 fn visit_id(&mut self, id: NodeId) {
515 /// Computes the id range for a single fn body, ignoring nested items.
516 pub fn compute_id_range_for_fn_body(fk: FnKind,
523 let mut visitor = IdRangeComputingVisitor::new();
524 let mut id_visitor = IdVisitor {
525 operation: &mut visitor,
526 pass_through_items: false,
527 visited_outermost: false,
529 id_visitor.visit_fn(fk, decl, body, sp, id);
530 id_visitor.operation.result
533 /// Returns true if the given struct def is tuple-like; i.e. that its fields
535 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
536 struct_def.ctor_id.is_some()
539 /// Returns true if the given pattern consists solely of an identifier
540 /// and false otherwise.
541 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
543 ast::PatIdent(..) => true,
548 // are two paths equal when compared unhygienically?
549 // since I'm using this to replace ==, it seems appropriate
550 // to compare the span, global, etc. fields as well.
551 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
553 && (a.global == b.global)
554 && (segments_name_eq(&a.segments[..], &b.segments[..]))
557 // are two arrays of segments equal when compared unhygienically?
558 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
559 a.len() == b.len() &&
560 a.iter().zip(b).all(|(s, t)| {
561 s.identifier.name == t.identifier.name &&
562 // FIXME #7743: ident -> name problems in lifetime comparison?
563 // can types contain idents?
564 s.parameters == t.parameters
568 /// Returns true if this literal is a string and false otherwise.
569 pub fn lit_is_str(lit: &Lit) -> bool {
581 fn ident_to_segment(id : &Ident) -> PathSegment {
582 PathSegment {identifier: id.clone(),
583 parameters: PathParameters::none()}
586 #[test] fn idents_name_eq_test() {
587 assert!(segments_name_eq(
588 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
589 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
590 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
591 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));
592 assert!(!segments_name_eq(
593 &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
594 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
595 &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
596 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));