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 {
110 pub fn is_path(e: P<Expr>) -> bool {
111 match e.node { ExprPath(..) => true, _ => false }
114 pub fn int_ty_to_string(t: IntTy) -> &'static str {
124 pub fn int_val_to_string(t: IntTy, val: i64) -> String {
125 // cast to a u64 so we can correctly print INT64_MIN. All integral types
126 // are parsed as u64, so we wouldn't want to print an extra negative
128 format!("{}{}", val as u64, int_ty_to_string(t))
131 pub fn int_ty_max(t: IntTy) -> u64 {
135 TyIs | TyI32 => 0x80000000, // actually ni about TyIs
136 TyI64 => 0x8000000000000000
140 pub fn uint_ty_to_string(t: UintTy) -> &'static str {
150 pub fn uint_val_to_string(t: UintTy, val: u64) -> String {
151 format!("{}{}", val, uint_ty_to_string(t))
154 pub fn uint_ty_max(t: UintTy) -> u64 {
158 TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
159 TyU64 => 0xffffffffffffffff
163 pub fn float_ty_to_string(t: FloatTy) -> &'static str {
170 // convert a span and an identifier to the corresponding
172 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
178 identifier: identifier,
179 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
180 lifetimes: Vec::new(),
181 types: OwnedSlice::empty(),
182 bindings: OwnedSlice::empty(),
189 // If path is a single segment ident path, return that ident. Otherwise, return
191 pub fn path_to_ident(path: &Path) -> Option<Ident> {
192 if path.segments.len() != 1 {
196 let segment = &path.segments[0];
197 if !segment.parameters.is_empty() {
201 Some(segment.identifier)
204 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
207 node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
212 /// Generate a "pretty" name for an `impl` from its type and trait.
213 /// This is designed so that symbols of `impl`'d methods give some
214 /// hint of where they came from, (previously they would all just be
215 /// listed as `__extensions__::method_name::hash`, with no indication
217 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
218 let mut pretty = match ty {
219 Some(t) => pprust::ty_to_string(t),
220 None => String::from("..")
224 Some(ref trait_ref) => {
226 pretty.push_str(&pprust::path_to_string(&trait_ref.path));
230 token::gensym_ident(&pretty[..])
233 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
234 match field.node.kind {
235 ast::NamedField(_, v) | ast::UnnamedField(v) => v
239 pub fn empty_generics() -> Generics {
241 lifetimes: Vec::new(),
242 ty_params: OwnedSlice::empty(),
243 where_clause: WhereClause {
245 predicates: Vec::new(),
250 // ______________________________________________________________________
251 // Enumerating the IDs which appear in an AST
253 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
260 pub fn max() -> IdRange {
267 pub fn empty(&self) -> bool {
271 pub fn add(&mut self, id: NodeId) {
272 self.min = cmp::min(self.min, id);
273 self.max = cmp::max(self.max, id + 1);
277 pub trait IdVisitingOperation {
278 fn visit_id(&mut self, node_id: NodeId);
281 /// A visitor that applies its operation to all of the node IDs
282 /// in a visitable thing.
284 pub struct IdVisitor<'a, O:'a> {
285 pub operation: &'a mut O,
286 pub visited_outermost: bool,
289 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
290 fn visit_generics_helper(&mut self, generics: &Generics) {
291 for type_parameter in generics.ty_params.iter() {
292 self.operation.visit_id(type_parameter.id)
294 for lifetime in &generics.lifetimes {
295 self.operation.visit_id(lifetime.lifetime.id)
300 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
301 fn visit_mod(&mut self,
305 self.operation.visit_id(node_id);
306 visit::walk_mod(self, module)
309 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
310 self.operation.visit_id(foreign_item.id);
311 visit::walk_foreign_item(self, foreign_item)
314 fn visit_item(&mut self, item: &Item) {
315 if self.visited_outermost {
318 self.visited_outermost = true
321 self.operation.visit_id(item.id);
323 ItemUse(ref view_path) => {
324 match view_path.node {
325 ViewPathSimple(_, _) |
326 ViewPathGlob(_) => {}
327 ViewPathList(_, ref paths) => {
329 self.operation.visit_id(path.node.id())
337 visit::walk_item(self, item);
339 self.visited_outermost = false
342 fn visit_local(&mut self, local: &Local) {
343 self.operation.visit_id(local.id);
344 visit::walk_local(self, local)
347 fn visit_block(&mut self, block: &Block) {
348 self.operation.visit_id(block.id);
349 visit::walk_block(self, block)
352 fn visit_stmt(&mut self, statement: &Stmt) {
354 .visit_id(ast_util::stmt_id(statement).expect("attempted to visit unexpanded stmt"));
355 visit::walk_stmt(self, statement)
358 fn visit_pat(&mut self, pattern: &Pat) {
359 self.operation.visit_id(pattern.id);
360 visit::walk_pat(self, pattern)
363 fn visit_expr(&mut self, expression: &Expr) {
364 self.operation.visit_id(expression.id);
365 visit::walk_expr(self, expression)
368 fn visit_ty(&mut self, typ: &Ty) {
369 self.operation.visit_id(typ.id);
370 visit::walk_ty(self, typ)
373 fn visit_generics(&mut self, generics: &Generics) {
374 self.visit_generics_helper(generics);
375 visit::walk_generics(self, generics)
378 fn visit_fn(&mut self,
379 function_kind: visit::FnKind<'v>,
380 function_declaration: &'v FnDecl,
384 match function_kind {
385 FnKind::Method(..) if self.visited_outermost => return,
386 FnKind::Method(..) => self.visited_outermost = true,
390 self.operation.visit_id(node_id);
392 match function_kind {
393 FnKind::ItemFn(_, generics, _, _, _, _) => {
394 self.visit_generics_helper(generics)
396 FnKind::Method(_, sig, _) => {
397 self.visit_generics_helper(&sig.generics)
399 FnKind::Closure => {}
402 for argument in &function_declaration.inputs {
403 self.operation.visit_id(argument.id)
408 function_declaration,
412 if let FnKind::Method(..) = function_kind {
413 self.visited_outermost = false;
417 fn visit_struct_field(&mut self, struct_field: &StructField) {
418 self.operation.visit_id(struct_field.node.id);
419 visit::walk_struct_field(self, struct_field)
422 fn visit_variant_data(&mut self,
423 struct_def: &VariantData,
428 self.operation.visit_id(struct_def.id());
429 visit::walk_struct_def(self, struct_def);
432 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
433 self.operation.visit_id(ti.id);
434 visit::walk_trait_item(self, ti);
437 fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
438 self.operation.visit_id(ii.id);
439 visit::walk_impl_item(self, ii);
442 fn visit_lifetime(&mut self, lifetime: &Lifetime) {
443 self.operation.visit_id(lifetime.id);
446 fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
447 self.visit_lifetime(&def.lifetime);
450 fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
451 self.operation.visit_id(trait_ref.ref_id);
452 visit::walk_trait_ref(self, trait_ref);
456 pub struct IdRangeComputingVisitor {
460 impl IdRangeComputingVisitor {
461 pub fn new() -> IdRangeComputingVisitor {
462 IdRangeComputingVisitor { result: IdRange::max() }
465 pub fn result(&self) -> IdRange {
470 impl IdVisitingOperation for IdRangeComputingVisitor {
471 fn visit_id(&mut self, id: NodeId) {
476 /// Computes the id range for a single fn body, ignoring nested items.
477 pub fn compute_id_range_for_fn_body(fk: FnKind,
484 let mut visitor = IdRangeComputingVisitor::new();
485 let mut id_visitor = IdVisitor {
486 operation: &mut visitor,
487 visited_outermost: false,
489 id_visitor.visit_fn(fk, decl, body, sp, id);
490 id_visitor.operation.result
493 /// Returns true if the given pattern consists solely of an identifier
494 /// and false otherwise.
495 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
497 ast::PatIdent(..) => true,
502 // are two paths equal when compared unhygienically?
503 // since I'm using this to replace ==, it seems appropriate
504 // to compare the span, global, etc. fields as well.
505 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
507 && (a.global == b.global)
508 && (segments_name_eq(&a.segments[..], &b.segments[..]))
511 // are two arrays of segments equal when compared unhygienically?
512 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
513 a.len() == b.len() &&
514 a.iter().zip(b).all(|(s, t)| {
515 s.identifier.name == t.identifier.name &&
516 // FIXME #7743: ident -> name problems in lifetime comparison?
517 // can types contain idents?
518 s.parameters == t.parameters
522 /// Returns true if this literal is a string and false otherwise.
523 pub fn lit_is_str(lit: &Lit) -> bool {
535 fn ident_to_segment(id: Ident) -> PathSegment {
536 PathSegment {identifier: id,
537 parameters: PathParameters::none()}
540 #[test] fn idents_name_eq_test() {
541 assert!(segments_name_eq(
542 &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
543 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
544 &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(78),SyntaxContext(182))]
545 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));
546 assert!(!segments_name_eq(
547 &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
548 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
549 &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(77),SyntaxContext(182))]
550 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));