rustc_ast/util/classify.rs
1//! Routines the parser and pretty-printer use to classify AST nodes.
2
3use crate::ast::ExprKind::*;
4use crate::ast::{self, MatchKind};
5use crate::token::Delimiter;
6
7/// This classification determines whether various syntactic positions break out
8/// of parsing the current expression (true) or continue parsing more of the
9/// same expression (false).
10///
11/// For example, it's relevant in the parsing of match arms:
12///
13/// ```ignore (illustrative)
14/// match ... {
15/// // Is this calling $e as a function, or is it the start of a new arm
16/// // with a tuple pattern?
17/// _ => $e (
18/// ^ )
19///
20/// // Is this an Index operation, or new arm with a slice pattern?
21/// _ => $e [
22/// ^ ]
23///
24/// // Is this a binary operator, or leading vert in a new arm? Same for
25/// // other punctuation which can either be a binary operator in
26/// // expression or unary operator in pattern, such as `&` and `-`.
27/// _ => $e |
28/// ^
29/// }
30/// ```
31///
32/// If $e is something like `{}` or `if … {}`, then terminate the current
33/// arm and parse a new arm.
34///
35/// If $e is something like `path::to` or `(…)`, continue parsing the same
36/// arm.
37///
38/// *Almost* the same classification is used as an early bail-out for parsing
39/// statements. See `expr_requires_semi_to_be_stmt`.
40pub fn expr_is_complete(e: &ast::Expr) -> bool {
41 matches!(
42 e.kind,
43 If(..)
44 | Match(..)
45 | Block(..)
46 | While(..)
47 | Loop(..)
48 | ForLoop { .. }
49 | TryBlock(..)
50 | ConstBlock(..)
51 )
52}
53
54/// Does this expression require a semicolon to be treated as a statement?
55///
56/// The negation of this: "can this expression be used as a statement without a
57/// semicolon" -- is used as an early bail-out when parsing statements so that,
58/// for instance,
59///
60/// ```ignore (illustrative)
61/// if true {...} else {...}
62/// |x| 5
63/// ```
64///
65/// isn't parsed as `(if true {...} else {...} | x) | 5`.
66///
67/// Surprising special case: even though braced macro calls like `m! {}`
68/// normally do not introduce a boundary when found at the head of a match arm,
69/// they do terminate the parsing of a statement.
70///
71/// ```ignore (illustrative)
72/// match ... {
73/// _ => m! {} (), // macro that expands to a function, which is then called
74/// }
75///
76/// let _ = { m! {} () }; // macro call followed by unit
77/// ```
78pub fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
79 match &e.kind {
80 MacCall(mac_call) => mac_call.args.delim != Delimiter::Brace,
81 _ => !expr_is_complete(e),
82 }
83}
84
85/// Returns whether the leftmost token of the given expression is the label of a
86/// labeled loop or block, such as in `'inner: loop { break 'inner 1 } + 1`.
87///
88/// Such expressions are not allowed as the value of an unlabeled break.
89///
90/// ```ignore (illustrative)
91/// 'outer: {
92/// break 'inner: loop { break 'inner 1 } + 1; // invalid syntax
93///
94/// break 'outer 'inner: loop { break 'inner 1 } + 1; // okay
95///
96/// break ('inner: loop { break 'inner 1 } + 1); // okay
97///
98/// break ('inner: loop { break 'inner 1 }) + 1; // okay
99/// }
100/// ```
101pub fn leading_labeled_expr(mut expr: &ast::Expr) -> bool {
102 loop {
103 match &expr.kind {
104 Block(_, label) | ForLoop { label, .. } | Loop(_, label, _) | While(_, _, label) => {
105 return label.is_some();
106 }
107
108 Assign(e, _, _)
109 | AssignOp(_, e, _)
110 | Await(e, _)
111 | Binary(_, e, _)
112 | Call(e, _)
113 | Cast(e, _)
114 | Field(e, _)
115 | Index(e, _, _)
116 | Match(e, _, MatchKind::Postfix)
117 | Range(Some(e), _, _)
118 | Try(e) => {
119 expr = e;
120 }
121 MethodCall(method_call) => {
122 expr = &method_call.receiver;
123 }
124
125 AddrOf(..)
126 | Array(..)
127 | Become(..)
128 | Break(..)
129 | Closure(..)
130 | ConstBlock(..)
131 | Continue(..)
132 | FormatArgs(..)
133 | Gen(..)
134 | If(..)
135 | IncludedBytes(..)
136 | InlineAsm(..)
137 | Let(..)
138 | Lit(..)
139 | MacCall(..)
140 | Match(_, _, MatchKind::Prefix)
141 | OffsetOf(..)
142 | Paren(..)
143 | Path(..)
144 | Range(None, _, _)
145 | Repeat(..)
146 | Ret(..)
147 | Struct(..)
148 | TryBlock(..)
149 | Tup(..)
150 | Type(..)
151 | Unary(..)
152 | Underscore
153 | Yeet(..)
154 | Yield(..)
155 | UnsafeBinderCast(..)
156 | Err(..)
157 | Dummy => return false,
158 }
159 }
160}
161
162pub enum TrailingBrace<'a> {
163 /// Trailing brace in a macro call, like the one in `x as *const brace! {}`.
164 /// We will suggest changing the macro call to a different delimiter.
165 MacCall(&'a ast::MacCall),
166 /// Trailing brace in any other expression, such as `a + B {}`. We will
167 /// suggest wrapping the innermost expression in parentheses: `a + (B {})`.
168 Expr(&'a ast::Expr),
169}
170
171/// If an expression ends with `}`, returns the innermost expression ending in the `}`
172pub fn expr_trailing_brace(mut expr: &ast::Expr) -> Option<TrailingBrace<'_>> {
173 loop {
174 match &expr.kind {
175 AddrOf(_, _, e)
176 | Assign(_, e, _)
177 | AssignOp(_, _, e)
178 | Binary(_, _, e)
179 | Break(_, Some(e))
180 | Let(_, e, _, _)
181 | Range(_, Some(e), _)
182 | Ret(Some(e))
183 | Unary(_, e)
184 | Yield(Some(e))
185 | Yeet(Some(e))
186 | Become(e) => {
187 expr = e;
188 }
189 Closure(closure) => {
190 expr = &closure.body;
191 }
192 Gen(..)
193 | Block(..)
194 | ForLoop { .. }
195 | If(..)
196 | Loop(..)
197 | Match(..)
198 | Struct(..)
199 | TryBlock(..)
200 | While(..)
201 | ConstBlock(_) => break Some(TrailingBrace::Expr(expr)),
202
203 Cast(_, ty) => {
204 break type_trailing_braced_mac_call(ty).map(TrailingBrace::MacCall);
205 }
206
207 MacCall(mac) => {
208 break (mac.args.delim == Delimiter::Brace).then_some(TrailingBrace::MacCall(mac));
209 }
210
211 InlineAsm(_) | OffsetOf(_, _) | IncludedBytes(_) | FormatArgs(_) => {
212 // These should have been denied pre-expansion.
213 break None;
214 }
215
216 Break(_, None)
217 | Range(_, None, _)
218 | Ret(None)
219 | Yield(None)
220 | Array(_)
221 | Call(_, _)
222 | MethodCall(_)
223 | Tup(_)
224 | Lit(_)
225 | Type(_, _)
226 | Await(_, _)
227 | Field(_, _)
228 | Index(_, _, _)
229 | Underscore
230 | Path(_, _)
231 | Continue(_)
232 | Repeat(_, _)
233 | Paren(_)
234 | Try(_)
235 | Yeet(None)
236 | UnsafeBinderCast(..)
237 | Err(_)
238 | Dummy => break None,
239 }
240 }
241}
242
243/// If the type's last token is `}`, it must be due to a braced macro call, such
244/// as in `*const brace! { ... }`. Returns that trailing macro call.
245fn type_trailing_braced_mac_call(mut ty: &ast::Ty) -> Option<&ast::MacCall> {
246 loop {
247 match &ty.kind {
248 ast::TyKind::MacCall(mac) => {
249 break (mac.args.delim == Delimiter::Brace).then_some(mac);
250 }
251
252 ast::TyKind::Ptr(mut_ty)
253 | ast::TyKind::Ref(_, mut_ty)
254 | ast::TyKind::PinnedRef(_, mut_ty) => {
255 ty = &mut_ty.ty;
256 }
257
258 ast::TyKind::UnsafeBinder(binder) => {
259 ty = &binder.inner_ty;
260 }
261
262 ast::TyKind::BareFn(fn_ty) => match &fn_ty.decl.output {
263 ast::FnRetTy::Default(_) => break None,
264 ast::FnRetTy::Ty(ret) => ty = ret,
265 },
266
267 ast::TyKind::Path(_, path) => match path_return_type(path) {
268 Some(trailing_ty) => ty = trailing_ty,
269 None => break None,
270 },
271
272 ast::TyKind::TraitObject(bounds, _) | ast::TyKind::ImplTrait(_, bounds) => {
273 match bounds.last() {
274 Some(ast::GenericBound::Trait(bound)) => {
275 match path_return_type(&bound.trait_ref.path) {
276 Some(trailing_ty) => ty = trailing_ty,
277 None => break None,
278 }
279 }
280 Some(ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..)) | None => {
281 break None;
282 }
283 }
284 }
285
286 ast::TyKind::Slice(..)
287 | ast::TyKind::Array(..)
288 | ast::TyKind::Never
289 | ast::TyKind::Tup(..)
290 | ast::TyKind::Paren(..)
291 | ast::TyKind::Typeof(..)
292 | ast::TyKind::Infer
293 | ast::TyKind::ImplicitSelf
294 | ast::TyKind::CVarArgs
295 | ast::TyKind::Pat(..)
296 | ast::TyKind::Dummy
297 | ast::TyKind::Err(..) => break None,
298 }
299 }
300}
301
302/// Returns the trailing return type in the given path, if it has one.
303///
304/// ```ignore (illustrative)
305/// ::std::ops::FnOnce(&str) -> fn() -> *const c_void
306/// ^^^^^^^^^^^^^^^^^^^^^
307/// ```
308fn path_return_type(path: &ast::Path) -> Option<&ast::Ty> {
309 let last_segment = path.segments.last()?;
310 let args = last_segment.args.as_ref()?;
311 match &**args {
312 ast::GenericArgs::Parenthesized(args) => match &args.output {
313 ast::FnRetTy::Default(_) => None,
314 ast::FnRetTy::Ty(ret) => Some(ret),
315 },
316 ast::GenericArgs::AngleBracketed(_) | ast::GenericArgs::ParenthesizedElided(_) => None,
317 }
318}