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