1 extern crate rustc_ast;
2 extern crate rustc_data_structures;
3 extern crate rustc_span;
4 extern crate rustc_target;
5 
6 use std::mem;
7 
8 use rustc_ast::ast::{
9     AngleBracketedArg, AngleBracketedArgs, AnonConst, Arm, AssocItemKind, AssocTyConstraint,
10     AssocTyConstraintKind, Async, AttrId, AttrItem, AttrKind, AttrStyle, Attribute, BareFnTy,
11     BinOpKind, BindingMode, Block, BlockCheckMode, BorrowKind, CaptureBy, Const, Crate, CrateSugar,
12     Defaultness, EnumDef, Expr, ExprKind, Extern, Field, FieldPat, FloatTy, FnDecl, FnHeader,
13     FnRetTy, FnSig, ForeignItemKind, ForeignMod, GenericArg, GenericArgs, GenericBound,
14     GenericParam, GenericParamKind, Generics, GlobalAsm, ImplPolarity, InlineAsm, InlineAsmOperand,
15     InlineAsmOptions, InlineAsmRegOrRegClass, InlineAsmTemplatePiece, IntTy, IsAuto, Item,
16     ItemKind, Label, Lifetime, Lit, LitFloatType, LitIntType, LitKind, LlvmAsmDialect,
17     LlvmInlineAsm, LlvmInlineAsmOutput, Local, MacArgs, MacCall, MacDelimiter, MacStmtStyle,
18     MacroDef, Mod, Movability, MutTy, Mutability, NodeId, Param, ParenthesizedArgs, Pat, PatKind,
19     Path, PathSegment, PolyTraitRef, QSelf, RangeEnd, RangeLimits, RangeSyntax, Stmt, StmtKind,
20     StrLit, StrStyle, StructField, TraitBoundModifier, TraitObjectSyntax, TraitRef, Ty, TyKind,
21     UintTy, UnOp, Unsafe, UnsafeSource, UseTree, UseTreeKind, Variant, VariantData, VisibilityKind,
22     WhereBoundPredicate, WhereClause, WhereEqPredicate, WherePredicate, WhereRegionPredicate,
23 };
24 use rustc_ast::ptr::P;
25 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
26 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
27 use rustc_ast::util::comments;
28 use rustc_data_structures::sync::Lrc;
29 use rustc_data_structures::thin_vec::ThinVec;
30 use rustc_span::source_map::Spanned;
31 use rustc_span::symbol::Ident;
32 use rustc_span::{sym, Span, Symbol, SyntaxContext, DUMMY_SP};
33 
34 pub trait SpanlessEq {
eq(&self, other: &Self) -> bool35     fn eq(&self, other: &Self) -> bool;
36 }
37 
38 impl<T: SpanlessEq> SpanlessEq for P<T> {
eq(&self, other: &Self) -> bool39     fn eq(&self, other: &Self) -> bool {
40         SpanlessEq::eq(&**self, &**other)
41     }
42 }
43 
44 impl<T: SpanlessEq> SpanlessEq for Lrc<T> {
eq(&self, other: &Self) -> bool45     fn eq(&self, other: &Self) -> bool {
46         SpanlessEq::eq(&**self, &**other)
47     }
48 }
49 
50 impl<T: SpanlessEq> SpanlessEq for Option<T> {
eq(&self, other: &Self) -> bool51     fn eq(&self, other: &Self) -> bool {
52         match (self, other) {
53             (None, None) => true,
54             (Some(this), Some(other)) => SpanlessEq::eq(this, other),
55             _ => false,
56         }
57     }
58 }
59 
60 impl<T: SpanlessEq> SpanlessEq for Vec<T> {
eq(&self, other: &Self) -> bool61     fn eq(&self, other: &Self) -> bool {
62         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| SpanlessEq::eq(a, b))
63     }
64 }
65 
66 impl<T: SpanlessEq> SpanlessEq for ThinVec<T> {
eq(&self, other: &Self) -> bool67     fn eq(&self, other: &Self) -> bool {
68         self.len() == other.len()
69             && self
70                 .iter()
71                 .zip(other.iter())
72                 .all(|(a, b)| SpanlessEq::eq(a, b))
73     }
74 }
75 
76 impl<T: SpanlessEq> SpanlessEq for Spanned<T> {
eq(&self, other: &Self) -> bool77     fn eq(&self, other: &Self) -> bool {
78         SpanlessEq::eq(&self.node, &other.node)
79     }
80 }
81 
82 impl<A: SpanlessEq, B: SpanlessEq> SpanlessEq for (A, B) {
eq(&self, other: &Self) -> bool83     fn eq(&self, other: &Self) -> bool {
84         SpanlessEq::eq(&self.0, &other.0) && SpanlessEq::eq(&self.1, &other.1)
85     }
86 }
87 
88 impl<A: SpanlessEq, B: SpanlessEq, C: SpanlessEq> SpanlessEq for (A, B, C) {
eq(&self, other: &Self) -> bool89     fn eq(&self, other: &Self) -> bool {
90         SpanlessEq::eq(&self.0, &other.0)
91             && SpanlessEq::eq(&self.1, &other.1)
92             && SpanlessEq::eq(&self.2, &other.2)
93     }
94 }
95 
96 macro_rules! spanless_eq_true {
97     ($name:ident) => {
98         impl SpanlessEq for $name {
99             fn eq(&self, _other: &Self) -> bool {
100                 true
101             }
102         }
103     };
104 }
105 
106 spanless_eq_true!(Span);
107 spanless_eq_true!(DelimSpan);
108 spanless_eq_true!(AttrId);
109 spanless_eq_true!(NodeId);
110 spanless_eq_true!(SyntaxContext);
111 
112 macro_rules! spanless_eq_partial_eq {
113     ($name:ident) => {
114         impl SpanlessEq for $name {
115             fn eq(&self, other: &Self) -> bool {
116                 PartialEq::eq(self, other)
117             }
118         }
119     };
120 }
121 
122 spanless_eq_partial_eq!(bool);
123 spanless_eq_partial_eq!(u8);
124 spanless_eq_partial_eq!(u16);
125 spanless_eq_partial_eq!(u128);
126 spanless_eq_partial_eq!(usize);
127 spanless_eq_partial_eq!(char);
128 spanless_eq_partial_eq!(String);
129 spanless_eq_partial_eq!(Symbol);
130 spanless_eq_partial_eq!(DelimToken);
131 spanless_eq_partial_eq!(InlineAsmOptions);
132 
133 macro_rules! spanless_eq_struct {
134     {
135         $name:ident $(<$param:ident>)?;
136         $([$field:ident $other:ident])*
137         $(![$ignore:ident])*
138     } => {
139         impl $(<$param: SpanlessEq>)* SpanlessEq for $name $(<$param>)* {
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 $(<$param:ident>)?;
150         $([$field:ident $other:ident])*
151         $next:ident
152         $($rest:ident)*
153         $(!$ignore:ident)*
154     } => {
155         spanless_eq_struct! {
156             $name $(<$param>)*;
157             $([$field $other])*
158             [$next other]
159             $($rest)*
160             $(!$ignore)*
161         }
162     };
163 
164     {
165         $name:ident $(<$param:ident>)?;
166         $([$field:ident $other:ident])*
167         $(![$ignore:ident])*
168         !$next:ident
169         $(!$rest:ident)*
170     } => {
171         spanless_eq_struct! {
172             $name $(<$param>)*;
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);
267 spanless_eq_struct!(AnonConst; id value);
268 spanless_eq_struct!(Arm; attrs pat guard body span id is_placeholder);
269 spanless_eq_struct!(AssocTyConstraint; id ident kind span);
270 spanless_eq_struct!(AttrItem; path args);
271 spanless_eq_struct!(Attribute; kind id style span);
272 spanless_eq_struct!(BareFnTy; unsafety ext generic_params decl);
273 spanless_eq_struct!(Block; stmts id rules span);
274 spanless_eq_struct!(Crate; module attrs span proc_macros);
275 spanless_eq_struct!(EnumDef; variants);
276 spanless_eq_struct!(Expr; id kind span attrs !tokens);
277 spanless_eq_struct!(Field; attrs id span ident expr is_shorthand is_placeholder);
278 spanless_eq_struct!(FieldPat; ident pat is_shorthand attrs id span is_placeholder);
279 spanless_eq_struct!(FnDecl; inputs output);
280 spanless_eq_struct!(FnHeader; constness asyncness unsafety ext);
281 spanless_eq_struct!(FnSig; header decl);
282 spanless_eq_struct!(ForeignMod; abi items);
283 spanless_eq_struct!(GenericParam; id ident attrs bounds is_placeholder kind);
284 spanless_eq_struct!(Generics; params where_clause span);
285 spanless_eq_struct!(GlobalAsm; asm);
286 spanless_eq_struct!(InlineAsm; template operands options line_spans);
287 spanless_eq_struct!(Item<K>; attrs id span vis ident kind !tokens);
288 spanless_eq_struct!(Label; ident);
289 spanless_eq_struct!(Lifetime; id ident);
290 spanless_eq_struct!(Lit; token kind span);
291 spanless_eq_struct!(LlvmInlineAsm; asm asm_str_style outputs inputs clobbers volatile alignstack dialect);
292 spanless_eq_struct!(LlvmInlineAsmOutput; constraint expr is_rw is_indirect);
293 spanless_eq_struct!(Local; pat ty init id span attrs);
294 spanless_eq_struct!(MacCall; path args prior_type_ascription);
295 spanless_eq_struct!(MacroDef; body macro_rules);
296 spanless_eq_struct!(Mod; inner items inline);
297 spanless_eq_struct!(MutTy; ty mutbl);
298 spanless_eq_struct!(Param; attrs ty pat id span is_placeholder);
299 spanless_eq_struct!(ParenthesizedArgs; span inputs output);
300 spanless_eq_struct!(Pat; id kind 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 kind span);
306 spanless_eq_struct!(StrLit; style symbol suffix span symbol_unescaped);
307 spanless_eq_struct!(StructField; attrs id span vis ident ty is_placeholder);
308 spanless_eq_struct!(Token; kind span);
309 spanless_eq_struct!(TraitRef; path ref_id);
310 spanless_eq_struct!(Ty; id kind span);
311 spanless_eq_struct!(UseTree; prefix kind span);
312 spanless_eq_struct!(Variant; attrs id span vis ident data disr_expr is_placeholder);
313 spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds);
314 spanless_eq_struct!(WhereClause; has_where_token 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!(AngleBracketedArg; Arg(0) Constraint(0));
318 spanless_eq_enum!(AssocItemKind; Const(0 1 2) Fn(0 1 2 3) TyAlias(0 1 2 3) MacCall(0));
319 spanless_eq_enum!(AssocTyConstraintKind; Equality(ty) Bound(bounds));
320 spanless_eq_enum!(Async; Yes(span closure_id return_impl_trait_id) No);
321 spanless_eq_enum!(AttrKind; Normal(0) DocComment(0));
322 spanless_eq_enum!(AttrStyle; Outer Inner);
323 spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt);
324 spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0));
325 spanless_eq_enum!(BlockCheckMode; Default Unsafe(0));
326 spanless_eq_enum!(BorrowKind; Ref Raw);
327 spanless_eq_enum!(CaptureBy; Value Ref);
328 spanless_eq_enum!(Const; Yes(0) No);
329 spanless_eq_enum!(CrateSugar; PubCrate JustCrate);
330 spanless_eq_enum!(Defaultness; Default(0) Final);
331 spanless_eq_enum!(Extern; None Implicit Explicit(0));
332 spanless_eq_enum!(FloatTy; F32 F64);
333 spanless_eq_enum!(FnRetTy; Default(0) Ty(0));
334 spanless_eq_enum!(ForeignItemKind; Static(0 1 2) Fn(0 1 2 3) TyAlias(0 1 2 3) MacCall(0));
335 spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0));
336 spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0));
337 spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0));
338 spanless_eq_enum!(GenericParamKind; Lifetime Type(default) Const(ty kw_span));
339 spanless_eq_enum!(ImplPolarity; Positive Negative(0));
340 spanless_eq_enum!(InlineAsmRegOrRegClass; Reg(0) RegClass(0));
341 spanless_eq_enum!(InlineAsmTemplatePiece; String(0) Placeholder(operand_idx modifier span));
342 spanless_eq_enum!(IntTy; Isize I8 I16 I32 I64 I128);
343 spanless_eq_enum!(IsAuto; Yes No);
344 spanless_eq_enum!(LitFloatType; Suffixed(0) Unsuffixed);
345 spanless_eq_enum!(LitIntType; Signed(0) Unsigned(0) Unsuffixed);
346 spanless_eq_enum!(LlvmAsmDialect; Att Intel);
347 spanless_eq_enum!(MacArgs; Empty Delimited(0 1 2) Eq(0 1));
348 spanless_eq_enum!(MacDelimiter; Parenthesis Bracket Brace);
349 spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces);
350 spanless_eq_enum!(Movability; Static Movable);
351 spanless_eq_enum!(Mutability; Mut Not);
352 spanless_eq_enum!(RangeEnd; Included(0) Excluded);
353 spanless_eq_enum!(RangeLimits; HalfOpen Closed);
354 spanless_eq_enum!(StmtKind; Local(0) Item(0) Expr(0) Semi(0) Empty MacCall(0));
355 spanless_eq_enum!(StrStyle; Cooked Raw(0));
356 spanless_eq_enum!(TokenTree; Token(0) Delimited(0 1 2));
357 spanless_eq_enum!(TraitBoundModifier; None Maybe MaybeConst MaybeConstMaybe);
358 spanless_eq_enum!(TraitObjectSyntax; Dyn None);
359 spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128);
360 spanless_eq_enum!(UnOp; Deref Not Neg);
361 spanless_eq_enum!(Unsafe; Yes(0) No);
362 spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided);
363 spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob);
364 spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0));
365 spanless_eq_enum!(VisibilityKind; Public Crate(0) Restricted(path id) Inherited);
366 spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0));
367 spanless_eq_enum!(ExprKind; Box(0) Array(0) Call(0 1) MethodCall(0 1 2) Tup(0)
368     Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1) Let(0 1) If(0 1 2)
369     While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1) Closure(0 1 2 3 4 5)
370     Block(0 1) Async(0 1 2) Await(0) TryBlock(0) Assign(0 1 2) AssignOp(0 1 2)
371     Field(0 1) Index(0 1) Range(0 1 2) Path(0 1) AddrOf(0 1 2) Break(0 1)
372     Continue(0) Ret(0) InlineAsm(0) LlvmInlineAsm(0) MacCall(0) Struct(0 1 2)
373     Repeat(0 1) Paren(0) Try(0) Yield(0) Err);
374 spanless_eq_enum!(InlineAsmOperand; In(reg expr) Out(reg late expr)
375     InOut(reg late expr) SplitInOut(reg late in_expr out_expr) Const(expr)
376     Sym(expr));
377 spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1 2)
378     Fn(0 1 2 3) Mod(0) ForeignMod(0) GlobalAsm(0) TyAlias(0 1 2 3) Enum(0 1)
379     Struct(0 1) Union(0 1) Trait(0 1 2 3 4) TraitAlias(0 1)
380     Impl(unsafety polarity defaultness constness generics of_trait self_ty items)
381     MacCall(0) MacroDef(0));
382 spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1)
383     Float(0 1) Bool(0) Err(0));
384 spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2) TupleStruct(0 1)
385     Or(0) Path(0 1) Tuple(0) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest
386     Paren(0) MacCall(0));
387 spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Rptr(0 1) BareFn(0) Never
388     Tup(0) Path(0 1) TraitObject(0 1) ImplTrait(0 1) Paren(0) Typeof(0) Infer
389     ImplicitSelf MacCall(0) Err CVarArgs);
390 
391 impl SpanlessEq for Ident {
eq(&self, other: &Self) -> bool392     fn eq(&self, other: &Self) -> bool {
393         self.as_str() == other.as_str()
394     }
395 }
396 
397 // Give up on comparing literals inside of macros because there are so many
398 // equivalent representations of the same literal; they are tested elsewhere
399 impl SpanlessEq for token::Lit {
eq(&self, other: &Self) -> bool400     fn eq(&self, other: &Self) -> bool {
401         mem::discriminant(self) == mem::discriminant(other)
402     }
403 }
404 
405 impl SpanlessEq for RangeSyntax {
eq(&self, _other: &Self) -> bool406     fn eq(&self, _other: &Self) -> bool {
407         match self {
408             RangeSyntax::DotDotDot | RangeSyntax::DotDotEq => true,
409         }
410     }
411 }
412 
413 impl SpanlessEq for TokenKind {
eq(&self, other: &Self) -> bool414     fn eq(&self, other: &Self) -> bool {
415         match (self, other) {
416             (TokenKind::Literal(this), TokenKind::Literal(other)) => SpanlessEq::eq(this, other),
417             (TokenKind::DotDotEq, _) | (TokenKind::DotDotDot, _) => match other {
418                 TokenKind::DotDotEq | TokenKind::DotDotDot => true,
419                 _ => false,
420             },
421             _ => self == other,
422         }
423     }
424 }
425 
426 impl SpanlessEq for TokenStream {
eq(&self, other: &Self) -> bool427     fn eq(&self, other: &Self) -> bool {
428         SpanlessEq::eq(&expand_tts(self), &expand_tts(other))
429     }
430 }
431 
expand_tts(tts: &TokenStream) -> Vec<TokenTree>432 fn expand_tts(tts: &TokenStream) -> Vec<TokenTree> {
433     let mut tokens = Vec::new();
434     for tt in tts.clone().into_trees() {
435         let c = match tt {
436             TokenTree::Token(Token {
437                 kind: TokenKind::DocComment(c),
438                 ..
439             }) => c,
440             _ => {
441                 tokens.push(tt);
442                 continue;
443             }
444         };
445         let contents = comments::strip_doc_comment_decoration(c);
446         let style = comments::doc_comment_style(c);
447         tokens.push(TokenTree::token(TokenKind::Pound, DUMMY_SP));
448         if style == AttrStyle::Inner {
449             tokens.push(TokenTree::token(TokenKind::Not, DUMMY_SP));
450         }
451         let lit = token::Lit {
452             kind: token::LitKind::Str,
453             symbol: Symbol::intern(&contents),
454             suffix: None,
455         };
456         let tts = vec![
457             TokenTree::token(TokenKind::Ident(sym::doc, false), DUMMY_SP),
458             TokenTree::token(TokenKind::Eq, DUMMY_SP),
459             TokenTree::token(TokenKind::Literal(lit), DUMMY_SP),
460         ];
461         tokens.push(TokenTree::Delimited(
462             DelimSpan::dummy(),
463             DelimToken::Bracket,
464             tts.into_iter().collect::<TokenStream>().into(),
465         ));
466     }
467     tokens
468 }
469