]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs
Auto merge of #54720 - davidtwco:issue-51191, r=nikomatsakis
[rust.git] / src / test / run-pass-fulldeps / pprust-expr-roundtrip.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // ignore-cross-compile
12
13
14 // The general idea of this test is to enumerate all "interesting" expressions and check that
15 // `parse(print(e)) == e` for all `e`.  Here's what's interesting, for the purposes of this test:
16 //
17 //  1. The test focuses on expression nesting, because interactions between different expression
18 //     types are harder to test manually than single expression types in isolation.
19 //
20 //  2. The test only considers expressions of at most two nontrivial nodes.  So it will check `x +
21 //     x` and `x + (x - x)` but not `(x * x) + (x - x)`.  The assumption here is that the correct
22 //     handling of an expression might depend on the expression's parent, but doesn't depend on its
23 //     siblings or any more distant ancestors.
24 //
25 // 3. The test only checks certain expression kinds.  The assumption is that similar expression
26 //    types, such as `if` and `while` or `+` and `-`,  will be handled identically in the printer
27 //    and parser.  So if all combinations of exprs involving `if` work correctly, then combinations
28 //    using `while`, `if let`, and so on will likely work as well.
29
30
31 #![feature(rustc_private)]
32
33 extern crate rustc_data_structures;
34 extern crate syntax;
35
36 use rustc_data_structures::thin_vec::ThinVec;
37 use syntax::ast::*;
38 use syntax::source_map::{Spanned, DUMMY_SP, FileName};
39 use syntax::source_map::FilePathMapping;
40 use syntax::fold::{self, Folder};
41 use syntax::parse::{self, ParseSess};
42 use syntax::print::pprust;
43 use syntax::ptr::P;
44
45
46 fn parse_expr(ps: &ParseSess, src: &str) -> P<Expr> {
47     let mut p = parse::new_parser_from_source_str(ps,
48                                                   FileName::Custom("expr".to_owned()),
49                                                   src.to_owned());
50     p.parse_expr().unwrap()
51 }
52
53
54 // Helper functions for building exprs
55 fn expr(kind: ExprKind) -> P<Expr> {
56     P(Expr {
57         id: DUMMY_NODE_ID,
58         node: kind,
59         span: DUMMY_SP,
60         attrs: ThinVec::new(),
61     })
62 }
63
64 fn make_x() -> P<Expr> {
65     let seg = PathSegment::from_ident(Ident::from_str("x"));
66     let path = Path { segments: vec![seg], span: DUMMY_SP };
67     expr(ExprKind::Path(None, path))
68 }
69
70 /// Iterate over exprs of depth up to `depth`.  The goal is to explore all "interesting"
71 /// combinations of expression nesting.  For example, we explore combinations using `if`, but not
72 /// `while` or `match`, since those should print and parse in much the same way as `if`.
73 fn iter_exprs(depth: usize, f: &mut FnMut(P<Expr>)) {
74     if depth == 0 {
75         f(make_x());
76         return;
77     }
78
79     let mut g = |e| f(expr(e));
80
81     for kind in 0 .. 16 {
82         match kind {
83             0 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Box(e))),
84             1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, vec![]))),
85             2 => {
86                 let seg = PathSegment::from_ident(Ident::from_str("x"));
87                 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
88                             seg.clone(), vec![e, make_x()])));
89                 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
90                             seg.clone(), vec![make_x(), e])));
91             },
92             3 => {
93                 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Add };
94                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
95                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
96             },
97             4 => {
98                 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Mul };
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             5 => {
103                 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Shl };
104                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
105                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
106             },
107             6 => {
108                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Unary(UnOp::Deref, e)));
109             },
110             7 => {
111                 let block = P(Block {
112                     stmts: Vec::new(),
113                     id: DUMMY_NODE_ID,
114                     rules: BlockCheckMode::Default,
115                     span: DUMMY_SP,
116                     recovered: false,
117                 });
118                 iter_exprs(depth - 1, &mut |e| g(ExprKind::If(e, block.clone(), None)));
119             },
120             8 => {
121                 let decl = P(FnDecl {
122                     inputs: vec![],
123                     output: FunctionRetTy::Default(DUMMY_SP),
124                     variadic: false,
125                 });
126                 iter_exprs(depth - 1, &mut |e| g(
127                         ExprKind::Closure(CaptureBy::Value,
128                                           IsAsync::NotAsync,
129                                           Movability::Movable,
130                                           decl.clone(),
131                                           e,
132                                           DUMMY_SP)));
133             },
134             9 => {
135                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(e, make_x())));
136                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(make_x(), e)));
137             },
138             10 => {
139                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Field(e, Ident::from_str("f"))));
140             },
141             11 => {
142                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
143                             Some(e), Some(make_x()), RangeLimits::HalfOpen)));
144                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
145                             Some(make_x()), Some(e), RangeLimits::HalfOpen)));
146             },
147             12 => {
148                 iter_exprs(depth - 1, &mut |e| g(ExprKind::AddrOf(Mutability::Immutable, e)));
149             },
150             13 => {
151                 g(ExprKind::Ret(None));
152                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Ret(Some(e))));
153             },
154             14 => {
155                 let path = Path::from_ident(Ident::from_str("S"));
156                 g(ExprKind::Struct(path, vec![], Some(make_x())));
157             },
158             15 => {
159                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Try(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 /// Folder that removes all `ExprKind::Paren` nodes.
170 struct RemoveParens;
171
172 impl Folder for RemoveParens {
173     fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
174         let e = match e.node {
175             ExprKind::Paren(ref inner) => inner.clone(),
176             _ => e.clone(),
177         };
178         e.map(|e| fold::noop_fold_expr(e, self))
179     }
180 }
181
182
183 /// Folder that inserts `ExprKind::Paren` nodes around every `Expr`.
184 struct AddParens;
185
186 impl Folder for AddParens {
187     fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
188         let e = e.map(|e| fold::noop_fold_expr(e, self));
189         P(Expr {
190             id: DUMMY_NODE_ID,
191             node: ExprKind::Paren(e),
192             span: DUMMY_SP,
193             attrs: ThinVec::new(),
194         })
195     }
196 }
197
198 fn main() {
199     syntax::with_globals(|| run());
200 }
201
202 fn run() {
203     let ps = ParseSess::new(FilePathMapping::empty());
204
205     iter_exprs(2, &mut |e| {
206         // If the pretty printer is correct, then `parse(print(e))` should be identical to `e`,
207         // modulo placement of `Paren` nodes.
208         let printed = pprust::expr_to_string(&e);
209         println!("printed: {}", printed);
210
211         let parsed = parse_expr(&ps, &printed);
212
213         // We want to know if `parsed` is structurally identical to `e`, ignoring trivial
214         // differences like placement of `Paren`s or the exact ranges of node spans.
215         // Unfortunately, there is no easy way to make this comparison.  Instead, we add `Paren`s
216         // everywhere we can, then pretty-print.  This should give an unambiguous representation of
217         // each `Expr`, and it bypasses nearly all of the parenthesization logic, so we aren't
218         // relying on the correctness of the very thing we're testing.
219         let e1 = AddParens.fold_expr(RemoveParens.fold_expr(e));
220         let text1 = pprust::expr_to_string(&e1);
221         let e2 = AddParens.fold_expr(RemoveParens.fold_expr(parsed));
222         let text2 = pprust::expr_to_string(&e2);
223         assert!(text1 == text2,
224                 "exprs are not equal:\n  e =      {:?}\n  parsed = {:?}",
225                 text1, text2);
226     });
227 }