]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/diagnostics.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[rust.git] / src / libsyntax / parse / diagnostics.rs
1 use crate::ast::{
2     self, Arg, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, ItemKind,
3     Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind, VariantData,
4 };
5 use crate::feature_gate::{feature_err, UnstableFeatures};
6 use crate::parse::{SeqSep, PResult, Parser, ParseSess};
7 use crate::parse::parser::{BlockMode, PathStyle, SemiColonMode, TokenType, TokenExpectType};
8 use crate::parse::token::{self, TokenKind};
9 use crate::print::pprust;
10 use crate::ptr::P;
11 use crate::source_map::Spanned;
12 use crate::symbol::{kw, sym};
13 use crate::ThinVec;
14 use crate::util::parser::AssocOp;
15 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
16 use rustc_data_structures::fx::FxHashSet;
17 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
18 use log::{debug, trace};
19 use std::mem;
20
21 /// Creates a placeholder argument.
22 crate fn dummy_arg(ident: Ident) -> Arg {
23     let pat = P(Pat {
24         id: ast::DUMMY_NODE_ID,
25         node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
26         span: ident.span,
27     });
28     let ty = Ty {
29         node: TyKind::Err,
30         span: ident.span,
31         id: ast::DUMMY_NODE_ID
32     };
33     Arg { attrs: ThinVec::default(), id: ast::DUMMY_NODE_ID, pat, span: ident.span, ty: P(ty) }
34 }
35
36 pub enum Error {
37     FileNotFoundForModule {
38         mod_name: String,
39         default_path: String,
40         secondary_path: String,
41         dir_path: String,
42     },
43     DuplicatePaths {
44         mod_name: String,
45         default_path: String,
46         secondary_path: String,
47     },
48     UselessDocComment,
49     InclusiveRangeWithNoEnd,
50 }
51
52 impl Error {
53     fn span_err<S: Into<MultiSpan>>(
54         self,
55         sp: S,
56         handler: &errors::Handler,
57     ) -> DiagnosticBuilder<'_> {
58         match self {
59             Error::FileNotFoundForModule {
60                 ref mod_name,
61                 ref default_path,
62                 ref secondary_path,
63                 ref dir_path,
64             } => {
65                 let mut err = struct_span_err!(
66                     handler,
67                     sp,
68                     E0583,
69                     "file not found for module `{}`",
70                     mod_name,
71                 );
72                 err.help(&format!(
73                     "name the file either {} or {} inside the directory \"{}\"",
74                     default_path,
75                     secondary_path,
76                     dir_path,
77                 ));
78                 err
79             }
80             Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
81                 let mut err = struct_span_err!(
82                     handler,
83                     sp,
84                     E0584,
85                     "file for module `{}` found at both {} and {}",
86                     mod_name,
87                     default_path,
88                     secondary_path,
89                 );
90                 err.help("delete or rename one of them to remove the ambiguity");
91                 err
92             }
93             Error::UselessDocComment => {
94                 let mut err = struct_span_err!(
95                     handler,
96                     sp,
97                     E0585,
98                     "found a documentation comment that doesn't document anything",
99                 );
100                 err.help("doc comments must come before what they document, maybe a comment was \
101                           intended with `//`?");
102                 err
103             }
104             Error::InclusiveRangeWithNoEnd => {
105                 let mut err = struct_span_err!(
106                     handler,
107                     sp,
108                     E0586,
109                     "inclusive range with no end",
110                 );
111                 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
112                 err
113             }
114         }
115     }
116 }
117
118 pub trait RecoverQPath: Sized + 'static {
119     const PATH_STYLE: PathStyle = PathStyle::Expr;
120     fn to_ty(&self) -> Option<P<Ty>>;
121     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
122 }
123
124 impl RecoverQPath for Ty {
125     const PATH_STYLE: PathStyle = PathStyle::Type;
126     fn to_ty(&self) -> Option<P<Ty>> {
127         Some(P(self.clone()))
128     }
129     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
130         Self {
131             span: path.span,
132             node: TyKind::Path(qself, path),
133             id: ast::DUMMY_NODE_ID,
134         }
135     }
136 }
137
138 impl RecoverQPath for Pat {
139     fn to_ty(&self) -> Option<P<Ty>> {
140         self.to_ty()
141     }
142     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
143         Self {
144             span: path.span,
145             node: PatKind::Path(qself, path),
146             id: ast::DUMMY_NODE_ID,
147         }
148     }
149 }
150
151 impl RecoverQPath for Expr {
152     fn to_ty(&self) -> Option<P<Ty>> {
153         self.to_ty()
154     }
155     fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
156         Self {
157             span: path.span,
158             node: ExprKind::Path(qself, path),
159             attrs: ThinVec::new(),
160             id: ast::DUMMY_NODE_ID,
161         }
162     }
163 }
164
165 impl<'a> Parser<'a> {
166     pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
167         self.span_fatal(self.token.span, m)
168     }
169
170     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
171         self.sess.span_diagnostic.struct_span_fatal(sp, m)
172     }
173
174     pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
175         err.span_err(sp, self.diagnostic())
176     }
177
178     pub fn bug(&self, m: &str) -> ! {
179         self.sess.span_diagnostic.span_bug(self.token.span, m)
180     }
181
182     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
183         self.sess.span_diagnostic.span_err(sp, m)
184     }
185
186     crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
187         self.sess.span_diagnostic.struct_span_err(sp, m)
188     }
189
190     crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
191         self.sess.span_diagnostic.span_bug(sp, m)
192     }
193
194     crate fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
195         self.sess.span_diagnostic.cancel(err)
196     }
197
198     crate fn diagnostic(&self) -> &'a errors::Handler {
199         &self.sess.span_diagnostic
200     }
201
202     crate fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
203         let mut err = self.struct_span_err(
204             self.token.span,
205             &format!("expected identifier, found {}", self.this_token_descr()),
206         );
207         if let token::Ident(name, false) = self.token.kind {
208             if Ident::new(name, self.token.span).is_raw_guess() {
209                 err.span_suggestion(
210                     self.token.span,
211                     "you can escape reserved keywords to use them as identifiers",
212                     format!("r#{}", name),
213                     Applicability::MaybeIncorrect,
214                 );
215             }
216         }
217         if let Some(token_descr) = self.token_descr() {
218             err.span_label(self.token.span, format!("expected identifier, found {}", token_descr));
219         } else {
220             err.span_label(self.token.span, "expected identifier");
221             if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
222                 err.span_suggestion(
223                     self.token.span,
224                     "remove this comma",
225                     String::new(),
226                     Applicability::MachineApplicable,
227                 );
228             }
229         }
230         err
231     }
232
233     pub fn expected_one_of_not_found(
234         &mut self,
235         edible: &[TokenKind],
236         inedible: &[TokenKind],
237     ) -> PResult<'a, bool /* recovered */> {
238         fn tokens_to_string(tokens: &[TokenType]) -> String {
239             let mut i = tokens.iter();
240             // This might be a sign we need a connect method on Iterator.
241             let b = i.next()
242                      .map_or(String::new(), |t| t.to_string());
243             i.enumerate().fold(b, |mut b, (i, a)| {
244                 if tokens.len() > 2 && i == tokens.len() - 2 {
245                     b.push_str(", or ");
246                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
247                     b.push_str(" or ");
248                 } else {
249                     b.push_str(", ");
250                 }
251                 b.push_str(&a.to_string());
252                 b
253             })
254         }
255
256         let mut expected = edible.iter()
257             .map(|x| TokenType::Token(x.clone()))
258             .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
259             .chain(self.expected_tokens.iter().cloned())
260             .collect::<Vec<_>>();
261         expected.sort_by_cached_key(|x| x.to_string());
262         expected.dedup();
263         let expect = tokens_to_string(&expected[..]);
264         let actual = self.this_token_to_string();
265         let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
266             let short_expect = if expected.len() > 6 {
267                 format!("{} possible tokens", expected.len())
268             } else {
269                 expect.clone()
270             };
271             (format!("expected one of {}, found `{}`", expect, actual),
272                 (self.sess.source_map().next_point(self.prev_span),
273                 format!("expected one of {} here", short_expect)))
274         } else if expected.is_empty() {
275             (format!("unexpected token: `{}`", actual),
276                 (self.prev_span, "unexpected token after this".to_string()))
277         } else {
278             (format!("expected {}, found `{}`", expect, actual),
279                 (self.sess.source_map().next_point(self.prev_span),
280                 format!("expected {} here", expect)))
281         };
282         self.last_unexpected_token_span = Some(self.token.span);
283         let mut err = self.fatal(&msg_exp);
284         if self.token.is_ident_named(sym::and) {
285             err.span_suggestion_short(
286                 self.token.span,
287                 "use `&&` instead of `and` for the boolean operator",
288                 "&&".to_string(),
289                 Applicability::MaybeIncorrect,
290             );
291         }
292         if self.token.is_ident_named(sym::or) {
293             err.span_suggestion_short(
294                 self.token.span,
295                 "use `||` instead of `or` for the boolean operator",
296                 "||".to_string(),
297                 Applicability::MaybeIncorrect,
298             );
299         }
300         let sp = if self.token == token::Eof {
301             // This is EOF, don't want to point at the following char, but rather the last token
302             self.prev_span
303         } else {
304             label_sp
305         };
306         match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
307             TokenType::Token(t) => Some(t.clone()),
308             _ => None,
309         }).collect::<Vec<_>>(), err) {
310             Err(e) => err = e,
311             Ok(recovered) => {
312                 return Ok(recovered);
313             }
314         }
315
316         let is_semi_suggestable = expected.iter().any(|t| match t {
317             TokenType::Token(token::Semi) => true, // we expect a `;` here
318             _ => false,
319         }) && ( // a `;` would be expected before the current keyword
320             self.token.is_keyword(kw::Break) ||
321             self.token.is_keyword(kw::Continue) ||
322             self.token.is_keyword(kw::For) ||
323             self.token.is_keyword(kw::If) ||
324             self.token.is_keyword(kw::Let) ||
325             self.token.is_keyword(kw::Loop) ||
326             self.token.is_keyword(kw::Match) ||
327             self.token.is_keyword(kw::Return) ||
328             self.token.is_keyword(kw::While)
329         );
330         let sm = self.sess.source_map();
331         match (sm.lookup_line(self.token.span.lo()), sm.lookup_line(sp.lo())) {
332             (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
333                 // The spans are in different lines, expected `;` and found `let` or `return`.
334                 // High likelihood that it is only a missing `;`.
335                 err.span_suggestion_short(
336                     label_sp,
337                     "a semicolon may be missing here",
338                     ";".to_string(),
339                     Applicability::MaybeIncorrect,
340                 );
341                 err.emit();
342                 return Ok(true);
343             }
344             (Ok(ref a), Ok(ref b)) if a.line == b.line => {
345                 // When the spans are in the same line, it means that the only content between
346                 // them is whitespace, point at the found token in that case:
347                 //
348                 // X |     () => { syntax error };
349                 //   |                    ^^^^^ expected one of 8 possible tokens here
350                 //
351                 // instead of having:
352                 //
353                 // X |     () => { syntax error };
354                 //   |                   -^^^^^ unexpected token
355                 //   |                   |
356                 //   |                   expected one of 8 possible tokens here
357                 err.span_label(self.token.span, label_exp);
358             }
359             _ if self.prev_span == syntax_pos::DUMMY_SP => {
360                 // Account for macro context where the previous span might not be
361                 // available to avoid incorrect output (#54841).
362                 err.span_label(self.token.span, "unexpected token");
363             }
364             _ => {
365                 err.span_label(sp, label_exp);
366                 err.span_label(self.token.span, "unexpected token");
367             }
368         }
369         self.maybe_annotate_with_ascription(&mut err, false);
370         Err(err)
371     }
372
373     pub fn maybe_annotate_with_ascription(
374         &self,
375         err: &mut DiagnosticBuilder<'_>,
376         maybe_expected_semicolon: bool,
377     ) {
378         if let Some((sp, likely_path)) = self.last_type_ascription {
379             let sm = self.sess.source_map();
380             let next_pos = sm.lookup_char_pos(self.token.span.lo());
381             let op_pos = sm.lookup_char_pos(sp.hi());
382
383             if likely_path {
384                 err.span_suggestion(
385                     sp,
386                     "maybe write a path separator here",
387                     "::".to_string(),
388                     match self.sess.unstable_features {
389                         UnstableFeatures::Disallow => Applicability::MachineApplicable,
390                         _ => Applicability::MaybeIncorrect,
391                     },
392                 );
393             } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
394                 err.span_suggestion(
395                     sp,
396                     "try using a semicolon",
397                     ";".to_string(),
398                     Applicability::MaybeIncorrect,
399                 );
400             } else if let UnstableFeatures::Disallow = self.sess.unstable_features {
401                 err.span_label(sp, "tried to parse a type due to this");
402             } else {
403                 err.span_label(sp, "tried to parse a type due to this type ascription");
404             }
405             if let UnstableFeatures::Disallow = self.sess.unstable_features {
406                 // Give extra information about type ascription only if it's a nightly compiler.
407             } else {
408                 err.note("`#![feature(type_ascription)]` lets you annotate an expression with a \
409                           type: `<expr>: <type>`");
410                 err.note("for more information, see \
411                           https://github.com/rust-lang/rust/issues/23416");
412             }
413         }
414     }
415
416     /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
417     /// passes through any errors encountered. Used for error recovery.
418     crate fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
419         let handler = self.diagnostic();
420
421         if let Err(ref mut err) = self.parse_seq_to_before_tokens(
422             kets,
423             SeqSep::none(),
424             TokenExpectType::Expect,
425             |p| Ok(p.parse_token_tree()),
426         ) {
427             handler.cancel(err);
428         }
429     }
430
431     /// This function checks if there are trailing angle brackets and produces
432     /// a diagnostic to suggest removing them.
433     ///
434     /// ```ignore (diagnostic)
435     /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
436     ///                                                        ^^ help: remove extra angle brackets
437     /// ```
438     crate fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) {
439         // This function is intended to be invoked after parsing a path segment where there are two
440         // cases:
441         //
442         // 1. A specific token is expected after the path segment.
443         //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
444         //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
445         // 2. No specific token is expected after the path segment.
446         //    eg. `x.foo` (field access)
447         //
448         // This function is called after parsing `.foo` and before parsing the token `end` (if
449         // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
450         // `Foo::<Bar>`.
451
452         // We only care about trailing angle brackets if we previously parsed angle bracket
453         // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
454         // removed in this case:
455         //
456         // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
457         //
458         // This case is particularly tricky as we won't notice it just looking at the tokens -
459         // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
460         // have already been parsed):
461         //
462         // `x.foo::<u32>>>(3)`
463         let parsed_angle_bracket_args = segment.args
464             .as_ref()
465             .map(|args| args.is_angle_bracketed())
466             .unwrap_or(false);
467
468         debug!(
469             "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
470             parsed_angle_bracket_args,
471         );
472         if !parsed_angle_bracket_args {
473             return;
474         }
475
476         // Keep the span at the start so we can highlight the sequence of `>` characters to be
477         // removed.
478         let lo = self.token.span;
479
480         // We need to look-ahead to see if we have `>` characters without moving the cursor forward
481         // (since we might have the field access case and the characters we're eating are
482         // actual operators and not trailing characters - ie `x.foo >> 3`).
483         let mut position = 0;
484
485         // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
486         // many of each (so we can correctly pluralize our error messages) and continue to
487         // advance.
488         let mut number_of_shr = 0;
489         let mut number_of_gt = 0;
490         while self.look_ahead(position, |t| {
491             trace!("check_trailing_angle_brackets: t={:?}", t);
492             if *t == token::BinOp(token::BinOpToken::Shr) {
493                 number_of_shr += 1;
494                 true
495             } else if *t == token::Gt {
496                 number_of_gt += 1;
497                 true
498             } else {
499                 false
500             }
501         }) {
502             position += 1;
503         }
504
505         // If we didn't find any trailing `>` characters, then we have nothing to error about.
506         debug!(
507             "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
508             number_of_gt, number_of_shr,
509         );
510         if number_of_gt < 1 && number_of_shr < 1 {
511             return;
512         }
513
514         // Finally, double check that we have our end token as otherwise this is the
515         // second case.
516         if self.look_ahead(position, |t| {
517             trace!("check_trailing_angle_brackets: t={:?}", t);
518             *t == end
519         }) {
520             // Eat from where we started until the end token so that parsing can continue
521             // as if we didn't have those extra angle brackets.
522             self.eat_to_tokens(&[&end]);
523             let span = lo.until(self.token.span);
524
525             let plural = number_of_gt > 1 || number_of_shr >= 1;
526             self.diagnostic()
527                 .struct_span_err(
528                     span,
529                     &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
530                 )
531                 .span_suggestion(
532                     span,
533                     &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
534                     String::new(),
535                     Applicability::MachineApplicable,
536                 )
537                 .emit();
538         }
539     }
540
541     /// Produce an error if comparison operators are chained (RFC #558).
542     /// We only need to check lhs, not rhs, because all comparison ops
543     /// have same precedence and are left-associative
544     crate fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) {
545         debug_assert!(outer_op.is_comparison(),
546                       "check_no_chained_comparison: {:?} is not comparison",
547                       outer_op);
548         match lhs.node {
549             ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
550                 // respan to include both operators
551                 let op_span = op.span.to(self.token.span);
552                 let mut err = self.diagnostic().struct_span_err(op_span,
553                     "chained comparison operators require parentheses");
554                 if op.node == BinOpKind::Lt &&
555                     *outer_op == AssocOp::Less ||  // Include `<` to provide this recommendation
556                     *outer_op == AssocOp::Greater  // even in a case like the following:
557                 {                                  //     Foo<Bar<Baz<Qux, ()>>>
558                     err.help(
559                         "use `::<...>` instead of `<...>` if you meant to specify type arguments");
560                     err.help("or use `(...)` if you meant to specify fn arguments");
561                 }
562                 err.emit();
563             }
564             _ => {}
565         }
566     }
567
568     crate fn maybe_report_ambiguous_plus(
569         &mut self,
570         allow_plus: bool,
571         impl_dyn_multi: bool,
572         ty: &Ty,
573     ) {
574         if !allow_plus && impl_dyn_multi {
575             let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
576             self.struct_span_err(ty.span, "ambiguous `+` in a type")
577                 .span_suggestion(
578                     ty.span,
579                     "use parentheses to disambiguate",
580                     sum_with_parens,
581                     Applicability::MachineApplicable,
582                 )
583                 .emit();
584         }
585     }
586
587     crate fn maybe_report_invalid_custom_discriminants(
588         sess: &ParseSess,
589         variants: &[Spanned<ast::Variant_>],
590     ) {
591         let has_fields = variants.iter().any(|variant| match variant.node.data {
592             VariantData::Tuple(..) | VariantData::Struct(..) => true,
593             VariantData::Unit(..) => false,
594         });
595
596         let discriminant_spans = variants.iter().filter(|variant| match variant.node.data {
597             VariantData::Tuple(..) | VariantData::Struct(..) => false,
598             VariantData::Unit(..) => true,
599         })
600         .filter_map(|variant| variant.node.disr_expr.as_ref().map(|c| c.value.span))
601         .collect::<Vec<_>>();
602
603         if !discriminant_spans.is_empty() && has_fields {
604             let mut err = feature_err(
605                 sess,
606                 sym::arbitrary_enum_discriminant,
607                 discriminant_spans.clone(),
608                 crate::feature_gate::GateIssue::Language,
609                 "custom discriminant values are not allowed in enums with tuple or struct variants",
610             );
611             for sp in discriminant_spans {
612                 err.span_label(sp, "disallowed custom discriminant");
613             }
614             for variant in variants.iter() {
615                 match &variant.node.data {
616                     VariantData::Struct(..) => {
617                         err.span_label(
618                             variant.span,
619                             "struct variant defined here",
620                         );
621                     }
622                     VariantData::Tuple(..) => {
623                         err.span_label(
624                             variant.span,
625                             "tuple variant defined here",
626                         );
627                     }
628                     VariantData::Unit(..) => {}
629                 }
630             }
631             err.emit();
632         }
633     }
634
635     crate fn maybe_recover_from_bad_type_plus(
636         &mut self,
637         allow_plus: bool,
638         ty: &Ty,
639     ) -> PResult<'a, ()> {
640         // Do not add `+` to expected tokens.
641         if !allow_plus || !self.token.is_like_plus() {
642             return Ok(());
643         }
644
645         self.bump(); // `+`
646         let bounds = self.parse_generic_bounds(None)?;
647         let sum_span = ty.span.to(self.prev_span);
648
649         let mut err = struct_span_err!(
650             self.sess.span_diagnostic,
651             sum_span,
652             E0178,
653             "expected a path on the left-hand side of `+`, not `{}`",
654             pprust::ty_to_string(ty)
655         );
656
657         match ty.node {
658             TyKind::Rptr(ref lifetime, ref mut_ty) => {
659                 let sum_with_parens = pprust::to_string(|s| {
660                     s.s.word("&");
661                     s.print_opt_lifetime(lifetime);
662                     s.print_mutability(mut_ty.mutbl);
663                     s.popen();
664                     s.print_type(&mut_ty.ty);
665                     s.print_type_bounds(" +", &bounds);
666                     s.pclose()
667                 });
668                 err.span_suggestion(
669                     sum_span,
670                     "try adding parentheses",
671                     sum_with_parens,
672                     Applicability::MachineApplicable,
673                 );
674             }
675             TyKind::Ptr(..) | TyKind::BareFn(..) => {
676                 err.span_label(sum_span, "perhaps you forgot parentheses?");
677             }
678             _ => {
679                 err.span_label(sum_span, "expected a path");
680             }
681         }
682         err.emit();
683         Ok(())
684     }
685
686     /// Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
687     /// Attempt to convert the base expression/pattern/type into a type, parse the `::AssocItem`
688     /// tail, and combine them into a `<Ty>::AssocItem` expression/pattern/type.
689     crate fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
690         &mut self,
691         base: P<T>,
692         allow_recovery: bool,
693     ) -> PResult<'a, P<T>> {
694         // Do not add `::` to expected tokens.
695         if allow_recovery && self.token == token::ModSep {
696             if let Some(ty) = base.to_ty() {
697                 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
698             }
699         }
700         Ok(base)
701     }
702
703     /// Given an already parsed `Ty` parse the `::AssocItem` tail and
704     /// combine them into a `<Ty>::AssocItem` expression/pattern/type.
705     crate fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
706         &mut self,
707         ty_span: Span,
708         ty: P<Ty>,
709     ) -> PResult<'a, P<T>> {
710         self.expect(&token::ModSep)?;
711
712         let mut path = ast::Path {
713             segments: Vec::new(),
714             span: DUMMY_SP,
715         };
716         self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
717         path.span = ty_span.to(self.prev_span);
718
719         let ty_str = self
720             .sess
721             .source_map()
722             .span_to_snippet(ty_span)
723             .unwrap_or_else(|_| pprust::ty_to_string(&ty));
724         self.diagnostic()
725             .struct_span_err(path.span, "missing angle brackets in associated item path")
726             .span_suggestion(
727                 // this is a best-effort recovery
728                 path.span,
729                 "try",
730                 format!("<{}>::{}", ty_str, path),
731                 Applicability::MaybeIncorrect,
732             )
733             .emit();
734
735         let path_span = ty_span.shrink_to_hi(); // use an empty path since `position` == 0
736         Ok(P(T::recovered(
737             Some(QSelf {
738                 ty,
739                 path_span,
740                 position: 0,
741             }),
742             path,
743         )))
744     }
745
746     crate fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
747         if self.eat(&token::Semi) {
748             let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
749             err.span_suggestion_short(
750                 self.prev_span,
751                 "remove this semicolon",
752                 String::new(),
753                 Applicability::MachineApplicable,
754             );
755             if !items.is_empty() {
756                 let previous_item = &items[items.len() - 1];
757                 let previous_item_kind_name = match previous_item.node {
758                     // say "braced struct" because tuple-structs and
759                     // braceless-empty-struct declarations do take a semicolon
760                     ItemKind::Struct(..) => Some("braced struct"),
761                     ItemKind::Enum(..) => Some("enum"),
762                     ItemKind::Trait(..) => Some("trait"),
763                     ItemKind::Union(..) => Some("union"),
764                     _ => None,
765                 };
766                 if let Some(name) = previous_item_kind_name {
767                     err.help(&format!(
768                         "{} declarations are not followed by a semicolon",
769                         name
770                     ));
771                 }
772             }
773             err.emit();
774             true
775         } else {
776             false
777         }
778     }
779
780     /// Create a `DiagnosticBuilder` for an unexpected token `t` and try to recover if it is a
781     /// closing delimiter.
782     pub fn unexpected_try_recover(
783         &mut self,
784         t: &TokenKind,
785     ) -> PResult<'a, bool /* recovered */> {
786         let token_str = pprust::token_kind_to_string(t);
787         let this_token_str = self.this_token_descr();
788         let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
789             // Point at the end of the macro call when reaching end of macro arguments.
790             (token::Eof, Some(_)) => {
791                 let sp = self.sess.source_map().next_point(self.token.span);
792                 (sp, sp)
793             }
794             // We don't want to point at the following span after DUMMY_SP.
795             // This happens when the parser finds an empty TokenStream.
796             _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span),
797             // EOF, don't want to point at the following char, but rather the last token.
798             (token::Eof, None) => (self.prev_span, self.token.span),
799             _ => (self.sess.source_map().next_point(self.prev_span), self.token.span),
800         };
801         let msg = format!(
802             "expected `{}`, found {}",
803             token_str,
804             match (&self.token.kind, self.subparser_name) {
805                 (token::Eof, Some(origin)) => format!("end of {}", origin),
806                 _ => this_token_str,
807             },
808         );
809         let mut err = self.struct_span_err(sp, &msg);
810         let label_exp = format!("expected `{}`", token_str);
811         match self.recover_closing_delimiter(&[t.clone()], err) {
812             Err(e) => err = e,
813             Ok(recovered) => {
814                 return Ok(recovered);
815             }
816         }
817         let sm = self.sess.source_map();
818         match (sm.lookup_line(prev_sp.lo()), sm.lookup_line(sp.lo())) {
819             (Ok(ref a), Ok(ref b)) if a.line == b.line => {
820                 // When the spans are in the same line, it means that the only content
821                 // between them is whitespace, point only at the found token.
822                 err.span_label(sp, label_exp);
823             }
824             _ => {
825                 err.span_label(prev_sp, label_exp);
826                 err.span_label(sp, "unexpected token");
827             }
828         }
829         Err(err)
830     }
831
832     crate fn parse_semi_or_incorrect_foreign_fn_body(
833         &mut self,
834         ident: &Ident,
835         extern_sp: Span,
836     ) -> PResult<'a, ()> {
837         if self.token != token::Semi {
838             // this might be an incorrect fn definition (#62109)
839             let parser_snapshot = self.clone();
840             match self.parse_inner_attrs_and_block() {
841                 Ok((_, body)) => {
842                     self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block")
843                         .span_label(ident.span, "can't have a body")
844                         .span_label(body.span, "this body is invalid here")
845                         .span_label(
846                             extern_sp,
847                             "`extern` blocks define existing foreign functions and `fn`s \
848                              inside of them cannot have a body")
849                         .help("you might have meant to write a function accessible through ffi, \
850                                which can be done by writing `extern fn` outside of the \
851                                `extern` block")
852                         .note("for more information, visit \
853                                https://doc.rust-lang.org/std/keyword.extern.html")
854                         .emit();
855                 }
856                 Err(mut err) => {
857                     err.cancel();
858                     mem::replace(self, parser_snapshot);
859                     self.expect(&token::Semi)?;
860                 }
861             }
862         } else {
863             self.bump();
864         }
865         Ok(())
866     }
867
868     /// Consume alternative await syntaxes like `await <expr>`, `await? <expr>`, `await(<expr>)`
869     /// and `await { <expr> }`.
870     crate fn parse_incorrect_await_syntax(
871         &mut self,
872         lo: Span,
873         await_sp: Span,
874     ) -> PResult<'a, (Span, ExprKind)> {
875         let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
876         let expr = if self.token == token::OpenDelim(token::Brace) {
877             // Handle `await { <expr> }`.
878             // This needs to be handled separatedly from the next arm to avoid
879             // interpreting `await { <expr> }?` as `<expr>?.await`.
880             self.parse_block_expr(
881                 None,
882                 self.token.span,
883                 BlockCheckMode::Default,
884                 ThinVec::new(),
885             )
886         } else {
887             self.parse_expr()
888         }.map_err(|mut err| {
889             err.span_label(await_sp, "while parsing this incorrect await expression");
890             err
891         })?;
892         let expr_str = self.sess.source_map().span_to_snippet(expr.span)
893             .unwrap_or_else(|_| pprust::expr_to_string(&expr));
894         let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" });
895         let sp = lo.to(expr.span);
896         let app = match expr.node {
897             ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
898             _ => Applicability::MachineApplicable,
899         };
900         self.struct_span_err(sp, "incorrect use of `await`")
901             .span_suggestion(sp, "`await` is a postfix operation", suggestion, app)
902             .emit();
903         Ok((sp, ExprKind::Await(ast::AwaitOrigin::FieldLike, expr)))
904     }
905
906     /// If encountering `future.await()`, consume and emit error.
907     crate fn recover_from_await_method_call(&mut self) {
908         if self.token == token::OpenDelim(token::Paren) &&
909             self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren))
910         {
911             // future.await()
912             let lo = self.token.span;
913             self.bump(); // (
914             let sp = lo.to(self.token.span);
915             self.bump(); // )
916             self.struct_span_err(sp, "incorrect use of `await`")
917                 .span_suggestion(
918                     sp,
919                     "`await` is not a method call, remove the parentheses",
920                     String::new(),
921                     Applicability::MachineApplicable,
922                 ).emit()
923         }
924     }
925
926     crate fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
927         self.token.is_ident() &&
928             if let ast::ExprKind::Path(..) = node { true } else { false } &&
929             !self.token.is_reserved_ident() &&           // v `foo:bar(baz)`
930             self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
931             self.look_ahead(1, |t| t == &token::Lt) &&     // `foo:bar<baz`
932             self.look_ahead(2, |t| t.is_ident()) ||
933             self.look_ahead(1, |t| t == &token::Colon) &&  // `foo:bar:baz`
934             self.look_ahead(2, |t| t.is_ident()) ||
935             self.look_ahead(1, |t| t == &token::ModSep) &&
936             (self.look_ahead(2, |t| t.is_ident()) ||   // `foo:bar::baz`
937              self.look_ahead(2, |t| t == &token::Lt))  // `foo:bar::<baz>`
938     }
939
940     crate fn recover_seq_parse_error(
941         &mut self,
942         delim: token::DelimToken,
943         lo: Span,
944         result: PResult<'a, P<Expr>>,
945     ) -> P<Expr> {
946         match result {
947             Ok(x) => x,
948             Err(mut err) => {
949                 err.emit();
950                 // recover from parse error
951                 self.consume_block(delim);
952                 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
953             }
954         }
955     }
956
957     crate fn recover_closing_delimiter(
958         &mut self,
959         tokens: &[TokenKind],
960         mut err: DiagnosticBuilder<'a>,
961     ) -> PResult<'a, bool> {
962         let mut pos = None;
963         // we want to use the last closing delim that would apply
964         for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
965             if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
966                 && Some(self.token.span) > unmatched.unclosed_span
967             {
968                 pos = Some(i);
969             }
970         }
971         match pos {
972             Some(pos) => {
973                 // Recover and assume that the detected unclosed delimiter was meant for
974                 // this location. Emit the diagnostic and act as if the delimiter was
975                 // present for the parser's sake.
976
977                  // Don't attempt to recover from this unclosed delimiter more than once.
978                 let unmatched = self.unclosed_delims.remove(pos);
979                 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
980
981                  // We want to suggest the inclusion of the closing delimiter where it makes
982                 // the most sense, which is immediately after the last token:
983                 //
984                 //  {foo(bar {}}
985                 //      -      ^
986                 //      |      |
987                 //      |      help: `)` may belong here
988                 //      |
989                 //      unclosed delimiter
990                 if let Some(sp) = unmatched.unclosed_span {
991                     err.span_label(sp, "unclosed delimiter");
992                 }
993                 err.span_suggestion_short(
994                     self.sess.source_map().next_point(self.prev_span),
995                     &format!("{} may belong here", delim.to_string()),
996                     delim.to_string(),
997                     Applicability::MaybeIncorrect,
998                 );
999                 err.emit();
1000                 self.expected_tokens.clear();  // reduce errors
1001                 Ok(true)
1002             }
1003             _ => Err(err),
1004         }
1005     }
1006
1007     /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
1008     crate fn eat_bad_pub(&mut self) {
1009         if self.token.is_keyword(kw::Pub) {
1010             match self.parse_visibility(false) {
1011                 Ok(vis) => {
1012                     self.diagnostic()
1013                         .struct_span_err(vis.span, "unnecessary visibility qualifier")
1014                         .span_label(vis.span, "`pub` not permitted here")
1015                         .emit();
1016                 }
1017                 Err(mut err) => err.emit(),
1018             }
1019         }
1020     }
1021
1022     // Eat tokens until we can be relatively sure we reached the end of the
1023     // statement. This is something of a best-effort heuristic.
1024     //
1025     // We terminate when we find an unmatched `}` (without consuming it).
1026     crate fn recover_stmt(&mut self) {
1027         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1028     }
1029
1030     // If `break_on_semi` is `Break`, then we will stop consuming tokens after
1031     // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1032     // approximate - it can mean we break too early due to macros, but that
1033     // should only lead to sub-optimal recovery, not inaccurate parsing).
1034     //
1035     // If `break_on_block` is `Break`, then we will stop consuming tokens
1036     // after finding (and consuming) a brace-delimited block.
1037     crate fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
1038         let mut brace_depth = 0;
1039         let mut bracket_depth = 0;
1040         let mut in_block = false;
1041         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
1042                break_on_semi, break_on_block);
1043         loop {
1044             debug!("recover_stmt_ loop {:?}", self.token);
1045             match self.token.kind {
1046                 token::OpenDelim(token::DelimToken::Brace) => {
1047                     brace_depth += 1;
1048                     self.bump();
1049                     if break_on_block == BlockMode::Break &&
1050                        brace_depth == 1 &&
1051                        bracket_depth == 0 {
1052                         in_block = true;
1053                     }
1054                 }
1055                 token::OpenDelim(token::DelimToken::Bracket) => {
1056                     bracket_depth += 1;
1057                     self.bump();
1058                 }
1059                 token::CloseDelim(token::DelimToken::Brace) => {
1060                     if brace_depth == 0 {
1061                         debug!("recover_stmt_ return - close delim {:?}", self.token);
1062                         break;
1063                     }
1064                     brace_depth -= 1;
1065                     self.bump();
1066                     if in_block && bracket_depth == 0 && brace_depth == 0 {
1067                         debug!("recover_stmt_ return - block end {:?}", self.token);
1068                         break;
1069                     }
1070                 }
1071                 token::CloseDelim(token::DelimToken::Bracket) => {
1072                     bracket_depth -= 1;
1073                     if bracket_depth < 0 {
1074                         bracket_depth = 0;
1075                     }
1076                     self.bump();
1077                 }
1078                 token::Eof => {
1079                     debug!("recover_stmt_ return - Eof");
1080                     break;
1081                 }
1082                 token::Semi => {
1083                     self.bump();
1084                     if break_on_semi == SemiColonMode::Break &&
1085                        brace_depth == 0 &&
1086                        bracket_depth == 0 {
1087                         debug!("recover_stmt_ return - Semi");
1088                         break;
1089                     }
1090                 }
1091                 token::Comma if break_on_semi == SemiColonMode::Comma &&
1092                        brace_depth == 0 &&
1093                        bracket_depth == 0 =>
1094                 {
1095                     debug!("recover_stmt_ return - Semi");
1096                     break;
1097                 }
1098                 _ => {
1099                     self.bump()
1100                 }
1101             }
1102         }
1103     }
1104
1105     crate fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1106         if self.eat_keyword(kw::In) {
1107             // a common typo: `for _ in in bar {}`
1108             let mut err = self.sess.span_diagnostic.struct_span_err(
1109                 self.prev_span,
1110                 "expected iterable, found keyword `in`",
1111             );
1112             err.span_suggestion_short(
1113                 in_span.until(self.prev_span),
1114                 "remove the duplicated `in`",
1115                 String::new(),
1116                 Applicability::MachineApplicable,
1117             );
1118             err.emit();
1119         }
1120     }
1121
1122     crate fn expected_semi_or_open_brace(&mut self) -> PResult<'a, ast::TraitItem> {
1123         let token_str = self.this_token_descr();
1124         let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", token_str));
1125         err.span_label(self.token.span, "expected `;` or `{`");
1126         Err(err)
1127     }
1128
1129     crate fn eat_incorrect_doc_comment_for_arg_type(&mut self) {
1130         if let token::DocComment(_) = self.token.kind {
1131             let mut err = self.diagnostic().struct_span_err(
1132                 self.token.span,
1133                 "documentation comments cannot be applied to a function parameter's type",
1134             );
1135             err.span_label(self.token.span, "doc comments are not allowed here");
1136             err.emit();
1137             self.bump();
1138         } else if self.token == token::Pound && self.look_ahead(1, |t| {
1139             *t == token::OpenDelim(token::Bracket)
1140         }) {
1141             let lo = self.token.span;
1142             // Skip every token until next possible arg.
1143             while self.token != token::CloseDelim(token::Bracket) {
1144                 self.bump();
1145             }
1146             let sp = lo.to(self.token.span);
1147             self.bump();
1148             let mut err = self.diagnostic().struct_span_err(
1149                 sp,
1150                 "attributes cannot be applied to a function parameter's type",
1151             );
1152             err.span_label(sp, "attributes are not allowed here");
1153             err.emit();
1154         }
1155     }
1156
1157     crate fn argument_without_type(
1158         &mut self,
1159         err: &mut DiagnosticBuilder<'_>,
1160         pat: P<ast::Pat>,
1161         require_name: bool,
1162         is_trait_item: bool,
1163     ) -> Option<Ident> {
1164         // If we find a pattern followed by an identifier, it could be an (incorrect)
1165         // C-style parameter declaration.
1166         if self.check_ident() && self.look_ahead(1, |t| {
1167             *t == token::Comma || *t == token::CloseDelim(token::Paren)
1168         }) { // `fn foo(String s) {}`
1169             let ident = self.parse_ident().unwrap();
1170             let span = pat.span.with_hi(ident.span.hi());
1171
1172             err.span_suggestion(
1173                 span,
1174                 "declare the type after the parameter binding",
1175                 String::from("<identifier>: <type>"),
1176                 Applicability::HasPlaceholders,
1177             );
1178             return Some(ident);
1179         } else if let PatKind::Ident(_, ident, _) = pat.node {
1180             if require_name && (
1181                 is_trait_item ||
1182                 self.token == token::Comma ||
1183                 self.token == token::CloseDelim(token::Paren)
1184             ) { // `fn foo(a, b) {}` or `fn foo(usize, usize) {}`
1185                 err.span_suggestion(
1186                     pat.span,
1187                     "if this was a parameter name, give it a type",
1188                     format!("{}: TypeName", ident),
1189                     Applicability::HasPlaceholders,
1190                 );
1191                 err.span_suggestion(
1192                     pat.span,
1193                     "if this is a type, explicitly ignore the parameter name",
1194                     format!("_: {}", ident),
1195                     Applicability::MachineApplicable,
1196                 );
1197                 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1198                 return Some(ident);
1199             }
1200         }
1201         None
1202     }
1203
1204     crate fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
1205         let pat = self.parse_pat(Some("argument name"))?;
1206         self.expect(&token::Colon)?;
1207         let ty = self.parse_ty()?;
1208
1209         let mut err = self.diagnostic().struct_span_err_with_code(
1210             pat.span,
1211             "patterns aren't allowed in methods without bodies",
1212             DiagnosticId::Error("E0642".into()),
1213         );
1214         err.span_suggestion_short(
1215             pat.span,
1216             "give this argument a name or use an underscore to ignore it",
1217             "_".to_owned(),
1218             Applicability::MachineApplicable,
1219         );
1220         err.emit();
1221
1222         // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1223         let pat = P(Pat {
1224             node: PatKind::Wild,
1225             span: pat.span,
1226             id: ast::DUMMY_NODE_ID
1227         });
1228         Ok((pat, ty))
1229     }
1230
1231     crate fn recover_bad_self_arg(
1232         &mut self,
1233         mut arg: ast::Arg,
1234         is_trait_item: bool,
1235     ) -> PResult<'a, ast::Arg> {
1236         let sp = arg.pat.span;
1237         arg.ty.node = TyKind::Err;
1238         let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function");
1239         if is_trait_item {
1240             err.span_label(sp, "must be the first associated function parameter");
1241         } else {
1242             err.span_label(sp, "not valid as function parameter");
1243             err.note("`self` is only valid as the first parameter of an associated function");
1244         }
1245         err.emit();
1246         Ok(arg)
1247     }
1248
1249     crate fn consume_block(&mut self, delim: token::DelimToken) {
1250         let mut brace_depth = 0;
1251         loop {
1252             if self.eat(&token::OpenDelim(delim)) {
1253                 brace_depth += 1;
1254             } else if self.eat(&token::CloseDelim(delim)) {
1255                 if brace_depth == 0 {
1256                     return;
1257                 } else {
1258                     brace_depth -= 1;
1259                     continue;
1260                 }
1261             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
1262                 return;
1263             } else {
1264                 self.bump();
1265             }
1266         }
1267     }
1268
1269     crate fn expected_expression_found(&self) -> DiagnosticBuilder<'a> {
1270         let (span, msg) = match (&self.token.kind, self.subparser_name) {
1271             (&token::Eof, Some(origin)) => {
1272                 let sp = self.sess.source_map().next_point(self.token.span);
1273                 (sp, format!("expected expression, found end of {}", origin))
1274             }
1275             _ => (self.token.span, format!(
1276                 "expected expression, found {}",
1277                 self.this_token_descr(),
1278             )),
1279         };
1280         let mut err = self.struct_span_err(span, &msg);
1281         let sp = self.sess.source_map().start_point(self.token.span);
1282         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
1283             self.sess.expr_parentheses_needed(&mut err, *sp, None);
1284         }
1285         err.span_label(span, "expected expression");
1286         err
1287     }
1288
1289     /// Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
1290     ///
1291     /// This is necessary because at this point we don't know whether we parsed a function with
1292     /// anonymous arguments or a function with names but no types. In order to minimize
1293     /// unecessary errors, we assume the arguments are in the shape of `fn foo(a, b, c)` where
1294     /// the arguments are *names* (so we don't emit errors about not being able to find `b` in
1295     /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
1296     /// we deduplicate them to not complain about duplicated argument names.
1297     crate fn deduplicate_recovered_arg_names(&self, fn_inputs: &mut Vec<Arg>) {
1298         let mut seen_inputs = FxHashSet::default();
1299         for input in fn_inputs.iter_mut() {
1300             let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = (
1301                 &input.pat.node, &input.ty.node,
1302             ) {
1303                 Some(*ident)
1304             } else {
1305                 None
1306             };
1307             if let Some(ident) = opt_ident {
1308                 if seen_inputs.contains(&ident) {
1309                     input.pat.node = PatKind::Wild;
1310                 }
1311                 seen_inputs.insert(ident);
1312             }
1313         }
1314     }
1315 }