1 extern crate rustc_ast;
2 extern crate rustc_data_structures;
3 extern crate rustc_span;
4 
5 use rustc_ast::ast::{
6     AngleBracketedArg, AngleBracketedArgs, AnonConst, Arm, AssocItemKind, AssocTyConstraint,
7     AssocTyConstraintKind, Async, AttrId, AttrItem, AttrKind, AttrStyle, Attribute, BareFnTy,
8     BinOpKind, BindingMode, Block, BlockCheckMode, BorrowKind, CaptureBy, Const, Crate, CrateSugar,
9     Defaultness, EnumDef, Expr, ExprField, ExprKind, Extern, FieldDef, FloatTy, FnDecl, FnHeader,
10     FnKind, FnRetTy, FnSig, ForeignItemKind, ForeignMod, GenericArg, GenericArgs, GenericBound,
11     GenericParam, GenericParamKind, Generics, ImplKind, ImplPolarity, Inline, InlineAsm,
12     InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass, InlineAsmTemplatePiece, IntTy,
13     IsAuto, Item, ItemKind, Label, Lifetime, Lit, LitFloatType, LitIntType, LitKind,
14     LlvmAsmDialect, LlvmInlineAsm, LlvmInlineAsmOutput, Local, LocalKind, MacArgs, MacCall,
15     MacCallStmt, MacDelimiter, MacStmtStyle, MacroDef, ModKind, Movability, MutTy, Mutability,
16     NodeId, Param, ParenthesizedArgs, Pat, PatField, PatKind, Path, PathSegment, PolyTraitRef,
17     QSelf, RangeEnd, RangeLimits, RangeSyntax, Stmt, StmtKind, StrLit, StrStyle, StructExpr,
18     StructRest, TraitBoundModifier, TraitKind, TraitObjectSyntax, TraitRef, Ty, TyAliasKind,
19     TyKind, UintTy, UnOp, Unsafe, UnsafeSource, UseTree, UseTreeKind, Variant, VariantData,
20     Visibility, VisibilityKind, WhereBoundPredicate, WhereClause, WhereEqPredicate, WherePredicate,
21     WhereRegionPredicate,
22 };
23 use rustc_ast::ptr::P;
24 use rustc_ast::token::{self, CommentKind, DelimToken, Nonterminal, Token, TokenKind};
25 use rustc_ast::tokenstream::{
26     AttrAnnotatedTokenStream, AttrAnnotatedTokenTree, AttributesData, DelimSpan, LazyTokenStream,
27     Spacing, TokenStream, TokenTree,
28 };
29 use rustc_data_structures::sync::Lrc;
30 use rustc_data_structures::thin_vec::ThinVec;
31 use rustc_span::source_map::Spanned;
32 use rustc_span::symbol::{sym, Ident};
33 use rustc_span::{Span, Symbol, SyntaxContext, DUMMY_SP};
34 
35 pub trait SpanlessEq {
eq(&self, other: &Self) -> bool36     fn eq(&self, other: &Self) -> bool;
37 }
38 
39 impl<T: ?Sized + SpanlessEq> SpanlessEq for Box<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 P<T> {
eq(&self, other: &Self) -> bool46     fn eq(&self, other: &Self) -> bool {
47         SpanlessEq::eq(&**self, &**other)
48     }
49 }
50 
51 impl<T: ?Sized + SpanlessEq> SpanlessEq for Lrc<T> {
eq(&self, other: &Self) -> bool52     fn eq(&self, other: &Self) -> bool {
53         SpanlessEq::eq(&**self, &**other)
54     }
55 }
56 
57 impl<T: SpanlessEq> SpanlessEq for Option<T> {
eq(&self, other: &Self) -> bool58     fn eq(&self, other: &Self) -> bool {
59         match (self, other) {
60             (None, None) => true,
61             (Some(this), Some(other)) => SpanlessEq::eq(this, other),
62             _ => false,
63         }
64     }
65 }
66 
67 impl<T: SpanlessEq> SpanlessEq for [T] {
eq(&self, other: &Self) -> bool68     fn eq(&self, other: &Self) -> bool {
69         self.len() == other.len() && self.iter().zip(other).all(|(a, b)| SpanlessEq::eq(a, b))
70     }
71 }
72 
73 impl<T: SpanlessEq> SpanlessEq for Vec<T> {
eq(&self, other: &Self) -> bool74     fn eq(&self, other: &Self) -> bool {
75         <[T] as SpanlessEq>::eq(self, other)
76     }
77 }
78 
79 impl<T: SpanlessEq> SpanlessEq for ThinVec<T> {
eq(&self, other: &Self) -> bool80     fn eq(&self, other: &Self) -> bool {
81         self.len() == other.len()
82             && self
83                 .iter()
84                 .zip(other.iter())
85                 .all(|(a, b)| SpanlessEq::eq(a, b))
86     }
87 }
88 
89 impl<T: SpanlessEq> SpanlessEq for Spanned<T> {
eq(&self, other: &Self) -> bool90     fn eq(&self, other: &Self) -> bool {
91         SpanlessEq::eq(&self.node, &other.node)
92     }
93 }
94 
95 impl<A: SpanlessEq, B: SpanlessEq> SpanlessEq for (A, B) {
eq(&self, other: &Self) -> bool96     fn eq(&self, other: &Self) -> bool {
97         SpanlessEq::eq(&self.0, &other.0) && SpanlessEq::eq(&self.1, &other.1)
98     }
99 }
100 
101 impl<A: SpanlessEq, B: SpanlessEq, C: SpanlessEq> SpanlessEq for (A, B, C) {
eq(&self, other: &Self) -> bool102     fn eq(&self, other: &Self) -> bool {
103         SpanlessEq::eq(&self.0, &other.0)
104             && SpanlessEq::eq(&self.1, &other.1)
105             && SpanlessEq::eq(&self.2, &other.2)
106     }
107 }
108 
109 macro_rules! spanless_eq_true {
110     ($name:ty) => {
111         impl SpanlessEq for $name {
112             fn eq(&self, _other: &Self) -> bool {
113                 true
114             }
115         }
116     };
117 }
118 
119 spanless_eq_true!(Span);
120 spanless_eq_true!(DelimSpan);
121 spanless_eq_true!(AttrId);
122 spanless_eq_true!(NodeId);
123 spanless_eq_true!(SyntaxContext);
124 spanless_eq_true!(Spacing);
125 
126 macro_rules! spanless_eq_partial_eq {
127     ($name:ty) => {
128         impl SpanlessEq for $name {
129             fn eq(&self, other: &Self) -> bool {
130                 PartialEq::eq(self, other)
131             }
132         }
133     };
134 }
135 
136 spanless_eq_partial_eq!(bool);
137 spanless_eq_partial_eq!(u8);
138 spanless_eq_partial_eq!(u16);
139 spanless_eq_partial_eq!(u128);
140 spanless_eq_partial_eq!(usize);
141 spanless_eq_partial_eq!(char);
142 spanless_eq_partial_eq!(String);
143 spanless_eq_partial_eq!(Symbol);
144 spanless_eq_partial_eq!(CommentKind);
145 spanless_eq_partial_eq!(DelimToken);
146 spanless_eq_partial_eq!(InlineAsmOptions);
147 spanless_eq_partial_eq!(token::LitKind);
148 
149 macro_rules! spanless_eq_struct {
150     {
151         $($name:ident)::+ $(<$param:ident>)?
152         $([$field:tt $this:ident $other:ident])*
153         $(![$ignore:tt])*;
154     } => {
155         impl $(<$param: SpanlessEq>)* SpanlessEq for $($name)::+ $(<$param>)* {
156             fn eq(&self, other: &Self) -> bool {
157                 let $($name)::+ { $($field: $this,)* $($ignore: _,)* } = self;
158                 let $($name)::+ { $($field: $other,)* $($ignore: _,)* } = other;
159                 true $(&& SpanlessEq::eq($this, $other))*
160             }
161         }
162     };
163 
164     {
165         $($name:ident)::+ $(<$param:ident>)?
166         $([$field:tt $this:ident $other:ident])*
167         $(![$ignore:tt])*;
168         !$next:tt
169         $($rest:tt)*
170     } => {
171         spanless_eq_struct! {
172             $($name)::+ $(<$param>)*
173             $([$field $this $other])*
174             $(![$ignore])*
175             ![$next];
176             $($rest)*
177         }
178     };
179 
180     {
181         $($name:ident)::+ $(<$param:ident>)?
182         $([$field:tt $this:ident $other:ident])*
183         $(![$ignore:tt])*;
184         $next:tt
185         $($rest:tt)*
186     } => {
187         spanless_eq_struct! {
188             $($name)::+ $(<$param>)*
189             $([$field $this $other])*
190             [$next this other]
191             $(![$ignore])*;
192             $($rest)*
193         }
194     };
195 }
196 
197 macro_rules! spanless_eq_enum {
198     {
199         $($name:ident)::+;
200         $([$($variant:ident)::+; $([$field:tt $this:ident $other:ident])* $(![$ignore:tt])*])*
201     } => {
202         impl SpanlessEq for $($name)::+ {
203             fn eq(&self, other: &Self) -> bool {
204                 match self {
205                     $(
206                         $($variant)::+ { .. } => {}
207                     )*
208                 }
209                 #[allow(unreachable_patterns)]
210                 match (self, other) {
211                     $(
212                         (
213                             $($variant)::+ { $($field: $this,)* $($ignore: _,)* },
214                             $($variant)::+ { $($field: $other,)* $($ignore: _,)* },
215                         ) => {
216                             true $(&& SpanlessEq::eq($this, $other))*
217                         }
218                     )*
219                     _ => false,
220                 }
221             }
222         }
223     };
224 
225     {
226         $($name:ident)::+;
227         $([$($variant:ident)::+; $($fields:tt)*])*
228         $next:ident [$([$($named:tt)*])* $(![$ignore:tt])*] (!$i:tt $($field:tt)*)
229         $($rest:tt)*
230     } => {
231         spanless_eq_enum! {
232             $($name)::+;
233             $([$($variant)::+; $($fields)*])*
234             $next [$([$($named)*])* $(![$ignore])* ![$i]] ($($field)*)
235             $($rest)*
236         }
237     };
238 
239     {
240         $($name:ident)::+;
241         $([$($variant:ident)::+; $($fields:tt)*])*
242         $next:ident [$([$($named:tt)*])* $(![$ignore:tt])*] ($i:tt $($field:tt)*)
243         $($rest:tt)*
244     } => {
245         spanless_eq_enum! {
246             $($name)::+;
247             $([$($variant)::+; $($fields)*])*
248             $next [$([$($named)*])* [$i this other] $(![$ignore])*] ($($field)*)
249             $($rest)*
250         }
251     };
252 
253     {
254         $($name:ident)::+;
255         $([$($variant:ident)::+; $($fields:tt)*])*
256         $next:ident [$($named:tt)*] ()
257         $($rest:tt)*
258     } => {
259         spanless_eq_enum! {
260             $($name)::+;
261             $([$($variant)::+; $($fields)*])*
262             [$($name)::+::$next; $($named)*]
263             $($rest)*
264         }
265     };
266 
267     {
268         $($name:ident)::+;
269         $([$($variant:ident)::+; $($fields:tt)*])*
270         $next:ident ($($field:tt)*)
271         $($rest:tt)*
272     } => {
273         spanless_eq_enum! {
274             $($name)::+;
275             $([$($variant)::+; $($fields)*])*
276             $next [] ($($field)*)
277             $($rest)*
278         }
279     };
280 
281     {
282         $($name:ident)::+;
283         $([$($variant:ident)::+; $($fields:tt)*])*
284         $next:ident
285         $($rest:tt)*
286     } => {
287         spanless_eq_enum! {
288             $($name)::+;
289             $([$($variant)::+; $($fields)*])*
290             [$($name)::+::$next;]
291             $($rest)*
292         }
293     };
294 }
295 
296 spanless_eq_struct!(AngleBracketedArgs; span args);
297 spanless_eq_struct!(AnonConst; id value);
298 spanless_eq_struct!(Arm; attrs pat guard body span id is_placeholder);
299 spanless_eq_struct!(AssocTyConstraint; id ident gen_args kind span);
300 spanless_eq_struct!(AttrAnnotatedTokenStream; 0);
301 spanless_eq_struct!(AttrItem; path args tokens);
302 spanless_eq_struct!(Attribute; kind id style span);
303 spanless_eq_struct!(AttributesData; attrs tokens);
304 spanless_eq_struct!(BareFnTy; unsafety ext generic_params decl);
305 spanless_eq_struct!(Block; stmts id rules span tokens);
306 spanless_eq_struct!(Crate; attrs items span proc_macros);
307 spanless_eq_struct!(EnumDef; variants);
308 spanless_eq_struct!(Expr; id kind span attrs !tokens);
309 spanless_eq_struct!(ExprField; attrs id span ident expr is_shorthand is_placeholder);
310 spanless_eq_struct!(FieldDef; attrs id span vis ident ty is_placeholder);
311 spanless_eq_struct!(FnDecl; inputs output);
312 spanless_eq_struct!(FnHeader; constness asyncness unsafety ext);
313 spanless_eq_struct!(FnKind; 0 1 2 3);
314 spanless_eq_struct!(FnSig; header decl span);
315 spanless_eq_struct!(ForeignMod; unsafety abi items);
316 spanless_eq_struct!(GenericParam; id ident attrs bounds is_placeholder kind);
317 spanless_eq_struct!(Generics; params where_clause span);
318 spanless_eq_struct!(ImplKind; unsafety polarity defaultness constness generics of_trait self_ty items);
319 spanless_eq_struct!(InlineAsm; template template_strs operands clobber_abi options line_spans);
320 spanless_eq_struct!(Item<K>; attrs id span vis ident kind !tokens);
321 spanless_eq_struct!(Label; ident);
322 spanless_eq_struct!(Lifetime; id ident);
323 spanless_eq_struct!(Lit; token kind span);
324 spanless_eq_struct!(LlvmInlineAsm; asm asm_str_style outputs inputs clobbers volatile alignstack dialect);
325 spanless_eq_struct!(LlvmInlineAsmOutput; constraint expr is_rw is_indirect);
326 spanless_eq_struct!(Local; pat ty kind id span attrs !tokens);
327 spanless_eq_struct!(MacCall; path args prior_type_ascription);
328 spanless_eq_struct!(MacCallStmt; mac style attrs tokens);
329 spanless_eq_struct!(MacroDef; body macro_rules);
330 spanless_eq_struct!(MutTy; ty mutbl);
331 spanless_eq_struct!(ParenthesizedArgs; span inputs inputs_span output);
332 spanless_eq_struct!(Pat; id kind span tokens);
333 spanless_eq_struct!(PatField; ident pat is_shorthand attrs id span is_placeholder);
334 spanless_eq_struct!(Path; span segments tokens);
335 spanless_eq_struct!(PathSegment; ident id args);
336 spanless_eq_struct!(PolyTraitRef; bound_generic_params trait_ref span);
337 spanless_eq_struct!(QSelf; ty path_span position);
338 spanless_eq_struct!(Stmt; id kind span);
339 spanless_eq_struct!(StrLit; style symbol suffix span symbol_unescaped);
340 spanless_eq_struct!(StructExpr; qself path fields rest);
341 spanless_eq_struct!(Token; kind span);
342 spanless_eq_struct!(TraitKind; 0 1 2 3 4);
343 spanless_eq_struct!(TraitRef; path ref_id);
344 spanless_eq_struct!(Ty; id kind span tokens);
345 spanless_eq_struct!(TyAliasKind; 0 1 2 3);
346 spanless_eq_struct!(UseTree; prefix kind span);
347 spanless_eq_struct!(Variant; attrs id span !vis ident data disr_expr is_placeholder);
348 spanless_eq_struct!(Visibility; kind span tokens);
349 spanless_eq_struct!(WhereBoundPredicate; span bound_generic_params bounded_ty bounds);
350 spanless_eq_struct!(WhereClause; has_where_token predicates span);
351 spanless_eq_struct!(WhereEqPredicate; id span lhs_ty rhs_ty);
352 spanless_eq_struct!(WhereRegionPredicate; span lifetime bounds);
353 spanless_eq_struct!(token::Lit; kind symbol suffix);
354 spanless_eq_enum!(AngleBracketedArg; Arg(0) Constraint(0));
355 spanless_eq_enum!(AssocItemKind; Const(0 1 2) Fn(0) TyAlias(0) MacCall(0));
356 spanless_eq_enum!(AssocTyConstraintKind; Equality(ty) Bound(bounds));
357 spanless_eq_enum!(Async; Yes(span closure_id return_impl_trait_id) No);
358 spanless_eq_enum!(AttrAnnotatedTokenTree; Token(0) Delimited(0 1 2) Attributes(0));
359 spanless_eq_enum!(AttrStyle; Outer Inner);
360 spanless_eq_enum!(BinOpKind; Add Sub Mul Div Rem And Or BitXor BitAnd BitOr Shl Shr Eq Lt Le Ne Ge Gt);
361 spanless_eq_enum!(BindingMode; ByRef(0) ByValue(0));
362 spanless_eq_enum!(BlockCheckMode; Default Unsafe(0));
363 spanless_eq_enum!(BorrowKind; Ref Raw);
364 spanless_eq_enum!(CaptureBy; Value Ref);
365 spanless_eq_enum!(Const; Yes(0) No);
366 spanless_eq_enum!(CrateSugar; PubCrate JustCrate);
367 spanless_eq_enum!(Defaultness; Default(0) Final);
368 spanless_eq_enum!(Extern; None Implicit Explicit(0));
369 spanless_eq_enum!(FloatTy; F32 F64);
370 spanless_eq_enum!(FnRetTy; Default(0) Ty(0));
371 spanless_eq_enum!(ForeignItemKind; Static(0 1 2) Fn(0) TyAlias(0) MacCall(0));
372 spanless_eq_enum!(GenericArg; Lifetime(0) Type(0) Const(0));
373 spanless_eq_enum!(GenericArgs; AngleBracketed(0) Parenthesized(0));
374 spanless_eq_enum!(GenericBound; Trait(0 1) Outlives(0));
375 spanless_eq_enum!(GenericParamKind; Lifetime Type(default) Const(ty kw_span default));
376 spanless_eq_enum!(ImplPolarity; Positive Negative(0));
377 spanless_eq_enum!(Inline; Yes No);
378 spanless_eq_enum!(InlineAsmRegOrRegClass; Reg(0) RegClass(0));
379 spanless_eq_enum!(InlineAsmTemplatePiece; String(0) Placeholder(operand_idx modifier span));
380 spanless_eq_enum!(IntTy; Isize I8 I16 I32 I64 I128);
381 spanless_eq_enum!(IsAuto; Yes No);
382 spanless_eq_enum!(LitFloatType; Suffixed(0) Unsuffixed);
383 spanless_eq_enum!(LitIntType; Signed(0) Unsigned(0) Unsuffixed);
384 spanless_eq_enum!(LlvmAsmDialect; Att Intel);
385 spanless_eq_enum!(LocalKind; Decl Init(0) InitElse(0 1));
386 spanless_eq_enum!(MacArgs; Empty Delimited(0 1 2) Eq(0 1));
387 spanless_eq_enum!(MacDelimiter; Parenthesis Bracket Brace);
388 spanless_eq_enum!(MacStmtStyle; Semicolon Braces NoBraces);
389 spanless_eq_enum!(ModKind; Loaded(0 1 2) Unloaded);
390 spanless_eq_enum!(Movability; Static Movable);
391 spanless_eq_enum!(Mutability; Mut Not);
392 spanless_eq_enum!(RangeEnd; Included(0) Excluded);
393 spanless_eq_enum!(RangeLimits; HalfOpen Closed);
394 spanless_eq_enum!(StmtKind; Local(0) Item(0) Expr(0) Semi(0) Empty MacCall(0));
395 spanless_eq_enum!(StrStyle; Cooked Raw(0));
396 spanless_eq_enum!(StructRest; Base(0) Rest(0) None);
397 spanless_eq_enum!(TokenTree; Token(0) Delimited(0 1 2));
398 spanless_eq_enum!(TraitBoundModifier; None Maybe MaybeConst MaybeConstMaybe);
399 spanless_eq_enum!(TraitObjectSyntax; Dyn None);
400 spanless_eq_enum!(UintTy; Usize U8 U16 U32 U64 U128);
401 spanless_eq_enum!(UnOp; Deref Not Neg);
402 spanless_eq_enum!(Unsafe; Yes(0) No);
403 spanless_eq_enum!(UnsafeSource; CompilerGenerated UserProvided);
404 spanless_eq_enum!(UseTreeKind; Simple(0 1 2) Nested(0) Glob);
405 spanless_eq_enum!(VariantData; Struct(0 1) Tuple(0 1) Unit(0));
406 spanless_eq_enum!(VisibilityKind; Public Crate(0) Restricted(path id) Inherited);
407 spanless_eq_enum!(WherePredicate; BoundPredicate(0) RegionPredicate(0) EqPredicate(0));
408 spanless_eq_enum!(ExprKind; Box(0) Array(0) ConstBlock(0) Call(0 1)
409     MethodCall(0 1 2) Tup(0) Binary(0 1 2) Unary(0 1) Lit(0) Cast(0 1) Type(0 1)
410     Let(0 1 2) If(0 1 2) While(0 1 2) ForLoop(0 1 2 3) Loop(0 1) Match(0 1)
411     Closure(0 1 2 3 4 5) Block(0 1) Async(0 1 2) Await(0) TryBlock(0)
412     Assign(0 1 2) AssignOp(0 1 2) Field(0 1) Index(0 1) Underscore Range(0 1 2)
413     Path(0 1) AddrOf(0 1 2) Break(0 1) Continue(0) Ret(0) InlineAsm(0)
414     LlvmInlineAsm(0) MacCall(0) Struct(0) Repeat(0 1) Paren(0) Try(0) Yield(0)
415     Err);
416 spanless_eq_enum!(InlineAsmOperand; In(reg expr) Out(reg late expr)
417     InOut(reg late expr) SplitInOut(reg late in_expr out_expr) Const(anon_const)
418     Sym(expr));
419 spanless_eq_enum!(ItemKind; ExternCrate(0) Use(0) Static(0 1 2) Const(0 1 2)
420     Fn(0) Mod(0 1) ForeignMod(0) GlobalAsm(0) TyAlias(0) Enum(0 1) Struct(0 1)
421     Union(0 1) Trait(0) TraitAlias(0 1) Impl(0) MacCall(0) MacroDef(0));
422 spanless_eq_enum!(LitKind; Str(0 1) ByteStr(0) Byte(0) Char(0) Int(0 1)
423     Float(0 1) Bool(0) Err(0));
424 spanless_eq_enum!(PatKind; Wild Ident(0 1 2) Struct(0 1 2 3) TupleStruct(0 1 2)
425     Or(0) Path(0 1) Tuple(0) Box(0) Ref(0 1) Lit(0) Range(0 1 2) Slice(0) Rest
426     Paren(0) MacCall(0));
427 spanless_eq_enum!(TyKind; Slice(0) Array(0 1) Ptr(0) Rptr(0 1) BareFn(0) Never
428     Tup(0) AnonymousStruct(0 1) AnonymousUnion(0 1) Path(0 1) TraitObject(0 1)
429     ImplTrait(0 1) Paren(0) Typeof(0) Infer ImplicitSelf MacCall(0) Err
430     CVarArgs);
431 
432 impl SpanlessEq for Ident {
eq(&self, other: &Self) -> bool433     fn eq(&self, other: &Self) -> bool {
434         self.as_str() == other.as_str()
435     }
436 }
437 
438 impl SpanlessEq for RangeSyntax {
eq(&self, _other: &Self) -> bool439     fn eq(&self, _other: &Self) -> bool {
440         match self {
441             RangeSyntax::DotDotDot | RangeSyntax::DotDotEq => true,
442         }
443     }
444 }
445 
446 impl SpanlessEq for Param {
eq(&self, other: &Self) -> bool447     fn eq(&self, other: &Self) -> bool {
448         let Param {
449             attrs,
450             ty,
451             pat,
452             id,
453             span: _,
454             is_placeholder,
455         } = self;
456         let Param {
457             attrs: attrs2,
458             ty: ty2,
459             pat: pat2,
460             id: id2,
461             span: _,
462             is_placeholder: is_placeholder2,
463         } = other;
464         SpanlessEq::eq(id, id2)
465             && SpanlessEq::eq(is_placeholder, is_placeholder2)
466             && (matches!(ty.kind, TyKind::Err)
467                 || matches!(ty2.kind, TyKind::Err)
468                 || SpanlessEq::eq(attrs, attrs2)
469                     && SpanlessEq::eq(ty, ty2)
470                     && SpanlessEq::eq(pat, pat2))
471     }
472 }
473 
474 impl SpanlessEq for TokenKind {
eq(&self, other: &Self) -> bool475     fn eq(&self, other: &Self) -> bool {
476         match (self, other) {
477             (TokenKind::Literal(this), TokenKind::Literal(other)) => SpanlessEq::eq(this, other),
478             (TokenKind::DotDotEq, _) | (TokenKind::DotDotDot, _) => match other {
479                 TokenKind::DotDotEq | TokenKind::DotDotDot => true,
480                 _ => false,
481             },
482             (TokenKind::Interpolated(this), TokenKind::Interpolated(other)) => {
483                 match (this.as_ref(), other.as_ref()) {
484                     (Nonterminal::NtExpr(this), Nonterminal::NtExpr(other)) => {
485                         SpanlessEq::eq(this, other)
486                     }
487                     _ => this == other,
488                 }
489             }
490             _ => self == other,
491         }
492     }
493 }
494 
495 impl SpanlessEq for TokenStream {
eq(&self, other: &Self) -> bool496     fn eq(&self, other: &Self) -> bool {
497         let mut this_trees = self.trees();
498         let mut other_trees = other.trees();
499         loop {
500             let this = match this_trees.next() {
501                 None => return other_trees.next().is_none(),
502                 Some(tree) => tree,
503             };
504             let other = match other_trees.next() {
505                 None => return false,
506                 Some(tree) => tree,
507             };
508             if SpanlessEq::eq(&this, &other) {
509                 continue;
510             }
511             if let (TokenTree::Token(this), TokenTree::Token(other)) = (this, other) {
512                 if match (&this.kind, &other.kind) {
513                     (TokenKind::Literal(this), TokenKind::Literal(other)) => {
514                         SpanlessEq::eq(this, other)
515                     }
516                     (TokenKind::DocComment(_kind, style, symbol), TokenKind::Pound) => {
517                         doc_comment(*style, *symbol, &mut other_trees)
518                     }
519                     (TokenKind::Pound, TokenKind::DocComment(_kind, style, symbol)) => {
520                         doc_comment(*style, *symbol, &mut this_trees)
521                     }
522                     _ => false,
523                 } {
524                     continue;
525                 }
526             }
527             return false;
528         }
529     }
530 }
531 
doc_comment<'a>( style: AttrStyle, unescaped: Symbol, trees: &mut impl Iterator<Item = TokenTree>, ) -> bool532 fn doc_comment<'a>(
533     style: AttrStyle,
534     unescaped: Symbol,
535     trees: &mut impl Iterator<Item = TokenTree>,
536 ) -> bool {
537     if match style {
538         AttrStyle::Outer => false,
539         AttrStyle::Inner => true,
540     } {
541         match trees.next() {
542             Some(TokenTree::Token(Token {
543                 kind: TokenKind::Not,
544                 span: _,
545             })) => {}
546             _ => return false,
547         }
548     }
549     let stream = match trees.next() {
550         Some(TokenTree::Delimited(_span, DelimToken::Bracket, stream)) => stream,
551         _ => return false,
552     };
553     let mut trees = stream.trees();
554     match trees.next() {
555         Some(TokenTree::Token(Token {
556             kind: TokenKind::Ident(symbol, false),
557             span: _,
558         })) if symbol == sym::doc => {}
559         _ => return false,
560     }
561     match trees.next() {
562         Some(TokenTree::Token(Token {
563             kind: TokenKind::Eq,
564             span: _,
565         })) => {}
566         _ => return false,
567     }
568     match trees.next() {
569         Some(TokenTree::Token(token)) => {
570             is_escaped_literal(&token, unescaped) && trees.next().is_none()
571         }
572         _ => false,
573     }
574 }
575 
is_escaped_literal(token: &Token, unescaped: Symbol) -> bool576 fn is_escaped_literal(token: &Token, unescaped: Symbol) -> bool {
577     match match token {
578         Token {
579             kind: TokenKind::Literal(lit),
580             span: _,
581         } => Lit::from_lit_token(*lit, DUMMY_SP),
582         Token {
583             kind: TokenKind::Interpolated(nonterminal),
584             span: _,
585         } => match nonterminal.as_ref() {
586             Nonterminal::NtExpr(expr) => match &expr.kind {
587                 ExprKind::Lit(lit) => Ok(lit.clone()),
588                 _ => return false,
589             },
590             _ => return false,
591         },
592         _ => return false,
593     } {
594         Ok(Lit {
595             token:
596                 token::Lit {
597                     kind: token::LitKind::Str,
598                     symbol: _,
599                     suffix: None,
600                 },
601             kind: LitKind::Str(symbol, StrStyle::Cooked),
602             span: _,
603         }) => symbol.as_str().replace('\r', "") == unescaped.as_str().replace('\r', ""),
604         _ => false,
605     }
606 }
607 
608 impl SpanlessEq for LazyTokenStream {
eq(&self, other: &Self) -> bool609     fn eq(&self, other: &Self) -> bool {
610         let this = self.create_token_stream();
611         let other = other.create_token_stream();
612         SpanlessEq::eq(&this, &other)
613     }
614 }
615 
616 impl SpanlessEq for AttrKind {
eq(&self, other: &Self) -> bool617     fn eq(&self, other: &Self) -> bool {
618         match (self, other) {
619             (AttrKind::Normal(item, tokens), AttrKind::Normal(item2, tokens2)) => {
620                 SpanlessEq::eq(item, item2) && SpanlessEq::eq(tokens, tokens2)
621             }
622             (AttrKind::DocComment(kind, symbol), AttrKind::DocComment(kind2, symbol2)) => {
623                 SpanlessEq::eq(kind, kind2) && SpanlessEq::eq(symbol, symbol2)
624             }
625             (AttrKind::DocComment(kind, unescaped), AttrKind::Normal(item2, _tokens)) => {
626                 match kind {
627                     CommentKind::Line | CommentKind::Block => {}
628                 }
629                 let path = Path::from_ident(Ident::with_dummy_span(sym::doc));
630                 SpanlessEq::eq(&path, &item2.path)
631                     && match &item2.args {
632                         MacArgs::Empty | MacArgs::Delimited(..) => false,
633                         MacArgs::Eq(_span, token) => is_escaped_literal(token, *unescaped),
634                     }
635             }
636             (AttrKind::Normal(..), AttrKind::DocComment(..)) => SpanlessEq::eq(other, self),
637         }
638     }
639 }
640