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