]> git.lizzy.rs Git - rust.git/blob - tests/ui-fulldeps/pprust-expr-roundtrip.rs
Rollup merge of #107706 - tgross35:atomic-as-mut-ptr, r=m-ou-se
[rust.git] / tests / ui-fulldeps / pprust-expr-roundtrip.rs
1 // run-pass
2 // ignore-cross-compile
3
4 // The general idea of this test is to enumerate all "interesting" expressions and check that
5 // `parse(print(e)) == e` for all `e`. Here's what's interesting, for the purposes of this test:
6 //
7 // 1. The test focuses on expression nesting, because interactions between different expression
8 //    types are harder to test manually than single expression types in isolation.
9 //
10 // 2. The test only considers expressions of at most two nontrivial nodes. So it will check `x +
11 //    x` and `x + (x - x)` but not `(x * x) + (x - x)`. The assumption here is that the correct
12 //    handling of an expression might depend on the expression's parent, but doesn't depend on its
13 //    siblings or any more distant ancestors.
14 //
15 // 3. The test only checks certain expression kinds. The assumption is that similar expression
16 //    types, such as `if` and `while` or `+` and `-`, will be handled identically in the printer
17 //    and parser. So if all combinations of exprs involving `if` work correctly, then combinations
18 //    using `while`, `if let`, and so on will likely work as well.
19
20 #![feature(rustc_private)]
21
22 extern crate rustc_ast;
23 extern crate rustc_ast_pretty;
24 extern crate rustc_data_structures;
25 extern crate rustc_parse;
26 extern crate rustc_session;
27 extern crate rustc_span;
28 extern crate thin_vec;
29
30 // Necessary to pull in object code as the rest of the rustc crates are shipped only as rmeta
31 // files.
32 #[allow(unused_extern_crates)]
33 extern crate rustc_driver;
34
35 use rustc_ast::mut_visit::{self, visit_clobber, MutVisitor};
36 use rustc_ast::ptr::P;
37 use rustc_ast::*;
38 use rustc_ast_pretty::pprust;
39 use rustc_parse::new_parser_from_source_str;
40 use rustc_session::parse::ParseSess;
41 use rustc_span::source_map::FilePathMapping;
42 use rustc_span::source_map::{FileName, Spanned, DUMMY_SP};
43 use rustc_span::symbol::Ident;
44 use thin_vec::thin_vec;
45
46 fn parse_expr(ps: &ParseSess, src: &str) -> Option<P<Expr>> {
47     let src_as_string = src.to_string();
48
49     let mut p =
50         new_parser_from_source_str(ps, FileName::Custom(src_as_string.clone()), src_as_string);
51     p.parse_expr().map_err(|e| e.cancel()).ok()
52 }
53
54 // Helper functions for building exprs
55 fn expr(kind: ExprKind) -> P<Expr> {
56     P(Expr { id: DUMMY_NODE_ID, kind, span: DUMMY_SP, attrs: AttrVec::new(), tokens: None })
57 }
58
59 fn make_x() -> P<Expr> {
60     let seg = PathSegment::from_ident(Ident::from_str("x"));
61     let path = Path { segments: thin_vec![seg], span: DUMMY_SP, tokens: None };
62     expr(ExprKind::Path(None, path))
63 }
64
65 /// Iterate over exprs of depth up to `depth`. The goal is to explore all "interesting"
66 /// combinations of expression nesting. For example, we explore combinations using `if`, but not
67 /// `while` or `match`, since those should print and parse in much the same way as `if`.
68 fn iter_exprs(depth: usize, f: &mut dyn FnMut(P<Expr>)) {
69     if depth == 0 {
70         f(make_x());
71         return;
72     }
73
74     let mut g = |e| f(expr(e));
75
76     for kind in 0..=19 {
77         match kind {
78             0 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Box(e))),
79             1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, vec![]))),
80             2 => {
81                 let seg = PathSegment::from_ident(Ident::from_str("x"));
82                 iter_exprs(depth - 1, &mut |e| {
83                     g(ExprKind::MethodCall(Box::new(MethodCall {
84                         seg: seg.clone(), receiver: e, args: vec![make_x()], span: DUMMY_SP
85                     }))
86                 )});
87                 iter_exprs(depth - 1, &mut |e| {
88                     g(ExprKind::MethodCall(Box::new(MethodCall {
89                         seg: seg.clone(), receiver: make_x(), args: vec![e], span: DUMMY_SP
90                     }))
91                 )});
92             }
93             3..=8 => {
94                 let op = Spanned {
95                     span: DUMMY_SP,
96                     node: match kind {
97                         3 => BinOpKind::Add,
98                         4 => BinOpKind::Mul,
99                         5 => BinOpKind::Shl,
100                         6 => BinOpKind::And,
101                         7 => BinOpKind::Or,
102                         8 => BinOpKind::Lt,
103                         _ => unreachable!(),
104                     },
105                 };
106                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
107                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
108             }
109             9 => {
110                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Unary(UnOp::Deref, e)));
111             }
112             10 => {
113                 let block = P(Block {
114                     stmts: Vec::new(),
115                     id: DUMMY_NODE_ID,
116                     rules: BlockCheckMode::Default,
117                     span: DUMMY_SP,
118                     tokens: None,
119                     could_be_bare_literal: false,
120                 });
121                 iter_exprs(depth - 1, &mut |e| g(ExprKind::If(e, block.clone(), None)));
122             }
123             11 => {
124                 let decl = P(FnDecl { inputs: vec![], output: FnRetTy::Default(DUMMY_SP) });
125                 iter_exprs(depth - 1, &mut |e| {
126                     g(ExprKind::Closure(Box::new(Closure {
127                         binder: ClosureBinder::NotPresent,
128                         capture_clause: CaptureBy::Value,
129                         constness: Const::No,
130                         asyncness: Async::No,
131                         movability: Movability::Movable,
132                         fn_decl: decl.clone(),
133                         body: e,
134                         fn_decl_span: DUMMY_SP,
135                         fn_arg_span: DUMMY_SP,
136                     })))
137                 });
138             }
139             12 => {
140                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(e, make_x(), DUMMY_SP)));
141                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(make_x(), e, DUMMY_SP)));
142             }
143             13 => {
144                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Field(e, Ident::from_str("f"))));
145             }
146             14 => {
147                 iter_exprs(depth - 1, &mut |e| {
148                     g(ExprKind::Range(Some(e), Some(make_x()), RangeLimits::HalfOpen))
149                 });
150                 iter_exprs(depth - 1, &mut |e| {
151                     g(ExprKind::Range(Some(make_x()), Some(e), RangeLimits::HalfOpen))
152                 });
153             }
154             15 => {
155                 iter_exprs(depth - 1, &mut |e| {
156                     g(ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, e))
157                 });
158             }
159             16 => {
160                 g(ExprKind::Ret(None));
161                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Ret(Some(e))));
162             }
163             17 => {
164                 let path = Path::from_ident(Ident::from_str("S"));
165                 g(ExprKind::Struct(P(StructExpr {
166                     qself: None,
167                     path,
168                     fields: vec![],
169                     rest: StructRest::Base(make_x()),
170                 })));
171             }
172             18 => {
173                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Try(e)));
174             }
175             19 => {
176                 let pat =
177                     P(Pat { id: DUMMY_NODE_ID, kind: PatKind::Wild, span: DUMMY_SP, tokens: None });
178                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Let(pat.clone(), e, DUMMY_SP)))
179             }
180             _ => panic!("bad counter value in iter_exprs"),
181         }
182     }
183 }
184
185 // Folders for manipulating the placement of `Paren` nodes. See below for why this is needed.
186
187 /// `MutVisitor` that removes all `ExprKind::Paren` nodes.
188 struct RemoveParens;
189
190 impl MutVisitor for RemoveParens {
191     fn visit_expr(&mut self, e: &mut P<Expr>) {
192         match e.kind.clone() {
193             ExprKind::Paren(inner) => *e = inner,
194             _ => {}
195         };
196         mut_visit::noop_visit_expr(e, self);
197     }
198 }
199
200 /// `MutVisitor` that inserts `ExprKind::Paren` nodes around every `Expr`.
201 struct AddParens;
202
203 impl MutVisitor for AddParens {
204     fn visit_expr(&mut self, e: &mut P<Expr>) {
205         mut_visit::noop_visit_expr(e, self);
206         visit_clobber(e, |e| {
207             P(Expr {
208                 id: DUMMY_NODE_ID,
209                 kind: ExprKind::Paren(e),
210                 span: DUMMY_SP,
211                 attrs: AttrVec::new(),
212                 tokens: None,
213             })
214         });
215     }
216 }
217
218 fn main() {
219     rustc_span::create_default_session_globals_then(|| run());
220 }
221
222 fn run() {
223     let ps = ParseSess::new(FilePathMapping::empty());
224
225     iter_exprs(2, &mut |mut e| {
226         // If the pretty printer is correct, then `parse(print(e))` should be identical to `e`,
227         // modulo placement of `Paren` nodes.
228         let printed = pprust::expr_to_string(&e);
229         println!("printed: {}", printed);
230
231         // Ignore expressions with chained comparisons that fail to parse
232         if let Some(mut parsed) = parse_expr(&ps, &printed) {
233             // We want to know if `parsed` is structurally identical to `e`, ignoring trivial
234             // differences like placement of `Paren`s or the exact ranges of node spans.
235             // Unfortunately, there is no easy way to make this comparison. Instead, we add `Paren`s
236             // everywhere we can, then pretty-print. This should give an unambiguous representation
237             // of each `Expr`, and it bypasses nearly all of the parenthesization logic, so we
238             // aren't relying on the correctness of the very thing we're testing.
239             RemoveParens.visit_expr(&mut e);
240             AddParens.visit_expr(&mut e);
241             let text1 = pprust::expr_to_string(&e);
242             RemoveParens.visit_expr(&mut parsed);
243             AddParens.visit_expr(&mut parsed);
244             let text2 = pprust::expr_to_string(&parsed);
245             assert!(
246                 text1 == text2,
247                 "exprs are not equal:\n  e =      {:?}\n  parsed = {:?}",
248                 text1,
249                 text2
250             );
251         }
252     });
253 }