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