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