1 extern crate rustc_data_structures;
2 extern crate rustc_target;
3 extern crate syntax;
4 extern crate syntax_pos;
5 
6 use std::mem;
7 
8 use self::rustc_data_structures::sync::Lrc;
9 use self::rustc_data_structures::thin_vec::ThinVec;
10 use self::rustc_target::abi::FloatTy;
11 use self::rustc_target::spec::abi::Abi;
12 use self::syntax::ast::{
13     AngleBracketedArgs, AnonConst, Arg, Arm, AsmDialect, AssocTyConstraint, AssocTyConstraintKind,
14     AttrId, AttrStyle, Attribute, BareFnTy, BinOpKind, BindingMode, Block, BlockCheckMode,
15     CaptureBy, Constness, Crate, CrateSugar, Defaultness, EnumDef, Expr, ExprKind, Field, FieldPat,
16     FnDecl, FnHeader, ForeignItem, ForeignItemKind, ForeignMod, FunctionRetTy, GenericArg,
17     GenericArgs, GenericBound, GenericParam, GenericParamKind, Generics, GlobalAsm, Ident,
18     ImplItem, ImplItemKind, ImplPolarity, InlineAsm, InlineAsmOutput, IntTy, IsAsync, IsAuto, Item,
19     ItemKind, Label, Lifetime, Lit, LitIntType, LitKind, Local, Mac, MacDelimiter, MacStmtStyle,
20     MacroDef, MethodSig, Mod, Movability, MutTy, Mutability, NodeId, ParenthesizedArgs, Pat,
21     PatKind, Path, PathSegment, PolyTraitRef, QSelf, RangeEnd, RangeLimits, RangeSyntax, Stmt,
22     StmtKind, StrStyle, StructField, TraitBoundModifier, TraitItem, TraitItemKind,
23     TraitObjectSyntax, TraitRef, Ty, TyKind, UintTy, UnOp, UnsafeSource, Unsafety, UseTree,
24     UseTreeKind, Variant, VariantData, VisibilityKind, WhereBoundPredicate, WhereClause,
25     WhereEqPredicate, WherePredicate, WhereRegionPredicate,
26 };
27 use self::syntax::parse::lexer::comments;
28 use self::syntax::parse::token::{self, DelimToken, Token, TokenKind};
29 use self::syntax::ptr::P;
30 use self::syntax::source_map::Spanned;
31 use self::syntax::symbol::{sym, Symbol};
32 use self::syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
33 use self::syntax_pos::{Span, SyntaxContext, DUMMY_SP};
34 
35 pub trait SpanlessEq {
eq(&self, other: &Self) -> bool36     fn eq(&self, other: &Self) -> bool;
37 }
38 
39 impl<T: SpanlessEq> SpanlessEq for P<T> {
eq(&self, other: &Self) -> bool40     fn eq(&self, other: &Self) -> bool {
41         SpanlessEq::eq(&**self, &**other)
42     }
43 }
44 
45 impl<T: SpanlessEq> SpanlessEq for Lrc<T> {
eq(&self, other: &Self) -> bool46     fn eq(&self, other: &Self) -> bool {
47         SpanlessEq::eq(&**self, &**other)
48     }
49 }
50 
51 impl<T: SpanlessEq> SpanlessEq for Option<T> {
eq(&self, other: &Self) -> bool52     fn eq(&self, other: &Self) -> bool {
53         match (self, other) {
54             (None, None) => true,
55             (Some(this), Some(other)) => SpanlessEq::eq(this, other),
56             _ => false,
57         }
58     }
59 }
60 
61 impl<T: SpanlessEq> SpanlessEq for Vec<T> {
eq(&self, other: &Self) -> bool62     fn eq(&self, other: &Self) -> bool {
63         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| SpanlessEq::eq(a, b))
64     }
65 }
66 
67 impl<T: SpanlessEq> SpanlessEq for ThinVec<T> {
eq(&self, other: &Self) -> bool68     fn eq(&self, other: &Self) -> bool {
69         self.len() == other.len()
70             && self
71                 .iter()
72                 .zip(other.iter())
73                 .all(|(a, b)| SpanlessEq::eq(a, b))
74     }
75 }
76 
77 impl<T: SpanlessEq> SpanlessEq for Spanned<T> {
eq(&self, other: &Self) -> bool78     fn eq(&self, other: &Self) -> bool {
79         SpanlessEq::eq(&self.node, &other.node)
80     }
81 }
82 
83 impl<A: SpanlessEq, B: SpanlessEq> SpanlessEq for (A, B) {
eq(&self, other: &Self) -> bool84     fn eq(&self, other: &Self) -> bool {
85         SpanlessEq::eq(&self.0, &other.0) && SpanlessEq::eq(&self.1, &other.1)
86     }
87 }
88 
89 impl<A: SpanlessEq, B: SpanlessEq, C: SpanlessEq> SpanlessEq for (A, B, C) {
eq(&self, other: &Self) -> bool90     fn eq(&self, other: &Self) -> bool {
91         SpanlessEq::eq(&self.0, &other.0)
92             && SpanlessEq::eq(&self.1, &other.1)
93             && SpanlessEq::eq(&self.2, &other.2)
94     }
95 }
96 
97 macro_rules! spanless_eq_true {
98     ($name:ident) => {
99         impl SpanlessEq for $name {
100             fn eq(&self, _other: &Self) -> bool {
101                 true
102             }
103         }
104     };
105 }
106 
107 spanless_eq_true!(Span);
108 spanless_eq_true!(DelimSpan);
109 spanless_eq_true!(AttrId);
110 spanless_eq_true!(NodeId);
111 spanless_eq_true!(SyntaxContext);
112 
113 macro_rules! spanless_eq_partial_eq {
114     ($name:ident) => {
115         impl SpanlessEq for $name {
116             fn eq(&self, other: &Self) -> bool {
117                 PartialEq::eq(self, other)
118             }
119         }
120     };
121 }
122 
123 spanless_eq_partial_eq!(bool);
124 spanless_eq_partial_eq!(u8);
125 spanless_eq_partial_eq!(u16);
126 spanless_eq_partial_eq!(u128);
127 spanless_eq_partial_eq!(usize);
128 spanless_eq_partial_eq!(char);
129 spanless_eq_partial_eq!(Symbol);
130 spanless_eq_partial_eq!(Abi);
131 spanless_eq_partial_eq!(DelimToken);
132 
133 macro_rules! spanless_eq_struct {
134     {
135         $name:ident;
136         $([$field:ident $other:ident])*
137         $(![$ignore:ident])*
138     } => {
139         impl SpanlessEq for $name {
140             fn eq(&self, other: &Self) -> bool {
141                 let $name { $($field,)* $($ignore: _,)* } = self;
142                 let $name { $($field: $other,)* $($ignore: _,)* } = other;
143                 $(SpanlessEq::eq($field, $other))&&*
144             }
145         }
146     };
147 
148     {
149         $name:ident;
150         $([$field:ident $other:ident])*
151         $next:ident
152         $($rest:ident)*
153         $(!$ignore:ident)*
154     } => {
155         spanless_eq_struct! {
156             $name;
157             $([$field $other])*
158             [$next other]
159             $($rest)*
160             $(!$ignore)*
161         }
162     };
163 
164     {
165         $name:ident;
166         $([$field:ident $other:ident])*
167         $(![$ignore:ident])*
168         !$next:ident
169         $(!$rest:ident)*
170     } => {
171         spanless_eq_struct! {
172             $name;
173             $([$field $other])*
174             $(![$ignore])*
175             ![$next]
176             $(!$rest)*
177         }
178     };
179 }
180 
181 macro_rules! spanless_eq_enum {
182     {
183         $name:ident;
184         $([$variant:ident $([$field:tt $this:ident $other:ident])*])*
185     } => {
186         impl SpanlessEq for $name {
187             fn eq(&self, other: &Self) -> bool {
188                 match self {
189                     $(
190                         $name::$variant { .. } => {}
191                     )*
192                 }
193                 #[allow(unreachable_patterns)]
194                 match (self, other) {
195                     $(
196                         (
197                             $name::$variant { $($field: $this),* },
198                             $name::$variant { $($field: $other),* },
199                         ) => {
200                             true $(&& SpanlessEq::eq($this, $other))*
201                         }
202                     )*
203                     _ => false,
204                 }
205             }
206         }
207     };
208 
209     {
210         $name:ident;
211         $([$variant:ident $($fields:tt)*])*
212         $next:ident [$($named:tt)*] ( $i:tt $($field:tt)* )
213         $($rest:tt)*
214     } => {
215         spanless_eq_enum! {
216             $name;
217             $([$variant $($fields)*])*
218             $next [$($named)* [$i this other]] ( $($field)* )
219             $($rest)*
220         }
221     };
222 
223     {
224         $name:ident;
225         $([$variant:ident $($fields:tt)*])*
226         $next:ident [$($named:tt)*] ()
227         $($rest:tt)*
228     } => {
229         spanless_eq_enum! {
230             $name;
231             $([$variant $($fields)*])*
232             [$next $($named)*]
233             $($rest)*
234         }
235     };
236 
237     {
238         $name:ident;
239         $([$variant:ident $($fields:tt)*])*
240         $next:ident ( $($field:tt)* )
241         $($rest:tt)*
242     } => {
243         spanless_eq_enum! {
244             $name;
245             $([$variant $($fields)*])*
246             $next [] ( $($field)* )
247             $($rest)*
248         }
249     };
250 
251     {
252         $name:ident;
253         $([$variant:ident $($fields:tt)*])*
254         $next:ident
255         $($rest:tt)*
256     } => {
257         spanless_eq_enum! {
258             $name;
259             $([$variant $($fields)*])*
260             [$next]
261             $($rest)*
262         }
263     };
264 }
265 
266 spanless_eq_struct!(AngleBracketedArgs; span args constraints);
267 spanless_eq_struct!(AnonConst; id value);
268 spanless_eq_struct!(Arg; attrs ty pat id span);
269 spanless_eq_struct!(Arm; attrs pats guard body span id);
270 spanless_eq_struct!(AssocTyConstraint; id ident kind span);
271 spanless_eq_struct!(Attribute; id style path tokens span !is_sugared_doc);
272 spanless_eq_struct!(BareFnTy; unsafety abi generic_params decl);
273 spanless_eq_struct!(Block; stmts id rules span);
274 spanless_eq_struct!(Crate; module attrs span);
275 spanless_eq_struct!(EnumDef; variants);
276 spanless_eq_struct!(Expr; id node span attrs);
277 spanless_eq_struct!(Field; ident expr span is_shorthand attrs id);
278 spanless_eq_struct!(FieldPat; ident pat is_shorthand attrs id span);
279 spanless_eq_struct!(FnDecl; inputs output c_variadic);
280 spanless_eq_struct!(FnHeader; constness asyncness unsafety abi);
281 spanless_eq_struct!(ForeignItem; ident attrs node id span vis);
282 spanless_eq_struct!(ForeignMod; abi items);
283 spanless_eq_struct!(GenericParam; id ident attrs bounds kind);
284 spanless_eq_struct!(Generics; params where_clause span);
285 spanless_eq_struct!(GlobalAsm; asm);
286 spanless_eq_struct!(ImplItem; id ident vis defaultness attrs generics node span !tokens);
287 spanless_eq_struct!(InlineAsm; asm asm_str_style outputs inputs clobbers volatile alignstack dialect);
288 spanless_eq_struct!(InlineAsmOutput; constraint expr is_rw is_indirect);
289 spanless_eq_struct!(Item; ident attrs id node vis span !tokens);
290 spanless_eq_struct!(Label; ident);
291 spanless_eq_struct!(Lifetime; id ident);
292 spanless_eq_struct!(Lit; token node span);
293 spanless_eq_struct!(Local; pat ty init id span attrs);
294 spanless_eq_struct!(Mac; path delim tts span prior_type_ascription);
295 spanless_eq_struct!(MacroDef; tokens legacy);
296 spanless_eq_struct!(MethodSig; header decl);
297 spanless_eq_struct!(Mod; inner items inline);
298 spanless_eq_struct!(MutTy; ty mutbl);
299 spanless_eq_struct!(ParenthesizedArgs; span inputs output);
300 spanless_eq_struct!(Pat; id node span);
301 spanless_eq_struct!(Path; span segments);
302 spanless_eq_struct!(PathSegment; ident id args);
303 spanless_eq_struct!(PolyTraitRef; bound_generic_params trait_ref span);
304 spanless_eq_struct!(QSelf; ty path_span position);
305 spanless_eq_struct!(Stmt; id node span);
306 spanless_eq_struct!(StructField; span ident vis id ty attrs);
307 spanless_eq_struct!(Token; kind span);
308 spanless_eq_struct!(TraitItem; id ident attrs generics node span !tokens);
309 spanless_eq_struct!(TraitRef; path ref_id);
310 spanless_eq_struct!(Ty; id node span);
311 spanless_eq_struct!(UseTree; prefix kind span);
312 spanless_eq_struct!(Variant; ident attrs id data disr_expr span);
313 spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds);
314 spanless_eq_struct!(WhereClause; predicates span);
315 spanless_eq_struct!(WhereEqPredicate; id span lhs_ty rhs_ty);
316 spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds);
317 spanless_eq_enum!(AsmDialect; Att Intel);
318 spanless_eq_enum!(AssocTyConstraintKind; Equality(ty) Bound(bounds));
319 spanless_eq_enum!(AttrStyle; Outer Inner);
320 spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt);
321 spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0));
322 spanless_eq_enum!(BlockCheckMode; Default Unsafe(0));
323 spanless_eq_enum!(CaptureBy; Value Ref);
324 spanless_eq_enum!(Constness; Const NotConst);
325 spanless_eq_enum!(CrateSugar; PubCrate JustCrate);
326 spanless_eq_enum!(Defaultness; Default Final);
327 spanless_eq_enum!(FloatTy; F32 F64);
328 spanless_eq_enum!(ForeignItemKind; Fn(0 1) Static(0 1) Ty Macro(0));
329 spanless_eq_enum!(FunctionRetTy; Default(0) Ty(0));
330 spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0));
331 spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0));
332 spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0));
333 spanless_eq_enum!(GenericParamKind; Lifetime Type(default) Const(ty));
334 spanless_eq_enum!(ImplItemKind; Const(0 1) Method(0 1) TyAlias(0) OpaqueTy(0) Macro(0));
335 spanless_eq_enum!(ImplPolarity; Positive Negative);
336 spanless_eq_enum!(IntTy; Isize I8 I16 I32 I64 I128);
337 spanless_eq_enum!(IsAsync; Async(closure_id return_impl_trait_id) NotAsync);
338 spanless_eq_enum!(IsAuto; Yes No);
339 spanless_eq_enum!(LitIntType; Signed(0) Unsigned(0) Unsuffixed);
340 spanless_eq_enum!(MacDelimiter; Parenthesis Bracket Brace);
341 spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces);
342 spanless_eq_enum!(Movability; Static Movable);
343 spanless_eq_enum!(Mutability; Mutable Immutable);
344 spanless_eq_enum!(RangeEnd; Included(0) Excluded);
345 spanless_eq_enum!(RangeLimits; HalfOpen Closed);
346 spanless_eq_enum!(StmtKind; Local(0) Item(0) Expr(0) Semi(0) Mac(0));
347 spanless_eq_enum!(StrStyle; Cooked Raw(0));
348 spanless_eq_enum!(TokenTree; Token(0) Delimited(0 1 2));
349 spanless_eq_enum!(TraitBoundModifier; None Maybe);
350 spanless_eq_enum!(TraitItemKind; Const(0 1) Method(0 1) Type(0 1) Macro(0));
351 spanless_eq_enum!(TraitObjectSyntax; Dyn None);
352 spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128);
353 spanless_eq_enum!(UnOp; Deref Not Neg);
354 spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided);
355 spanless_eq_enum!(Unsafety; Unsafe Normal);
356 spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob);
357 spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0));
358 spanless_eq_enum!(VisibilityKind; Public Crate(0) Restricted(path id) Inherited);
359 spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0));
360 spanless_eq_enum!(ExprKind; Box(0) Array(0) Call(0 1) MethodCall(0 1) Tup(0)
361     Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1) Let(0 1) If(0 1 2)
362     While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1) Closure(0 1 2 3 4 5)
363     Block(0 1) Async(0 1 2) Await(0) TryBlock(0) Assign(0 1) AssignOp(0 1 2)
364     Field(0 1) Index(0 1) Range(0 1 2) Path(0 1) AddrOf(0 1) Break(0 1)
365     Continue(0) Ret(0) InlineAsm(0) Mac(0) Struct(0 1 2) Repeat(0 1) Paren(0)
366     Try(0) Yield(0) Err);
367 spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1)
368     Fn(0 1 2 3) Mod(0) ForeignMod(0) GlobalAsm(0) TyAlias(0 1) OpaqueTy(0 1)
369     Enum(0 1) Struct(0 1) Union(0 1) Trait(0 1 2 3 4) TraitAlias(0 1)
370     Impl(0 1 2 3 4 5 6) Mac(0) MacroDef(0));
371 spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1)
372     Float(0 1) FloatUnsuffixed(0) Bool(0) Err(0));
373 spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2) TupleStruct(0 1)
374     Or(0) Path(0 1) Tuple(0) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest
375     Paren(0) Mac(0));
376 spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Rptr(0 1) BareFn(0) Never
377     Tup(0) Path(0 1) TraitObject(0 1) ImplTrait(0 1) Paren(0) Typeof(0) Infer
378     ImplicitSelf Mac(0) Err CVarArgs);
379 
380 impl SpanlessEq for Ident {
eq(&self, other: &Self) -> bool381     fn eq(&self, other: &Self) -> bool {
382         self.as_str() == other.as_str()
383     }
384 }
385 
386 // Give up on comparing literals inside of macros because there are so many
387 // equivalent representations of the same literal; they are tested elsewhere
388 impl SpanlessEq for token::Lit {
eq(&self, other: &Self) -> bool389     fn eq(&self, other: &Self) -> bool {
390         mem::discriminant(self) == mem::discriminant(other)
391     }
392 }
393 
394 impl SpanlessEq for RangeSyntax {
eq(&self, _other: &Self) -> bool395     fn eq(&self, _other: &Self) -> bool {
396         match self {
397             RangeSyntax::DotDotDot | RangeSyntax::DotDotEq => true,
398         }
399     }
400 }
401 
402 impl SpanlessEq for TokenKind {
eq(&self, other: &Self) -> bool403     fn eq(&self, other: &Self) -> bool {
404         match (self, other) {
405             (TokenKind::Literal(this), TokenKind::Literal(other)) => SpanlessEq::eq(this, other),
406             (TokenKind::DotDotEq, _) | (TokenKind::DotDotDot, _) => match other {
407                 TokenKind::DotDotEq | TokenKind::DotDotDot => true,
408                 _ => false,
409             },
410             _ => self == other,
411         }
412     }
413 }
414 
415 impl SpanlessEq for TokenStream {
eq(&self, other: &Self) -> bool416     fn eq(&self, other: &Self) -> bool {
417         SpanlessEq::eq(&expand_tts(self), &expand_tts(other))
418     }
419 }
420 
expand_tts(tts: &TokenStream) -> Vec<TokenTree>421 fn expand_tts(tts: &TokenStream) -> Vec<TokenTree> {
422     let mut tokens = Vec::new();
423     for tt in tts.clone().into_trees() {
424         let c = match tt {
425             TokenTree::Token(Token {
426                 kind: TokenKind::DocComment(c),
427                 ..
428             }) => c,
429             _ => {
430                 tokens.push(tt);
431                 continue;
432             }
433         };
434         let contents = comments::strip_doc_comment_decoration(&c.as_str());
435         let style = comments::doc_comment_style(&c.as_str());
436         tokens.push(TokenTree::token(TokenKind::Pound, DUMMY_SP));
437         if style == AttrStyle::Inner {
438             tokens.push(TokenTree::token(TokenKind::Not, DUMMY_SP));
439         }
440         let lit = token::Lit {
441             kind: token::LitKind::Str,
442             symbol: Symbol::intern(&contents),
443             suffix: None,
444         };
445         let tts = vec![
446             TokenTree::token(TokenKind::Ident(sym::doc, false), DUMMY_SP),
447             TokenTree::token(TokenKind::Eq, DUMMY_SP),
448             TokenTree::token(TokenKind::Literal(lit), DUMMY_SP),
449         ];
450         tokens.push(TokenTree::Delimited(
451             DelimSpan::dummy(),
452             DelimToken::Bracket,
453             tts.into_iter().collect::<TokenStream>().into(),
454         ));
455     }
456     tokens
457 }
458