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