]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass-fulldeps/pprust-expr-roundtrip.rs
Auto merge of #61421 - vorner:string-in-rc-into-raw-docs, r=RalfJung
[rust.git] / src / test / run-pass-fulldeps / pprust-expr-roundtrip.rs
1 // ignore-cross-compile
2
3 // The general idea of this test is to enumerate all "interesting" expressions and check that
4 // `parse(print(e)) == e` for all `e`. Here's what's interesting, for the purposes of this test:
5 //
6 // 1. The test focuses on expression nesting, because interactions between different expression
7 //    types are harder to test manually than single expression types in isolation.
8 //
9 // 2. The test only considers expressions of at most two nontrivial nodes. So it will check `x +
10 //    x` and `x + (x - x)` but not `(x * x) + (x - x)`. The assumption here is that the correct
11 //    handling of an expression might depend on the expression's parent, but doesn't depend on its
12 //    siblings or any more distant ancestors.
13 //
14 // 3. The test only checks certain expression kinds. The assumption is that similar expression
15 //    types, such as `if` and `while` or `+` and `-`, will be handled identically in the printer
16 //    and parser. So if all combinations of exprs involving `if` work correctly, then combinations
17 //    using `while`, `if let`, and so on will likely work as well.
18
19 #![feature(rustc_private)]
20
21 extern crate rustc_data_structures;
22 extern crate syntax;
23
24 use rustc_data_structures::thin_vec::ThinVec;
25 use syntax::ast::*;
26 use syntax::source_map::{Spanned, DUMMY_SP, FileName};
27 use syntax::source_map::FilePathMapping;
28 use syntax::mut_visit::{self, MutVisitor, visit_clobber};
29 use syntax::parse::{self, ParseSess};
30 use syntax::print::pprust;
31 use syntax::ptr::P;
32
33
34 fn parse_expr(ps: &ParseSess, src: &str) -> P<Expr> {
35     let src_as_string = src.to_string();
36
37     let mut p = parse::new_parser_from_source_str(ps,
38                                                   FileName::Custom(src_as_string.clone()),
39                                                   src_as_string);
40     p.parse_expr().unwrap()
41 }
42
43
44 // Helper functions for building exprs
45 fn expr(kind: ExprKind) -> P<Expr> {
46     P(Expr {
47         id: DUMMY_NODE_ID,
48         node: kind,
49         span: DUMMY_SP,
50         attrs: ThinVec::new(),
51     })
52 }
53
54 fn make_x() -> P<Expr> {
55     let seg = PathSegment::from_ident(Ident::from_str("x"));
56     let path = Path { segments: vec![seg], span: DUMMY_SP };
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 .. 16 {
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| g(ExprKind::MethodCall(
78                             seg.clone(), vec![e, make_x()])));
79                 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
80                             seg.clone(), vec![make_x(), e])));
81             },
82             3 => {
83                 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Add };
84                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
85                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
86             },
87             4 => {
88                 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Mul };
89                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
90                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
91             },
92             5 => {
93                 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Shl };
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             6 => {
98                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Unary(UnOp::Deref, e)));
99             },
100             7 => {
101                 let block = P(Block {
102                     stmts: Vec::new(),
103                     id: DUMMY_NODE_ID,
104                     rules: BlockCheckMode::Default,
105                     span: DUMMY_SP,
106                 });
107                 iter_exprs(depth - 1, &mut |e| g(ExprKind::If(e, block.clone(), None)));
108             },
109             8 => {
110                 let decl = P(FnDecl {
111                     inputs: vec![],
112                     output: FunctionRetTy::Default(DUMMY_SP),
113                     c_variadic: false,
114                 });
115                 iter_exprs(depth - 1, &mut |e| g(
116                         ExprKind::Closure(CaptureBy::Value,
117                                           IsAsync::NotAsync,
118                                           Movability::Movable,
119                                           decl.clone(),
120                                           e,
121                                           DUMMY_SP)));
122             },
123             9 => {
124                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(e, make_x())));
125                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(make_x(), e)));
126             },
127             10 => {
128                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Field(e, Ident::from_str("f"))));
129             },
130             11 => {
131                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
132                             Some(e), Some(make_x()), RangeLimits::HalfOpen)));
133                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
134                             Some(make_x()), Some(e), RangeLimits::HalfOpen)));
135             },
136             12 => {
137                 iter_exprs(depth - 1, &mut |e| g(ExprKind::AddrOf(Mutability::Immutable, e)));
138             },
139             13 => {
140                 g(ExprKind::Ret(None));
141                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Ret(Some(e))));
142             },
143             14 => {
144                 let path = Path::from_ident(Ident::from_str("S"));
145                 g(ExprKind::Struct(path, vec![], Some(make_x())));
146             },
147             15 => {
148                 iter_exprs(depth - 1, &mut |e| g(ExprKind::Try(e)));
149             },
150             _ => panic!("bad counter value in iter_exprs"),
151         }
152     }
153 }
154
155
156 // Folders for manipulating the placement of `Paren` nodes. See below for why this is needed.
157
158 /// `MutVisitor` that removes all `ExprKind::Paren` nodes.
159 struct RemoveParens;
160
161 impl MutVisitor for RemoveParens {
162     fn visit_expr(&mut self, e: &mut P<Expr>) {
163         match e.node.clone() {
164             ExprKind::Paren(inner) => *e = inner,
165             _ => {}
166         };
167         mut_visit::noop_visit_expr(e, self);
168     }
169 }
170
171
172 /// `MutVisitor` that inserts `ExprKind::Paren` nodes around every `Expr`.
173 struct AddParens;
174
175 impl MutVisitor for AddParens {
176     fn visit_expr(&mut self, e: &mut P<Expr>) {
177         mut_visit::noop_visit_expr(e, self);
178         visit_clobber(e, |e| {
179             P(Expr {
180                 id: DUMMY_NODE_ID,
181                 node: ExprKind::Paren(e),
182                 span: DUMMY_SP,
183                 attrs: ThinVec::new(),
184             })
185         });
186     }
187 }
188
189 fn main() {
190     syntax::with_default_globals(|| run());
191 }
192
193 fn run() {
194     let ps = ParseSess::new(FilePathMapping::empty());
195
196     iter_exprs(2, &mut |mut e| {
197         // If the pretty printer is correct, then `parse(print(e))` should be identical to `e`,
198         // modulo placement of `Paren` nodes.
199         let printed = pprust::expr_to_string(&e);
200         println!("printed: {}", printed);
201
202         let mut parsed = parse_expr(&ps, &printed);
203
204         // We want to know if `parsed` is structurally identical to `e`, ignoring trivial
205         // differences like placement of `Paren`s or the exact ranges of node spans.
206         // Unfortunately, there is no easy way to make this comparison. Instead, we add `Paren`s
207         // everywhere we can, then pretty-print. This should give an unambiguous representation of
208         // each `Expr`, and it bypasses nearly all of the parenthesization logic, so we aren't
209         // relying on the correctness of the very thing we're testing.
210         RemoveParens.visit_expr(&mut e);
211         AddParens.visit_expr(&mut e);
212         let text1 = pprust::expr_to_string(&e);
213         RemoveParens.visit_expr(&mut parsed);
214         AddParens.visit_expr(&mut parsed);
215         let text2 = pprust::expr_to_string(&parsed);
216         assert!(text1 == text2,
217                 "exprs are not equal:\n  e =      {:?}\n  parsed = {:?}",
218                 text1, text2);
219     });
220 }