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