Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Parse/Parser.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- Parser.cpp - C Language Family Parser ----------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the Parser interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTLambda.h"
17
#include "clang/AST/DeclTemplate.h"
18
#include "clang/Basic/FileManager.h"
19
#include "clang/Parse/ParseDiagnostic.h"
20
#include "clang/Parse/RAIIObjectsForParser.h"
21
#include "clang/Sema/DeclSpec.h"
22
#include "clang/Sema/ParsedTemplate.h"
23
#include "clang/Sema/Scope.h"
24
#include "llvm/Support/Path.h"
25
#include "llvm/Support/TimeProfiler.h"
26
using namespace clang;
27
28
29
namespace {
30
/// A comment handler that passes comments found by the preprocessor
31
/// to the parser action.
32
class ActionCommentHandler : public CommentHandler {
33
  Sema &S;
34
35
public:
36
46
  explicit ActionCommentHandler(Sema &S) : S(S) { }
37
38
943
  bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
39
943
    S.ActOnComment(Comment);
40
943
    return false;
41
943
  }
42
};
43
} // end anonymous namespace
44
45
0
IdentifierInfo *Parser::getSEHExceptKeyword() {
46
  // __except is accepted as a (contextual) keyword
47
0
  if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
48
0
    Ident__except = PP.getIdentifierInfo("__except");
49
50
0
  return Ident__except;
51
0
}
52
53
Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
54
    : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
55
      Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
56
      ColonIsSacred(false), InMessageExpression(false),
57
46
      TemplateParameterDepth(0), ParsingInObjCContainer(false) {
58
46
  SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
59
46
  Tok.startToken();
60
46
  Tok.setKind(tok::eof);
61
46
  Actions.CurScope = nullptr;
62
46
  NumCachedScopes = 0;
63
46
  CurParsedObjCImpl = nullptr;
64
65
  // Add #pragma handlers. These are removed and destroyed in the
66
  // destructor.
67
46
  initializePragmaHandlers();
68
69
46
  CommentSemaHandler.reset(new ActionCommentHandler(actions));
70
46
  PP.addCommentHandler(CommentSemaHandler.get());
71
72
46
  PP.setCodeCompletionHandler(*this);
73
46
}
74
75
36.0k
DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
76
36.0k
  return Diags.Report(Loc, DiagID);
77
36.0k
}
78
79
11.7k
DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
80
11.7k
  return Diag(Tok.getLocation(), DiagID);
81
11.7k
}
82
83
/// Emits a diagnostic suggesting parentheses surrounding a
84
/// given range.
85
///
86
/// \param Loc The location where we'll emit the diagnostic.
87
/// \param DK The kind of diagnostic to emit.
88
/// \param ParenRange Source range enclosing code that should be parenthesized.
89
void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
90
0
                                SourceRange ParenRange) {
91
0
  SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
92
0
  if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
93
    // We can't display the parentheses, so just dig the
94
    // warning/error and return.
95
0
    Diag(Loc, DK);
96
0
    return;
97
0
  }
98
99
0
  Diag(Loc, DK)
100
0
    << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
101
0
    << FixItHint::CreateInsertion(EndLoc, ")");
102
0
}
103
104
4.67k
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
105
4.67k
  switch (ExpectedTok) {
106
4.66k
  case tok::semi:
107
4.66k
    return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
108
7
  default: return false;
109
4.67k
  }
110
4.67k
}
111
112
bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
113
4.67k
                              StringRef Msg) {
114
4.67k
  if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
115
1
    ConsumeAnyToken();
116
1
    return false;
117
1
  }
118
119
  // Detect common single-character typos and resume.
120
4.67k
  if (IsCommonTypo(ExpectedTok, Tok)) {
121
99
    SourceLocation Loc = Tok.getLocation();
122
99
    {
123
99
      DiagnosticBuilder DB = Diag(Loc, DiagID);
124
99
      DB << FixItHint::CreateReplacement(
125
99
                SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
126
99
      if (DiagID == diag::err_expected)
127
0
        DB << ExpectedTok;
128
99
      else if (DiagID == diag::err_expected_after)
129
0
        DB << Msg << ExpectedTok;
130
99
      else
131
99
        DB << Msg;
132
99
    }
133
134
    // Pretend there wasn't a problem.
135
99
    ConsumeAnyToken();
136
99
    return false;
137
99
  }
138
139
4.57k
  SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
140
4.57k
  const char *Spelling = nullptr;
141
4.57k
  if (EndLoc.isValid())
142
4.57k
    Spelling = tok::getPunctuatorSpelling(ExpectedTok);
143
144
4.57k
  DiagnosticBuilder DB =
145
4.57k
      Spelling
146
4.57k
          ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
147
4.57k
          : Diag(Tok, DiagID);
148
4.57k
  if (DiagID == diag::err_expected)
149
7
    DB << ExpectedTok;
150
4.56k
  else if (DiagID == diag::err_expected_after)
151
0
    DB << Msg << ExpectedTok;
152
4.56k
  else
153
4.56k
    DB << Msg;
154
155
4.57k
  return true;
156
4.67k
}
157
158
5.05k
bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
159
5.05k
  if (TryConsumeToken(tok::semi))
160
384
    return false;
161
162
4.67k
  if (Tok.is(tok::code_completion)) {
163
0
    handleUnexpectedCodeCompletionToken();
164
0
    return false;
165
0
  }
166
167
4.67k
  if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
168
4.67k
      NextToken().is(tok::semi)) {
169
4
    Diag(Tok, diag::err_extraneous_token_before_semi)
170
4
      << PP.getSpelling(Tok)
171
4
      << FixItHint::CreateRemoval(Tok.getLocation());
172
4
    ConsumeAnyToken(); // The ')' or ']'.
173
4
    ConsumeToken(); // The ';'.
174
4
    return false;
175
4
  }
176
177
4.66k
  return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
178
4.67k
}
179
180
439
void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
181
439
  if (!Tok.is(tok::semi)) return;
182
183
439
  bool HadMultipleSemis = false;
184
439
  SourceLocation StartLoc = Tok.getLocation();
185
439
  SourceLocation EndLoc = Tok.getLocation();
186
439
  ConsumeToken();
187
188
456
  while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
189
17
    HadMultipleSemis = true;
190
17
    EndLoc = Tok.getLocation();
191
17
    ConsumeToken();
192
17
  }
193
194
  // C++11 allows extra semicolons at namespace scope, but not in any of the
195
  // other contexts.
196
439
  if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
197
232
    if (getLangOpts().CPlusPlus11)
198
232
      Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
199
232
          << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
200
0
    else
201
0
      Diag(StartLoc, diag::ext_extra_semi_cxx11)
202
0
          << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
203
232
    return;
204
232
  }
205
206
207
  if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
207
207
    Diag(StartLoc, diag::ext_extra_semi)
208
207
        << Kind << DeclSpec::getSpecifierName(TST,
209
207
                                    Actions.getASTContext().getPrintingPolicy())
210
207
        << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
211
0
  else
212
    // A single semicolon is valid after a member function definition.
213
0
    Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
214
0
      << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
215
207
}
216
217
81
bool Parser::expectIdentifier() {
218
81
  if (Tok.is(tok::identifier))
219
41
    return false;
220
40
  if (const auto *II = Tok.getIdentifierInfo()) {
221
0
    if (II->isCPlusPlusKeyword(getLangOpts())) {
222
0
      Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
223
0
          << tok::identifier << Tok.getIdentifierInfo();
224
      // Objective-C++: Recover by treating this keyword as a valid identifier.
225
0
      return false;
226
0
    }
227
0
  }
228
40
  Diag(Tok, diag::err_expected) << tok::identifier;
229
40
  return true;
230
40
}
231
232
void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
233
4
                                tok::TokenKind FirstTokKind, CompoundToken Op) {
234
4
  if (FirstTokLoc.isInvalid())
235
0
    return;
236
4
  SourceLocation SecondTokLoc = Tok.getLocation();
237
238
  // If either token is in a macro, we expect both tokens to come from the same
239
  // macro expansion.
240
4
  if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
241
4
      PP.getSourceManager().getFileID(FirstTokLoc) !=
242
0
          PP.getSourceManager().getFileID(SecondTokLoc)) {
243
0
    Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
244
0
        << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
245
0
        << static_cast<int>(Op) << SourceRange(FirstTokLoc);
246
0
    Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
247
0
        << (FirstTokKind == Tok.getKind()) << Tok.getKind()
248
0
        << SourceRange(SecondTokLoc);
249
0
    return;
250
0
  }
251
252
  // We expect the tokens to abut.
253
4
  if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
254
1
    SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
255
1
    if (SpaceLoc.isInvalid())
256
0
      SpaceLoc = FirstTokLoc;
257
1
    Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
258
1
        << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
259
1
        << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
260
1
    return;
261
1
  }
262
4
}
263
264
//===----------------------------------------------------------------------===//
265
// Error recovery.
266
//===----------------------------------------------------------------------===//
267
268
282k
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
269
282k
  return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
270
282k
}
271
272
/// SkipUntil - Read tokens until we get to the specified token, then consume
273
/// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
274
/// token will ever occur, this skips to the next token, or to some likely
275
/// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
276
/// character.
277
///
278
/// If SkipUntil finds the specified token, it returns true, otherwise it
279
/// returns false.
280
207k
bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
281
  // We always want this function to skip at least one token if the first token
282
  // isn't T and if not at EOF.
283
207k
  bool isFirstTokenSkipped = true;
284
6.00M
  while (true) {
285
    // If we found one of the tokens, stop and return true.
286
11.9M
    for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
287
6.02M
      if (Tok.is(Toks[i])) {
288
87.1k
        if (HasFlagsSet(Flags, StopBeforeMatch)) {
289
          // Noop, don't consume the token.
290
86.6k
        } else {
291
86.6k
          ConsumeAnyToken();
292
86.6k
        }
293
87.1k
        return true;
294
87.1k
      }
295
6.02M
    }
296
297
    // Important special case: The caller has given up and just wants us to
298
    // skip the rest of the file. Do this without recursing, since we can
299
    // get here precisely because the caller detected too much recursion.
300
5.91M
    if (Toks.size() == 1 && Toks[0] == tok::eof &&
301
5.91M
        !HasFlagsSet(Flags, StopAtSemi) &&
302
5.91M
        !HasFlagsSet(Flags, StopAtCodeCompletion)) {
303
0
      while (Tok.isNot(tok::eof))
304
0
        ConsumeAnyToken();
305
0
      return true;
306
0
    }
307
308
5.91M
    switch (Tok.getKind()) {
309
15.4k
    case tok::eof:
310
      // Ran out of tokens.
311
15.4k
      return false;
312
313
0
    case tok::annot_pragma_openmp:
314
0
    case tok::annot_attr_openmp:
315
0
    case tok::annot_pragma_openmp_end:
316
      // Stop before an OpenMP pragma boundary.
317
0
      if (OpenMPDirectiveParsing)
318
0
        return false;
319
0
      ConsumeAnnotationToken();
320
0
      break;
321
0
    case tok::annot_pragma_openacc:
322
0
    case tok::annot_pragma_openacc_end:
323
      // Stop before an OpenACC pragma boundary.
324
0
      if (OpenACCDirectiveParsing)
325
0
        return false;
326
0
      ConsumeAnnotationToken();
327
0
      break;
328
0
    case tok::annot_module_begin:
329
0
    case tok::annot_module_end:
330
0
    case tok::annot_module_include:
331
0
    case tok::annot_repl_input_end:
332
      // Stop before we change submodules. They generally indicate a "good"
333
      // place to pick up parsing again (except in the special case where
334
      // we're trying to skip to EOF).
335
0
      return false;
336
337
0
    case tok::code_completion:
338
0
      if (!HasFlagsSet(Flags, StopAtCodeCompletion))
339
0
        handleUnexpectedCodeCompletionToken();
340
0
      return false;
341
342
55.4k
    case tok::l_paren:
343
      // Recursively skip properly-nested parens.
344
55.4k
      ConsumeParen();
345
55.4k
      if (HasFlagsSet(Flags, StopAtCodeCompletion))
346
0
        SkipUntil(tok::r_paren, StopAtCodeCompletion);
347
55.4k
      else
348
55.4k
        SkipUntil(tok::r_paren);
349
55.4k
      break;
350
44.7k
    case tok::l_square:
351
      // Recursively skip properly-nested square brackets.
352
44.7k
      ConsumeBracket();
353
44.7k
      if (HasFlagsSet(Flags, StopAtCodeCompletion))
354
0
        SkipUntil(tok::r_square, StopAtCodeCompletion);
355
44.7k
      else
356
44.7k
        SkipUntil(tok::r_square);
357
44.7k
      break;
358
44.2k
    case tok::l_brace:
359
      // Recursively skip properly-nested braces.
360
44.2k
      ConsumeBrace();
361
44.2k
      if (HasFlagsSet(Flags, StopAtCodeCompletion))
362
0
        SkipUntil(tok::r_brace, StopAtCodeCompletion);
363
44.2k
      else
364
44.2k
        SkipUntil(tok::r_brace);
365
44.2k
      break;
366
40.5k
    case tok::question:
367
      // Recursively skip ? ... : pairs; these function as brackets. But
368
      // still stop at a semicolon if requested.
369
40.5k
      ConsumeToken();
370
40.5k
      SkipUntil(tok::colon,
371
40.5k
                SkipUntilFlags(unsigned(Flags) &
372
40.5k
                               unsigned(StopAtCodeCompletion | StopAtSemi)));
373
40.5k
      break;
374
375
    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
376
    // Since the user wasn't looking for this token (if they were, it would
377
    // already be handled), this isn't balanced.  If there is a LHS token at a
378
    // higher level, we will assume that this matches the unbalanced token
379
    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
380
47.4k
    case tok::r_paren:
381
47.4k
      if (ParenCount && !isFirstTokenSkipped)
382
34.6k
        return false;  // Matches something.
383
12.8k
      ConsumeParen();
384
12.8k
      break;
385
50.0k
    case tok::r_square:
386
50.0k
      if (BracketCount && !isFirstTokenSkipped)
387
38.4k
        return false;  // Matches something.
388
11.5k
      ConsumeBracket();
389
11.5k
      break;
390
43.9k
    case tok::r_brace:
391
43.9k
      if (BraceCount && !isFirstTokenSkipped)
392
31.3k
        return false;  // Matches something.
393
12.5k
      ConsumeBrace();
394
12.5k
      break;
395
396
50.5k
    case tok::semi:
397
50.5k
      if (HasFlagsSet(Flags, StopAtSemi))
398
511
        return false;
399
50.5k
      [[fallthrough]];
400
5.57M
    default:
401
      // Skip this token.
402
5.57M
      ConsumeAnyToken();
403
5.57M
      break;
404
5.91M
    }
405
5.79M
    isFirstTokenSkipped = false;
406
5.79M
  }
407
207k
}
408
409
//===----------------------------------------------------------------------===//
410
// Scope manipulation
411
//===----------------------------------------------------------------------===//
412
413
/// EnterScope - Start a new scope.
414
190
void Parser::EnterScope(unsigned ScopeFlags) {
415
190
  if (NumCachedScopes) {
416
115
    Scope *N = ScopeCache[--NumCachedScopes];
417
115
    N->Init(getCurScope(), ScopeFlags);
418
115
    Actions.CurScope = N;
419
115
  } else {
420
75
    Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
421
75
  }
422
190
}
423
424
/// ExitScope - Pop a scope off the scope stack.
425
144
void Parser::ExitScope() {
426
144
  assert(getCurScope() && "Scope imbalance!");
427
428
  // Inform the actions module that this scope is going away if there are any
429
  // decls in it.
430
0
  Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
431
432
144
  Scope *OldScope = getCurScope();
433
144
  Actions.CurScope = OldScope->getParent();
434
435
144
  if (NumCachedScopes == ScopeCacheSize)
436
0
    delete OldScope;
437
144
  else
438
144
    ScopeCache[NumCachedScopes++] = OldScope;
439
144
}
440
441
/// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
442
/// this object does nothing.
443
Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
444
                                 bool ManageFlags)
445
0
  : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
446
0
  if (CurScope) {
447
0
    OldFlags = CurScope->getFlags();
448
0
    CurScope->setFlags(ScopeFlags);
449
0
  }
450
0
}
451
452
/// Restore the flags for the current scope to what they were before this
453
/// object overrode them.
454
0
Parser::ParseScopeFlags::~ParseScopeFlags() {
455
0
  if (CurScope)
456
0
    CurScope->setFlags(OldFlags);
457
0
}
458
459
460
//===----------------------------------------------------------------------===//
461
// C99 6.9: External Definitions.
462
//===----------------------------------------------------------------------===//
463
464
46
Parser::~Parser() {
465
  // If we still have scopes active, delete the scope tree.
466
46
  delete getCurScope();
467
46
  Actions.CurScope = nullptr;
468
469
  // Free the scope cache.
470
75
  for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
471
29
    delete ScopeCache[i];
472
473
46
  resetPragmaHandlers();
474
475
46
  PP.removeCommentHandler(CommentSemaHandler.get());
476
477
46
  PP.clearCodeCompletionHandler();
478
479
46
  DestroyTemplateIds();
480
46
}
481
482
/// Initialize - Warm up the parser.
483
///
484
46
void Parser::Initialize() {
485
  // Create the translation unit scope.  Install it as the current scope.
486
46
  assert(getCurScope() == nullptr && "A scope is already active?");
487
0
  EnterScope(Scope::DeclScope);
488
46
  Actions.ActOnTranslationUnitScope(getCurScope());
489
490
  // Initialization for Objective-C context sensitive keywords recognition.
491
  // Referenced in Parser::ParseObjCTypeQualifierList.
492
46
  if (getLangOpts().ObjC) {
493
23
    ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
494
23
    ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
495
23
    ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
496
23
    ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
497
23
    ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
498
23
    ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
499
23
    ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
500
23
    ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
501
23
    ObjCTypeQuals[objc_null_unspecified]
502
23
      = &PP.getIdentifierTable().get("null_unspecified");
503
23
  }
504
505
46
  Ident_instancetype = nullptr;
506
46
  Ident_final = nullptr;
507
46
  Ident_sealed = nullptr;
508
46
  Ident_abstract = nullptr;
509
46
  Ident_override = nullptr;
510
46
  Ident_GNU_final = nullptr;
511
46
  Ident_import = nullptr;
512
46
  Ident_module = nullptr;
513
514
46
  Ident_super = &PP.getIdentifierTable().get("super");
515
516
46
  Ident_vector = nullptr;
517
46
  Ident_bool = nullptr;
518
46
  Ident_Bool = nullptr;
519
46
  Ident_pixel = nullptr;
520
46
  if (getLangOpts().AltiVec || getLangOpts().ZVector) {
521
0
    Ident_vector = &PP.getIdentifierTable().get("vector");
522
0
    Ident_bool = &PP.getIdentifierTable().get("bool");
523
0
    Ident_Bool = &PP.getIdentifierTable().get("_Bool");
524
0
  }
525
46
  if (getLangOpts().AltiVec)
526
0
    Ident_pixel = &PP.getIdentifierTable().get("pixel");
527
528
46
  Ident_introduced = nullptr;
529
46
  Ident_deprecated = nullptr;
530
46
  Ident_obsoleted = nullptr;
531
46
  Ident_unavailable = nullptr;
532
46
  Ident_strict = nullptr;
533
46
  Ident_replacement = nullptr;
534
535
46
  Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
536
46
      nullptr;
537
538
46
  Ident__except = nullptr;
539
540
46
  Ident__exception_code = Ident__exception_info = nullptr;
541
46
  Ident__abnormal_termination = Ident___exception_code = nullptr;
542
46
  Ident___exception_info = Ident___abnormal_termination = nullptr;
543
46
  Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
544
46
  Ident_AbnormalTermination = nullptr;
545
546
46
  if(getLangOpts().Borland) {
547
0
    Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
548
0
    Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
549
0
    Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
550
0
    Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
551
0
    Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
552
0
    Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
553
0
    Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
554
0
    Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
555
0
    Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
556
557
0
    PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
558
0
    PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
559
0
    PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
560
0
    PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
561
0
    PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
562
0
    PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
563
0
    PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
564
0
    PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
565
0
    PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
566
0
  }
567
568
46
  if (getLangOpts().CPlusPlusModules) {
569
0
    Ident_import = PP.getIdentifierInfo("import");
570
0
    Ident_module = PP.getIdentifierInfo("module");
571
0
  }
572
573
46
  Actions.Initialize();
574
575
  // Prime the lexer look-ahead.
576
46
  ConsumeToken();
577
46
}
578
579
72
void Parser::DestroyTemplateIds() {
580
72
  for (TemplateIdAnnotation *Id : TemplateIds)
581
26
    Id->Destroy();
582
72
  TemplateIds.clear();
583
72
}
584
585
/// Parse the first top-level declaration in a translation unit.
586
///
587
///   translation-unit:
588
/// [C]     external-declaration
589
/// [C]     translation-unit external-declaration
590
/// [C++]   top-level-declaration-seq[opt]
591
/// [C++20] global-module-fragment[opt] module-declaration
592
///                 top-level-declaration-seq[opt] private-module-fragment[opt]
593
///
594
/// Note that in C, it is an error if there is no first declaration.
595
bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
596
46
                                    Sema::ModuleImportState &ImportState) {
597
46
  Actions.ActOnStartOfTranslationUnit();
598
599
  // For C++20 modules, a module decl must be the first in the TU.  We also
600
  // need to track module imports.
601
46
  ImportState = Sema::ModuleImportState::FirstDecl;
602
46
  bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
603
604
  // C11 6.9p1 says translation units must have at least one top-level
605
  // declaration. C++ doesn't have this restriction. We also don't want to
606
  // complain if we have a precompiled header, although technically if the PCH
607
  // is empty we should still emit the (pedantic) diagnostic.
608
  // If the main file is a header, we're only pretending it's a TU; don't warn.
609
46
  if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
610
46
      !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
611
0
    Diag(diag::ext_empty_translation_unit);
612
613
46
  return NoTopLevelDecls;
614
46
}
615
616
/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
617
/// action tells us to.  This returns true if the EOF was encountered.
618
///
619
///   top-level-declaration:
620
///           declaration
621
/// [C++20]   module-import-declaration
622
bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
623
34.7k
                               Sema::ModuleImportState &ImportState) {
624
34.7k
  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
625
626
  // Skip over the EOF token, flagging end of previous input for incremental
627
  // processing
628
34.7k
  if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
629
0
    ConsumeToken();
630
631
34.7k
  Result = nullptr;
632
34.7k
  switch (Tok.getKind()) {
633
0
  case tok::annot_pragma_unused:
634
0
    HandlePragmaUnused();
635
0
    return false;
636
637
0
  case tok::kw_export:
638
0
    switch (NextToken().getKind()) {
639
0
    case tok::kw_module:
640
0
      goto module_decl;
641
642
    // Note: no need to handle kw_import here. We only form kw_import under
643
    // the Standard C++ Modules, and in that case 'export import' is parsed as
644
    // an export-declaration containing an import-declaration.
645
646
    // Recognize context-sensitive C++20 'export module' and 'export import'
647
    // declarations.
648
0
    case tok::identifier: {
649
0
      IdentifierInfo *II = NextToken().getIdentifierInfo();
650
0
      if ((II == Ident_module || II == Ident_import) &&
651
0
          GetLookAheadToken(2).isNot(tok::coloncolon)) {
652
0
        if (II == Ident_module)
653
0
          goto module_decl;
654
0
        else
655
0
          goto import_decl;
656
0
      }
657
0
      break;
658
0
    }
659
660
0
    default:
661
0
      break;
662
0
    }
663
0
    break;
664
665
0
  case tok::kw_module:
666
0
  module_decl:
667
0
    Result = ParseModuleDecl(ImportState);
668
0
    return false;
669
670
0
  case tok::kw_import:
671
0
  import_decl: {
672
0
    Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
673
0
    Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
674
0
    return false;
675
0
  }
676
677
0
  case tok::annot_module_include: {
678
0
    auto Loc = Tok.getLocation();
679
0
    Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
680
    // FIXME: We need a better way to disambiguate C++ clang modules and
681
    // standard C++ modules.
682
0
    if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
683
0
      Actions.ActOnModuleInclude(Loc, Mod);
684
0
    else {
685
0
      DeclResult Import =
686
0
          Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
687
0
      Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
688
0
      Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
689
0
    }
690
0
    ConsumeAnnotationToken();
691
0
    return false;
692
0
  }
693
694
0
  case tok::annot_module_begin:
695
0
    Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
696
0
                                                    Tok.getAnnotationValue()));
697
0
    ConsumeAnnotationToken();
698
0
    ImportState = Sema::ModuleImportState::NotACXX20Module;
699
0
    return false;
700
701
0
  case tok::annot_module_end:
702
0
    Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
703
0
                                                  Tok.getAnnotationValue()));
704
0
    ConsumeAnnotationToken();
705
0
    ImportState = Sema::ModuleImportState::NotACXX20Module;
706
0
    return false;
707
708
46
  case tok::eof:
709
46
  case tok::annot_repl_input_end:
710
    // Check whether -fmax-tokens= was reached.
711
46
    if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
712
0
      PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
713
0
          << PP.getTokenCount() << PP.getMaxTokens();
714
0
      SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
715
0
      if (OverrideLoc.isValid()) {
716
0
        PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
717
0
      }
718
0
    }
719
720
    // Late template parsing can begin.
721
46
    Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
722
46
    Actions.ActOnEndOfTranslationUnit();
723
    //else don't tell Sema that we ended parsing: more input might come.
724
46
    return true;
725
726
11.0k
  case tok::identifier:
727
    // C++2a [basic.link]p3:
728
    //   A token sequence beginning with 'export[opt] module' or
729
    //   'export[opt] import' and not immediately followed by '::'
730
    //   is never interpreted as the declaration of a top-level-declaration.
731
11.0k
    if ((Tok.getIdentifierInfo() == Ident_module ||
732
11.0k
         Tok.getIdentifierInfo() == Ident_import) &&
733
11.0k
        NextToken().isNot(tok::coloncolon)) {
734
0
      if (Tok.getIdentifierInfo() == Ident_module)
735
0
        goto module_decl;
736
0
      else
737
0
        goto import_decl;
738
0
    }
739
11.0k
    break;
740
741
23.6k
  default:
742
23.6k
    break;
743
34.7k
  }
744
745
34.6k
  ParsedAttributes DeclAttrs(AttrFactory);
746
34.6k
  ParsedAttributes DeclSpecAttrs(AttrFactory);
747
  // GNU attributes are applied to the declaration specification while the
748
  // standard attributes are applied to the declaration.  We parse the two
749
  // attribute sets into different containters so we can apply them during
750
  // the regular parsing process.
751
34.6k
  while (MaybeParseCXX11Attributes(DeclAttrs) ||
752
34.6k
         MaybeParseGNUAttributes(DeclSpecAttrs))
753
3
    ;
754
755
34.6k
  Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
756
  // An empty Result might mean a line with ';' or some parsing error, ignore
757
  // it.
758
34.6k
  if (Result) {
759
5.50k
    if (ImportState == Sema::ModuleImportState::FirstDecl)
760
      // First decl was not modular.
761
40
      ImportState = Sema::ModuleImportState::NotACXX20Module;
762
5.46k
    else if (ImportState == Sema::ModuleImportState::ImportAllowed)
763
      // Non-imports disallow further imports.
764
0
      ImportState = Sema::ModuleImportState::ImportFinished;
765
5.46k
    else if (ImportState ==
766
5.46k
             Sema::ModuleImportState::PrivateFragmentImportAllowed)
767
      // Non-imports disallow further imports.
768
0
      ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;
769
5.50k
  }
770
34.6k
  return false;
771
34.7k
}
772
773
/// ParseExternalDeclaration:
774
///
775
/// The `Attrs` that are passed in are C++11 attributes and appertain to the
776
/// declaration.
777
///
778
///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
779
///         function-definition
780
///         declaration
781
/// [GNU]   asm-definition
782
/// [GNU]   __extension__ external-declaration
783
/// [OBJC]  objc-class-definition
784
/// [OBJC]  objc-class-declaration
785
/// [OBJC]  objc-alias-declaration
786
/// [OBJC]  objc-protocol-definition
787
/// [OBJC]  objc-method-definition
788
/// [OBJC]  @end
789
/// [C++]   linkage-specification
790
/// [GNU] asm-definition:
791
///         simple-asm-expr ';'
792
/// [C++11] empty-declaration
793
/// [C++11] attribute-declaration
794
///
795
/// [C++11] empty-declaration:
796
///           ';'
797
///
798
/// [C++0x/GNU] 'extern' 'template' declaration
799
///
800
/// [C++20] module-import-declaration
801
///
802
Parser::DeclGroupPtrTy
803
Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
804
                                 ParsedAttributes &DeclSpecAttrs,
805
34.6k
                                 ParsingDeclSpec *DS) {
806
34.6k
  DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
807
34.6k
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
808
809
34.6k
  if (PP.isCodeCompletionReached()) {
810
0
    cutOffParsing();
811
0
    return nullptr;
812
0
  }
813
814
34.6k
  Decl *SingleDecl = nullptr;
815
34.6k
  switch (Tok.getKind()) {
816
0
  case tok::annot_pragma_vis:
817
0
    HandlePragmaVisibility();
818
0
    return nullptr;
819
0
  case tok::annot_pragma_pack:
820
0
    HandlePragmaPack();
821
0
    return nullptr;
822
0
  case tok::annot_pragma_msstruct:
823
0
    HandlePragmaMSStruct();
824
0
    return nullptr;
825
0
  case tok::annot_pragma_align:
826
0
    HandlePragmaAlign();
827
0
    return nullptr;
828
0
  case tok::annot_pragma_weak:
829
0
    HandlePragmaWeak();
830
0
    return nullptr;
831
0
  case tok::annot_pragma_weakalias:
832
0
    HandlePragmaWeakAlias();
833
0
    return nullptr;
834
0
  case tok::annot_pragma_redefine_extname:
835
0
    HandlePragmaRedefineExtname();
836
0
    return nullptr;
837
0
  case tok::annot_pragma_fp_contract:
838
0
    HandlePragmaFPContract();
839
0
    return nullptr;
840
0
  case tok::annot_pragma_fenv_access:
841
0
  case tok::annot_pragma_fenv_access_ms:
842
0
    HandlePragmaFEnvAccess();
843
0
    return nullptr;
844
0
  case tok::annot_pragma_fenv_round:
845
0
    HandlePragmaFEnvRound();
846
0
    return nullptr;
847
0
  case tok::annot_pragma_cx_limited_range:
848
0
    HandlePragmaCXLimitedRange();
849
0
    return nullptr;
850
0
  case tok::annot_pragma_float_control:
851
0
    HandlePragmaFloatControl();
852
0
    return nullptr;
853
0
  case tok::annot_pragma_fp:
854
0
    HandlePragmaFP();
855
0
    break;
856
0
  case tok::annot_pragma_opencl_extension:
857
0
    HandlePragmaOpenCLExtension();
858
0
    return nullptr;
859
0
  case tok::annot_attr_openmp:
860
0
  case tok::annot_pragma_openmp: {
861
0
    AccessSpecifier AS = AS_none;
862
0
    return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
863
0
  }
864
0
  case tok::annot_pragma_openacc:
865
0
    return ParseOpenACCDirectiveDecl();
866
0
  case tok::annot_pragma_ms_pointers_to_members:
867
0
    HandlePragmaMSPointersToMembers();
868
0
    return nullptr;
869
0
  case tok::annot_pragma_ms_vtordisp:
870
0
    HandlePragmaMSVtorDisp();
871
0
    return nullptr;
872
0
  case tok::annot_pragma_ms_pragma:
873
0
    HandlePragmaMSPragma();
874
0
    return nullptr;
875
0
  case tok::annot_pragma_dump:
876
0
    HandlePragmaDump();
877
0
    return nullptr;
878
0
  case tok::annot_pragma_attribute:
879
0
    HandlePragmaAttribute();
880
0
    return nullptr;
881
439
  case tok::semi:
882
    // Either a C++11 empty-declaration or attribute-declaration.
883
439
    SingleDecl =
884
439
        Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
885
439
    ConsumeExtraSemi(OutsideFunction);
886
439
    break;
887
9.93k
  case tok::r_brace:
888
9.93k
    Diag(Tok, diag::err_extraneous_closing_brace);
889
9.93k
    ConsumeBrace();
890
9.93k
    return nullptr;
891
0
  case tok::eof:
892
0
    Diag(Tok, diag::err_expected_external_declaration);
893
0
    return nullptr;
894
0
  case tok::kw___extension__: {
895
    // __extension__ silences extension warnings in the subexpression.
896
0
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
897
0
    ConsumeToken();
898
0
    return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
899
0
  }
900
0
  case tok::kw_asm: {
901
0
    ProhibitAttributes(Attrs);
902
903
0
    SourceLocation StartLoc = Tok.getLocation();
904
0
    SourceLocation EndLoc;
905
906
0
    ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
907
908
    // Check if GNU-style InlineAsm is disabled.
909
    // Empty asm string is allowed because it will not introduce
910
    // any assembly code.
911
0
    if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
912
0
      const auto *SL = cast<StringLiteral>(Result.get());
913
0
      if (!SL->getString().trim().empty())
914
0
        Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
915
0
    }
916
917
0
    ExpectAndConsume(tok::semi, diag::err_expected_after,
918
0
                     "top-level asm block");
919
920
0
    if (Result.isInvalid())
921
0
      return nullptr;
922
0
    SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
923
0
    break;
924
0
  }
925
55
  case tok::at:
926
55
    return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
927
150
  case tok::minus:
928
347
  case tok::plus:
929
347
    if (!getLangOpts().ObjC) {
930
177
      Diag(Tok, diag::err_expected_external_declaration);
931
177
      ConsumeToken();
932
177
      return nullptr;
933
177
    }
934
170
    SingleDecl = ParseObjCMethodDefinition();
935
170
    break;
936
0
  case tok::code_completion:
937
0
    cutOffParsing();
938
0
    if (CurParsedObjCImpl) {
939
      // Code-complete Objective-C methods even without leading '-'/'+' prefix.
940
0
      Actions.CodeCompleteObjCMethodDecl(getCurScope(),
941
0
                                         /*IsInstanceMethod=*/std::nullopt,
942
0
                                         /*ReturnType=*/nullptr);
943
0
    }
944
945
0
    Sema::ParserCompletionContext PCC;
946
0
    if (CurParsedObjCImpl) {
947
0
      PCC = Sema::PCC_ObjCImplementation;
948
0
    } else if (PP.isIncrementalProcessingEnabled()) {
949
0
      PCC = Sema::PCC_TopLevelOrExpression;
950
0
    } else {
951
0
      PCC = Sema::PCC_Namespace;
952
0
    };
953
0
    Actions.CodeCompleteOrdinaryName(getCurScope(), PCC);
954
0
    return nullptr;
955
0
  case tok::kw_import: {
956
0
    Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
957
0
    if (getLangOpts().CPlusPlusModules) {
958
0
      llvm_unreachable("not expecting a c++20 import here");
959
0
      ProhibitAttributes(Attrs);
960
0
    }
961
0
    SingleDecl = ParseModuleImport(SourceLocation(), IS);
962
0
  } break;
963
0
  case tok::kw_export:
964
0
    if (getLangOpts().CPlusPlusModules) {
965
0
      ProhibitAttributes(Attrs);
966
0
      SingleDecl = ParseExportDeclaration();
967
0
      break;
968
0
    }
969
    // This must be 'export template'. Parse it so we can diagnose our lack
970
    // of support.
971
0
    [[fallthrough]];
972
0
  case tok::kw_using:
973
0
  case tok::kw_namespace:
974
0
  case tok::kw_typedef:
975
0
  case tok::kw_template:
976
0
  case tok::kw_static_assert:
977
0
  case tok::kw__Static_assert:
978
    // A function definition cannot start with any of these keywords.
979
0
    {
980
0
      SourceLocation DeclEnd;
981
0
      return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
982
0
                              DeclSpecAttrs);
983
0
    }
984
985
0
  case tok::kw_cbuffer:
986
0
  case tok::kw_tbuffer:
987
0
    if (getLangOpts().HLSL) {
988
0
      SourceLocation DeclEnd;
989
0
      return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
990
0
                              DeclSpecAttrs);
991
0
    }
992
0
    goto dont_know;
993
994
0
  case tok::kw_static:
995
    // Parse (then ignore) 'static' prior to a template instantiation. This is
996
    // a GCC extension that we intentionally do not support.
997
0
    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
998
0
      Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
999
0
        << 0;
1000
0
      SourceLocation DeclEnd;
1001
0
      return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1002
0
                              DeclSpecAttrs);
1003
0
    }
1004
0
    goto dont_know;
1005
1006
0
  case tok::kw_inline:
1007
0
    if (getLangOpts().CPlusPlus) {
1008
0
      tok::TokenKind NextKind = NextToken().getKind();
1009
1010
      // Inline namespaces. Allowed as an extension even in C++03.
1011
0
      if (NextKind == tok::kw_namespace) {
1012
0
        SourceLocation DeclEnd;
1013
0
        return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1014
0
                                DeclSpecAttrs);
1015
0
      }
1016
1017
      // Parse (then ignore) 'inline' prior to a template instantiation. This is
1018
      // a GCC extension that we intentionally do not support.
1019
0
      if (NextKind == tok::kw_template) {
1020
0
        Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
1021
0
          << 1;
1022
0
        SourceLocation DeclEnd;
1023
0
        return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1024
0
                                DeclSpecAttrs);
1025
0
      }
1026
0
    }
1027
0
    goto dont_know;
1028
1029
0
  case tok::kw_extern:
1030
0
    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
1031
      // Extern templates
1032
0
      SourceLocation ExternLoc = ConsumeToken();
1033
0
      SourceLocation TemplateLoc = ConsumeToken();
1034
0
      Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
1035
0
             diag::warn_cxx98_compat_extern_template :
1036
0
             diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1037
0
      SourceLocation DeclEnd;
1038
0
      return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
1039
0
          DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, Attrs));
1040
0
    }
1041
0
    goto dont_know;
1042
1043
0
  case tok::kw___if_exists:
1044
0
  case tok::kw___if_not_exists:
1045
0
    ParseMicrosoftIfExistsExternalDeclaration();
1046
0
    return nullptr;
1047
1048
0
  case tok::kw_module:
1049
0
    Diag(Tok, diag::err_unexpected_module_decl);
1050
0
    SkipUntil(tok::semi);
1051
0
    return nullptr;
1052
1053
23.8k
  default:
1054
23.8k
  dont_know:
1055
23.8k
    if (Tok.isEditorPlaceholder()) {
1056
0
      ConsumeToken();
1057
0
      return nullptr;
1058
0
    }
1059
23.8k
    if (getLangOpts().IncrementalExtensions &&
1060
23.8k
        !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1061
0
      return ParseTopLevelStmtDecl();
1062
1063
    // We can't tell whether this is a function-definition or declaration yet.
1064
23.8k
    if (!SingleDecl)
1065
23.8k
      return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1066
34.6k
  }
1067
1068
  // This routine returns a DeclGroup, if the thing we parsed only contains a
1069
  // single decl, convert it now.
1070
609
  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1071
34.6k
}
1072
1073
/// Determine whether the current token, if it occurs after a
1074
/// declarator, continues a declaration or declaration list.
1075
77
bool Parser::isDeclarationAfterDeclarator() {
1076
  // Check for '= delete' or '= default'
1077
77
  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1078
0
    const Token &KW = NextToken();
1079
0
    if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
1080
0
      return false;
1081
0
  }
1082
1083
77
  return Tok.is(tok::equal) ||      // int X()=  -> not a function def
1084
77
    Tok.is(tok::comma) ||           // int X(),  -> not a function def
1085
77
    Tok.is(tok::semi)  ||           // int X();  -> not a function def
1086
77
    Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
1087
77
    Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
1088
77
    (getLangOpts().CPlusPlus &&
1089
59
     Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
1090
77
}
1091
1092
/// Determine whether the current token, if it occurs after a
1093
/// declarator, indicates the start of a function definition.
1094
59
bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1095
59
  assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1096
59
  if (Tok.is(tok::l_brace))   // int X() {}
1097
0
    return true;
1098
1099
  // Handle K&R C argument lists: int X(f) int f; {}
1100
59
  if (!getLangOpts().CPlusPlus &&
1101
59
      Declarator.getFunctionTypeInfo().isKNRPrototype())
1102
0
    return isDeclarationSpecifier(ImplicitTypenameContext::No);
1103
1104
59
  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1105
0
    const Token &KW = NextToken();
1106
0
    return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
1107
0
  }
1108
1109
59
  return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
1110
59
         Tok.is(tok::kw_try);          // X() try { ... }
1111
59
}
1112
1113
/// Parse either a function-definition or a declaration.  We can't tell which
1114
/// we have until we read up to the compound-statement in function-definition.
1115
/// TemplateParams, if non-NULL, provides the template parameters when we're
1116
/// parsing a C++ template-declaration.
1117
///
1118
///       function-definition: [C99 6.9.1]
1119
///         decl-specs      declarator declaration-list[opt] compound-statement
1120
/// [C90] function-definition: [C99 6.7.1] - implicit int result
1121
/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
1122
///
1123
///       declaration: [C99 6.7]
1124
///         declaration-specifiers init-declarator-list[opt] ';'
1125
/// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
1126
/// [OMP]   threadprivate-directive
1127
/// [OMP]   allocate-directive                         [TODO]
1128
///
1129
Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1130
    ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1131
23.8k
    ParsingDeclSpec &DS, AccessSpecifier AS) {
1132
  // Because we assume that the DeclSpec has not yet been initialised, we simply
1133
  // overwrite the source range and attribute the provided leading declspec
1134
  // attributes.
1135
23.8k
  assert(DS.getSourceRange().isInvalid() &&
1136
23.8k
         "expected uninitialised source range");
1137
0
  DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1138
23.8k
  DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1139
23.8k
  DS.takeAttributesFrom(DeclSpecAttrs);
1140
1141
23.8k
  MaybeParseMicrosoftAttributes(DS.getAttributes());
1142
  // Parse the common declaration-specifiers piece.
1143
23.8k
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1144
23.8k
                             DeclSpecContext::DSC_top_level);
1145
1146
  // If we had a free-standing type definition with a missing semicolon, we
1147
  // may get this far before the problem becomes obvious.
1148
23.8k
  if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1149
0
                                   DS, AS, DeclSpecContext::DSC_top_level))
1150
0
    return nullptr;
1151
1152
  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1153
  // declaration-specifiers init-declarator-list[opt] ';'
1154
23.8k
  if (Tok.is(tok::semi)) {
1155
39
    auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1156
0
      assert(DeclSpec::isDeclRep(TKind));
1157
0
      switch(TKind) {
1158
0
      case DeclSpec::TST_class:
1159
0
        return 5;
1160
0
      case DeclSpec::TST_struct:
1161
0
        return 6;
1162
0
      case DeclSpec::TST_union:
1163
0
        return 5;
1164
0
      case DeclSpec::TST_enum:
1165
0
        return 4;
1166
0
      case DeclSpec::TST_interface:
1167
0
        return 9;
1168
0
      default:
1169
0
        llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1170
0
      }
1171
1172
0
    };
1173
    // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1174
39
    SourceLocation CorrectLocationForAttributes =
1175
39
        DeclSpec::isDeclRep(DS.getTypeSpecType())
1176
39
            ? DS.getTypeSpecTypeLoc().getLocWithOffset(
1177
0
                  LengthOfTSTToken(DS.getTypeSpecType()))
1178
39
            : SourceLocation();
1179
39
    ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1180
39
    ConsumeToken();
1181
39
    RecordDecl *AnonRecord = nullptr;
1182
39
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1183
39
        getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1184
39
    DS.complete(TheDecl);
1185
39
    Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1186
39
    if (AnonRecord) {
1187
0
      Decl* decls[] = {AnonRecord, TheDecl};
1188
0
      return Actions.BuildDeclaratorGroup(decls);
1189
0
    }
1190
39
    return Actions.ConvertDeclToDeclGroup(TheDecl);
1191
39
  }
1192
1193
23.8k
  if (DS.hasTagDefinition())
1194
0
    Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
1195
1196
  // ObjC2 allows prefix attributes on class interfaces and protocols.
1197
  // FIXME: This still needs better diagnostics. We should only accept
1198
  // attributes here, no types, etc.
1199
23.8k
  if (getLangOpts().ObjC && Tok.is(tok::at)) {
1200
144
    SourceLocation AtLoc = ConsumeToken(); // the "@"
1201
144
    if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1202
144
        !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1203
144
        !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1204
144
      Diag(Tok, diag::err_objc_unexpected_attr);
1205
144
      SkipUntil(tok::semi);
1206
144
      return nullptr;
1207
144
    }
1208
1209
0
    DS.abort();
1210
0
    DS.takeAttributesFrom(Attrs);
1211
1212
0
    const char *PrevSpec = nullptr;
1213
0
    unsigned DiagID;
1214
0
    if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1215
0
                           Actions.getASTContext().getPrintingPolicy()))
1216
0
      Diag(AtLoc, DiagID) << PrevSpec;
1217
1218
0
    if (Tok.isObjCAtKeyword(tok::objc_protocol))
1219
0
      return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1220
1221
0
    if (Tok.isObjCAtKeyword(tok::objc_implementation))
1222
0
      return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1223
1224
0
    return Actions.ConvertDeclToDeclGroup(
1225
0
            ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1226
0
  }
1227
1228
  // If the declspec consisted only of 'extern' and we have a string
1229
  // literal following it, this must be a C++ linkage specifier like
1230
  // 'extern "C"'.
1231
23.7k
  if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1232
23.7k
      DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1233
23.7k
      DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1234
0
    ProhibitAttributes(Attrs);
1235
0
    Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1236
0
    return Actions.ConvertDeclToDeclGroup(TheDecl);
1237
0
  }
1238
1239
23.7k
  return ParseDeclGroup(DS, DeclaratorContext::File, Attrs);
1240
23.7k
}
1241
1242
Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1243
    ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1244
23.8k
    ParsingDeclSpec *DS, AccessSpecifier AS) {
1245
  // Add an enclosing time trace scope for a bunch of small scopes with
1246
  // "EvaluateAsConstExpr".
1247
23.8k
  llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {
1248
0
    return Tok.getLocation().printToString(
1249
0
        Actions.getASTContext().getSourceManager());
1250
0
  });
1251
1252
23.8k
  if (DS) {
1253
0
    return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1254
23.8k
  } else {
1255
23.8k
    ParsingDeclSpec PDS(*this);
1256
    // Must temporarily exit the objective-c container scope for
1257
    // parsing c constructs and re-enter objc container scope
1258
    // afterwards.
1259
23.8k
    ObjCDeclContextSwitch ObjCDC(*this);
1260
1261
23.8k
    return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1262
23.8k
  }
1263
23.8k
}
1264
1265
/// ParseFunctionDefinition - We parsed and verified that the specified
1266
/// Declarator is well formed.  If this is a K&R-style function, read the
1267
/// parameters declaration-list, then start the compound-statement.
1268
///
1269
///       function-definition: [C99 6.9.1]
1270
///         decl-specs      declarator declaration-list[opt] compound-statement
1271
/// [C90] function-definition: [C99 6.7.1] - implicit int result
1272
/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
1273
/// [C++] function-definition: [C++ 8.4]
1274
///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
1275
///         function-body
1276
/// [C++] function-definition: [C++ 8.4]
1277
///         decl-specifier-seq[opt] declarator function-try-block
1278
///
1279
Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1280
                                      const ParsedTemplateInfo &TemplateInfo,
1281
0
                                      LateParsedAttrList *LateParsedAttrs) {
1282
0
  llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {
1283
0
    return Actions.GetNameForDeclarator(D).getName().getAsString();
1284
0
  });
1285
1286
  // Poison SEH identifiers so they are flagged as illegal in function bodies.
1287
0
  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1288
0
  const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1289
0
  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1290
1291
  // If this is C89 and the declspecs were completely missing, fudge in an
1292
  // implicit int.  We do this here because this is the only place where
1293
  // declaration-specifiers are completely optional in the grammar.
1294
0
  if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
1295
0
    Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
1296
0
        << D.getDeclSpec().getSourceRange();
1297
0
    const char *PrevSpec;
1298
0
    unsigned DiagID;
1299
0
    const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1300
0
    D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1301
0
                                           D.getIdentifierLoc(),
1302
0
                                           PrevSpec, DiagID,
1303
0
                                           Policy);
1304
0
    D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1305
0
  }
1306
1307
  // If this declaration was formed with a K&R-style identifier list for the
1308
  // arguments, parse declarations for all of the args next.
1309
  // int foo(a,b) int a; float b; {}
1310
0
  if (FTI.isKNRPrototype())
1311
0
    ParseKNRParamDeclarations(D);
1312
1313
  // We should have either an opening brace or, in a C++ constructor,
1314
  // we may have a colon.
1315
0
  if (Tok.isNot(tok::l_brace) &&
1316
0
      (!getLangOpts().CPlusPlus ||
1317
0
       (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1318
0
        Tok.isNot(tok::equal)))) {
1319
0
    Diag(Tok, diag::err_expected_fn_body);
1320
1321
    // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1322
0
    SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1323
1324
    // If we didn't find the '{', bail out.
1325
0
    if (Tok.isNot(tok::l_brace))
1326
0
      return nullptr;
1327
0
  }
1328
1329
  // Check to make sure that any normal attributes are allowed to be on
1330
  // a definition.  Late parsed attributes are checked at the end.
1331
0
  if (Tok.isNot(tok::equal)) {
1332
0
    for (const ParsedAttr &AL : D.getAttributes())
1333
0
      if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1334
0
        Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1335
0
  }
1336
1337
  // In delayed template parsing mode, for function template we consume the
1338
  // tokens and store them for late parsing at the end of the translation unit.
1339
0
  if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1340
0
      TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1341
0
      Actions.canDelayFunctionBody(D)) {
1342
0
    MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1343
1344
0
    ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1345
0
                                   Scope::CompoundStmtScope);
1346
0
    Scope *ParentScope = getCurScope()->getParent();
1347
1348
0
    D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1349
0
    Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1350
0
                                        TemplateParameterLists);
1351
0
    D.complete(DP);
1352
0
    D.getMutableDeclSpec().abort();
1353
1354
0
    if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1355
0
        trySkippingFunctionBody()) {
1356
0
      BodyScope.Exit();
1357
0
      return Actions.ActOnSkippedFunctionBody(DP);
1358
0
    }
1359
1360
0
    CachedTokens Toks;
1361
0
    LexTemplateFunctionForLateParsing(Toks);
1362
1363
0
    if (DP) {
1364
0
      FunctionDecl *FnD = DP->getAsFunction();
1365
0
      Actions.CheckForFunctionRedefinition(FnD);
1366
0
      Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1367
0
    }
1368
0
    return DP;
1369
0
  }
1370
0
  else if (CurParsedObjCImpl &&
1371
0
           !TemplateInfo.TemplateParams &&
1372
0
           (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1373
0
            Tok.is(tok::colon)) &&
1374
0
      Actions.CurContext->isTranslationUnit()) {
1375
0
    ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1376
0
                                   Scope::CompoundStmtScope);
1377
0
    Scope *ParentScope = getCurScope()->getParent();
1378
1379
0
    D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1380
0
    Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1381
0
                                              MultiTemplateParamsArg());
1382
0
    D.complete(FuncDecl);
1383
0
    D.getMutableDeclSpec().abort();
1384
0
    if (FuncDecl) {
1385
      // Consume the tokens and store them for later parsing.
1386
0
      StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1387
0
      CurParsedObjCImpl->HasCFunction = true;
1388
0
      return FuncDecl;
1389
0
    }
1390
    // FIXME: Should we really fall through here?
1391
0
  }
1392
1393
  // Enter a scope for the function body.
1394
0
  ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1395
0
                                 Scope::CompoundStmtScope);
1396
1397
  // Parse function body eagerly if it is either '= delete;' or '= default;' as
1398
  // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1399
0
  Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
1400
0
  SourceLocation KWLoc;
1401
0
  if (TryConsumeToken(tok::equal)) {
1402
0
    assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1403
1404
0
    if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1405
0
      Diag(KWLoc, getLangOpts().CPlusPlus11
1406
0
                      ? diag::warn_cxx98_compat_defaulted_deleted_function
1407
0
                      : diag::ext_defaulted_deleted_function)
1408
0
          << 1 /* deleted */;
1409
0
      BodyKind = Sema::FnBodyKind::Delete;
1410
0
    } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1411
0
      Diag(KWLoc, getLangOpts().CPlusPlus11
1412
0
                      ? diag::warn_cxx98_compat_defaulted_deleted_function
1413
0
                      : diag::ext_defaulted_deleted_function)
1414
0
          << 0 /* defaulted */;
1415
0
      BodyKind = Sema::FnBodyKind::Default;
1416
0
    } else {
1417
0
      llvm_unreachable("function definition after = not 'delete' or 'default'");
1418
0
    }
1419
1420
0
    if (Tok.is(tok::comma)) {
1421
0
      Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1422
0
          << (BodyKind == Sema::FnBodyKind::Delete);
1423
0
      SkipUntil(tok::semi);
1424
0
    } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1425
0
                                BodyKind == Sema::FnBodyKind::Delete
1426
0
                                    ? "delete"
1427
0
                                    : "default")) {
1428
0
      SkipUntil(tok::semi);
1429
0
    }
1430
0
  }
1431
1432
  // Tell the actions module that we have entered a function definition with the
1433
  // specified Declarator for the function.
1434
0
  Sema::SkipBodyInfo SkipBody;
1435
0
  Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1436
0
                                              TemplateInfo.TemplateParams
1437
0
                                                  ? *TemplateInfo.TemplateParams
1438
0
                                                  : MultiTemplateParamsArg(),
1439
0
                                              &SkipBody, BodyKind);
1440
1441
0
  if (SkipBody.ShouldSkip) {
1442
    // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1443
0
    if (BodyKind == Sema::FnBodyKind::Other)
1444
0
      SkipFunctionBody();
1445
1446
    // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
1447
    // and it would be popped in ActOnFinishFunctionBody.
1448
    // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
1449
    //
1450
    // Do not call PopExpressionEvaluationContext() if it is a lambda because
1451
    // one is already popped when finishing the lambda in BuildLambdaExpr().
1452
    //
1453
    // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1454
    // and PopExpressionEvaluationContext().
1455
0
    if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
1456
0
      Actions.PopExpressionEvaluationContext();
1457
0
    return Res;
1458
0
  }
1459
1460
  // Break out of the ParsingDeclarator context before we parse the body.
1461
0
  D.complete(Res);
1462
1463
  // Break out of the ParsingDeclSpec context, too.  This const_cast is
1464
  // safe because we're always the sole owner.
1465
0
  D.getMutableDeclSpec().abort();
1466
1467
0
  if (BodyKind != Sema::FnBodyKind::Other) {
1468
0
    Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind);
1469
0
    Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1470
0
    Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1471
0
    return Res;
1472
0
  }
1473
1474
  // With abbreviated function templates - we need to explicitly add depth to
1475
  // account for the implicit template parameter list induced by the template.
1476
0
  if (const auto *Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1477
0
      Template && Template->isAbbreviated() &&
1478
0
      Template->getTemplateParameters()->getParam(0)->isImplicit())
1479
    // First template parameter is implicit - meaning no explicit template
1480
    // parameter list was specified.
1481
0
    CurTemplateDepthTracker.addDepth(1);
1482
1483
0
  if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1484
0
      trySkippingFunctionBody()) {
1485
0
    BodyScope.Exit();
1486
0
    Actions.ActOnSkippedFunctionBody(Res);
1487
0
    return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1488
0
  }
1489
1490
0
  if (Tok.is(tok::kw_try))
1491
0
    return ParseFunctionTryBlock(Res, BodyScope);
1492
1493
  // If we have a colon, then we're probably parsing a C++
1494
  // ctor-initializer.
1495
0
  if (Tok.is(tok::colon)) {
1496
0
    ParseConstructorInitializer(Res);
1497
1498
    // Recover from error.
1499
0
    if (!Tok.is(tok::l_brace)) {
1500
0
      BodyScope.Exit();
1501
0
      Actions.ActOnFinishFunctionBody(Res, nullptr);
1502
0
      return Res;
1503
0
    }
1504
0
  } else
1505
0
    Actions.ActOnDefaultCtorInitializers(Res);
1506
1507
  // Late attributes are parsed in the same scope as the function body.
1508
0
  if (LateParsedAttrs)
1509
0
    ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1510
1511
0
  return ParseFunctionStatementBody(Res, BodyScope);
1512
0
}
1513
1514
0
void Parser::SkipFunctionBody() {
1515
0
  if (Tok.is(tok::equal)) {
1516
0
    SkipUntil(tok::semi);
1517
0
    return;
1518
0
  }
1519
1520
0
  bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1521
0
  if (IsFunctionTryBlock)
1522
0
    ConsumeToken();
1523
1524
0
  CachedTokens Skipped;
1525
0
  if (ConsumeAndStoreFunctionPrologue(Skipped))
1526
0
    SkipMalformedDecl();
1527
0
  else {
1528
0
    SkipUntil(tok::r_brace);
1529
0
    while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1530
0
      SkipUntil(tok::l_brace);
1531
0
      SkipUntil(tok::r_brace);
1532
0
    }
1533
0
  }
1534
0
}
1535
1536
/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1537
/// types for a function with a K&R-style identifier list for arguments.
1538
0
void Parser::ParseKNRParamDeclarations(Declarator &D) {
1539
  // We know that the top-level of this declarator is a function.
1540
0
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1541
1542
  // Enter function-declaration scope, limiting any declarators to the
1543
  // function prototype scope, including parameter declarators.
1544
0
  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1545
0
                            Scope::FunctionDeclarationScope | Scope::DeclScope);
1546
1547
  // Read all the argument declarations.
1548
0
  while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
1549
0
    SourceLocation DSStart = Tok.getLocation();
1550
1551
    // Parse the common declaration-specifiers piece.
1552
0
    DeclSpec DS(AttrFactory);
1553
0
    ParseDeclarationSpecifiers(DS);
1554
1555
    // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1556
    // least one declarator'.
1557
    // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1558
    // the declarations though.  It's trivial to ignore them, really hard to do
1559
    // anything else with them.
1560
0
    if (TryConsumeToken(tok::semi)) {
1561
0
      Diag(DSStart, diag::err_declaration_does_not_declare_param);
1562
0
      continue;
1563
0
    }
1564
1565
    // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1566
    // than register.
1567
0
    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1568
0
        DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1569
0
      Diag(DS.getStorageClassSpecLoc(),
1570
0
           diag::err_invalid_storage_class_in_func_decl);
1571
0
      DS.ClearStorageClassSpecs();
1572
0
    }
1573
0
    if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1574
0
      Diag(DS.getThreadStorageClassSpecLoc(),
1575
0
           diag::err_invalid_storage_class_in_func_decl);
1576
0
      DS.ClearStorageClassSpecs();
1577
0
    }
1578
1579
    // Parse the first declarator attached to this declspec.
1580
0
    Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1581
0
                              DeclaratorContext::KNRTypeList);
1582
0
    ParseDeclarator(ParmDeclarator);
1583
1584
    // Handle the full declarator list.
1585
0
    while (true) {
1586
      // If attributes are present, parse them.
1587
0
      MaybeParseGNUAttributes(ParmDeclarator);
1588
1589
      // Ask the actions module to compute the type for this declarator.
1590
0
      Decl *Param =
1591
0
        Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1592
1593
0
      if (Param &&
1594
          // A missing identifier has already been diagnosed.
1595
0
          ParmDeclarator.getIdentifier()) {
1596
1597
        // Scan the argument list looking for the correct param to apply this
1598
        // type.
1599
0
        for (unsigned i = 0; ; ++i) {
1600
          // C99 6.9.1p6: those declarators shall declare only identifiers from
1601
          // the identifier list.
1602
0
          if (i == FTI.NumParams) {
1603
0
            Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1604
0
              << ParmDeclarator.getIdentifier();
1605
0
            break;
1606
0
          }
1607
1608
0
          if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1609
            // Reject redefinitions of parameters.
1610
0
            if (FTI.Params[i].Param) {
1611
0
              Diag(ParmDeclarator.getIdentifierLoc(),
1612
0
                   diag::err_param_redefinition)
1613
0
                 << ParmDeclarator.getIdentifier();
1614
0
            } else {
1615
0
              FTI.Params[i].Param = Param;
1616
0
            }
1617
0
            break;
1618
0
          }
1619
0
        }
1620
0
      }
1621
1622
      // If we don't have a comma, it is either the end of the list (a ';') or
1623
      // an error, bail out.
1624
0
      if (Tok.isNot(tok::comma))
1625
0
        break;
1626
1627
0
      ParmDeclarator.clear();
1628
1629
      // Consume the comma.
1630
0
      ParmDeclarator.setCommaLoc(ConsumeToken());
1631
1632
      // Parse the next declarator.
1633
0
      ParseDeclarator(ParmDeclarator);
1634
0
    }
1635
1636
    // Consume ';' and continue parsing.
1637
0
    if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1638
0
      continue;
1639
1640
    // Otherwise recover by skipping to next semi or mandatory function body.
1641
0
    if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1642
0
      break;
1643
0
    TryConsumeToken(tok::semi);
1644
0
  }
1645
1646
  // The actions module must verify that all arguments were declared.
1647
0
  Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1648
0
}
1649
1650
1651
/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1652
/// allowed to be a wide string, and is not subject to character translation.
1653
/// Unlike GCC, we also diagnose an empty string literal when parsing for an
1654
/// asm label as opposed to an asm statement, because such a construct does not
1655
/// behave well.
1656
///
1657
/// [GNU] asm-string-literal:
1658
///         string-literal
1659
///
1660
0
ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1661
0
  if (!isTokenStringLiteral()) {
1662
0
    Diag(Tok, diag::err_expected_string_literal)
1663
0
      << /*Source='in...'*/0 << "'asm'";
1664
0
    return ExprError();
1665
0
  }
1666
1667
0
  ExprResult AsmString(ParseStringLiteralExpression());
1668
0
  if (!AsmString.isInvalid()) {
1669
0
    const auto *SL = cast<StringLiteral>(AsmString.get());
1670
0
    if (!SL->isOrdinary()) {
1671
0
      Diag(Tok, diag::err_asm_operand_wide_string_literal)
1672
0
        << SL->isWide()
1673
0
        << SL->getSourceRange();
1674
0
      return ExprError();
1675
0
    }
1676
0
    if (ForAsmLabel && SL->getString().empty()) {
1677
0
      Diag(Tok, diag::err_asm_operand_wide_string_literal)
1678
0
          << 2 /* an empty */ << SL->getSourceRange();
1679
0
      return ExprError();
1680
0
    }
1681
0
  }
1682
0
  return AsmString;
1683
0
}
1684
1685
/// ParseSimpleAsm
1686
///
1687
/// [GNU] simple-asm-expr:
1688
///         'asm' '(' asm-string-literal ')'
1689
///
1690
0
ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1691
0
  assert(Tok.is(tok::kw_asm) && "Not an asm!");
1692
0
  SourceLocation Loc = ConsumeToken();
1693
1694
0
  if (isGNUAsmQualifier(Tok)) {
1695
    // Remove from the end of 'asm' to the end of the asm qualifier.
1696
0
    SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1697
0
                             PP.getLocForEndOfToken(Tok.getLocation()));
1698
0
    Diag(Tok, diag::err_global_asm_qualifier_ignored)
1699
0
        << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1700
0
        << FixItHint::CreateRemoval(RemovalRange);
1701
0
    ConsumeToken();
1702
0
  }
1703
1704
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
1705
0
  if (T.consumeOpen()) {
1706
0
    Diag(Tok, diag::err_expected_lparen_after) << "asm";
1707
0
    return ExprError();
1708
0
  }
1709
1710
0
  ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1711
1712
0
  if (!Result.isInvalid()) {
1713
    // Close the paren and get the location of the end bracket
1714
0
    T.consumeClose();
1715
0
    if (EndLoc)
1716
0
      *EndLoc = T.getCloseLocation();
1717
0
  } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1718
0
    if (EndLoc)
1719
0
      *EndLoc = Tok.getLocation();
1720
0
    ConsumeParen();
1721
0
  }
1722
1723
0
  return Result;
1724
0
}
1725
1726
/// Get the TemplateIdAnnotation from the token and put it in the
1727
/// cleanup pool so that it gets destroyed when parsing the current top level
1728
/// declaration is finished.
1729
48
TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1730
48
  assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1731
0
  TemplateIdAnnotation *
1732
48
      Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1733
48
  return Id;
1734
48
}
1735
1736
0
void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1737
  // Push the current token back into the token stream (or revert it if it is
1738
  // cached) and use an annotation scope token for current token.
1739
0
  if (PP.isBacktrackEnabled())
1740
0
    PP.RevertCachedTokens(1);
1741
0
  else
1742
0
    PP.EnterToken(Tok, /*IsReinject=*/true);
1743
0
  Tok.setKind(tok::annot_cxxscope);
1744
0
  Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1745
0
  Tok.setAnnotationRange(SS.getRange());
1746
1747
  // In case the tokens were cached, have Preprocessor replace them
1748
  // with the annotation token.  We don't need to do this if we've
1749
  // just reverted back to a prior state.
1750
0
  if (IsNewAnnotation)
1751
0
    PP.AnnotateCachedTokens(Tok);
1752
0
}
1753
1754
/// Attempt to classify the name at the current token position. This may
1755
/// form a type, scope or primary expression annotation, or replace the token
1756
/// with a typo-corrected keyword. This is only appropriate when the current
1757
/// name must refer to an entity which has already been declared.
1758
///
1759
/// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1760
///        no typo correction will be performed.
1761
/// \param AllowImplicitTypename Whether we are in a context where a dependent
1762
///        nested-name-specifier without typename is treated as a type (e.g.
1763
///        T::type).
1764
Parser::AnnotatedNameKind
1765
Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1766
178
                        ImplicitTypenameContext AllowImplicitTypename) {
1767
178
  assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1768
1769
0
  const bool EnteringContext = false;
1770
178
  const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1771
1772
178
  CXXScopeSpec SS;
1773
178
  if (getLangOpts().CPlusPlus &&
1774
178
      ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1775
178
                                     /*ObjectHasErrors=*/false,
1776
178
                                     EnteringContext))
1777
0
    return ANK_Error;
1778
1779
178
  if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1780
0
    if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1781
0
                                                  AllowImplicitTypename))
1782
0
      return ANK_Error;
1783
0
    return ANK_Unresolved;
1784
0
  }
1785
1786
178
  IdentifierInfo *Name = Tok.getIdentifierInfo();
1787
178
  SourceLocation NameLoc = Tok.getLocation();
1788
1789
  // FIXME: Move the tentative declaration logic into ClassifyName so we can
1790
  // typo-correct to tentatively-declared identifiers.
1791
178
  if (isTentativelyDeclared(Name) && SS.isEmpty()) {
1792
    // Identifier has been tentatively declared, and thus cannot be resolved as
1793
    // an expression. Fall back to annotating it as a type.
1794
0
    if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1795
0
                                                  AllowImplicitTypename))
1796
0
      return ANK_Error;
1797
0
    return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1798
0
  }
1799
1800
178
  Token Next = NextToken();
1801
1802
  // Look up and classify the identifier. We don't perform any typo-correction
1803
  // after a scope specifier, because in general we can't recover from typos
1804
  // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1805
  // jump back into scope specifier parsing).
1806
178
  Sema::NameClassification Classification = Actions.ClassifyName(
1807
178
      getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1808
1809
  // If name lookup found nothing and we guessed that this was a template name,
1810
  // double-check before committing to that interpretation. C++20 requires that
1811
  // we interpret this as a template-id if it can be, but if it can't be, then
1812
  // this is an error recovery case.
1813
178
  if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1814
178
      isTemplateArgumentList(1) == TPResult::False) {
1815
    // It's not a template-id; re-classify without the '<' as a hint.
1816
0
    Token FakeNext = Next;
1817
0
    FakeNext.setKind(tok::unknown);
1818
0
    Classification =
1819
0
        Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1820
0
                             SS.isEmpty() ? CCC : nullptr);
1821
0
  }
1822
1823
178
  switch (Classification.getKind()) {
1824
0
  case Sema::NC_Error:
1825
0
    return ANK_Error;
1826
1827
0
  case Sema::NC_Keyword:
1828
    // The identifier was typo-corrected to a keyword.
1829
0
    Tok.setIdentifierInfo(Name);
1830
0
    Tok.setKind(Name->getTokenID());
1831
0
    PP.TypoCorrectToken(Tok);
1832
0
    if (SS.isNotEmpty())
1833
0
      AnnotateScopeToken(SS, !WasScopeAnnotation);
1834
    // We've "annotated" this as a keyword.
1835
0
    return ANK_Success;
1836
1837
135
  case Sema::NC_Unknown:
1838
    // It's not something we know about. Leave it unannotated.
1839
135
    break;
1840
1841
0
  case Sema::NC_Type: {
1842
0
    if (TryAltiVecVectorToken())
1843
      // vector has been found as a type id when altivec is enabled but
1844
      // this is followed by a declaration specifier so this is really the
1845
      // altivec vector token.  Leave it unannotated.
1846
0
      break;
1847
0
    SourceLocation BeginLoc = NameLoc;
1848
0
    if (SS.isNotEmpty())
1849
0
      BeginLoc = SS.getBeginLoc();
1850
1851
    /// An Objective-C object type followed by '<' is a specialization of
1852
    /// a parameterized class type or a protocol-qualified type.
1853
0
    ParsedType Ty = Classification.getType();
1854
0
    if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1855
0
        (Ty.get()->isObjCObjectType() ||
1856
0
         Ty.get()->isObjCObjectPointerType())) {
1857
      // Consume the name.
1858
0
      SourceLocation IdentifierLoc = ConsumeToken();
1859
0
      SourceLocation NewEndLoc;
1860
0
      TypeResult NewType
1861
0
          = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1862
0
                                                   /*consumeLastToken=*/false,
1863
0
                                                   NewEndLoc);
1864
0
      if (NewType.isUsable())
1865
0
        Ty = NewType.get();
1866
0
      else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1867
0
        return ANK_Error;
1868
0
    }
1869
1870
0
    Tok.setKind(tok::annot_typename);
1871
0
    setTypeAnnotation(Tok, Ty);
1872
0
    Tok.setAnnotationEndLoc(Tok.getLocation());
1873
0
    Tok.setLocation(BeginLoc);
1874
0
    PP.AnnotateCachedTokens(Tok);
1875
0
    return ANK_Success;
1876
0
  }
1877
1878
0
  case Sema::NC_OverloadSet:
1879
0
    Tok.setKind(tok::annot_overload_set);
1880
0
    setExprAnnotation(Tok, Classification.getExpression());
1881
0
    Tok.setAnnotationEndLoc(NameLoc);
1882
0
    if (SS.isNotEmpty())
1883
0
      Tok.setLocation(SS.getBeginLoc());
1884
0
    PP.AnnotateCachedTokens(Tok);
1885
0
    return ANK_Success;
1886
1887
43
  case Sema::NC_NonType:
1888
43
    if (TryAltiVecVectorToken())
1889
      // vector has been found as a non-type id when altivec is enabled but
1890
      // this is followed by a declaration specifier so this is really the
1891
      // altivec vector token.  Leave it unannotated.
1892
0
      break;
1893
43
    Tok.setKind(tok::annot_non_type);
1894
43
    setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1895
43
    Tok.setLocation(NameLoc);
1896
43
    Tok.setAnnotationEndLoc(NameLoc);
1897
43
    PP.AnnotateCachedTokens(Tok);
1898
43
    if (SS.isNotEmpty())
1899
0
      AnnotateScopeToken(SS, !WasScopeAnnotation);
1900
43
    return ANK_Success;
1901
1902
0
  case Sema::NC_UndeclaredNonType:
1903
0
  case Sema::NC_DependentNonType:
1904
0
    Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1905
0
                    ? tok::annot_non_type_undeclared
1906
0
                    : tok::annot_non_type_dependent);
1907
0
    setIdentifierAnnotation(Tok, Name);
1908
0
    Tok.setLocation(NameLoc);
1909
0
    Tok.setAnnotationEndLoc(NameLoc);
1910
0
    PP.AnnotateCachedTokens(Tok);
1911
0
    if (SS.isNotEmpty())
1912
0
      AnnotateScopeToken(SS, !WasScopeAnnotation);
1913
0
    return ANK_Success;
1914
1915
0
  case Sema::NC_TypeTemplate:
1916
0
    if (Next.isNot(tok::less)) {
1917
      // This may be a type template being used as a template template argument.
1918
0
      if (SS.isNotEmpty())
1919
0
        AnnotateScopeToken(SS, !WasScopeAnnotation);
1920
0
      return ANK_TemplateName;
1921
0
    }
1922
0
    [[fallthrough]];
1923
0
  case Sema::NC_Concept:
1924
0
  case Sema::NC_VarTemplate:
1925
0
  case Sema::NC_FunctionTemplate:
1926
0
  case Sema::NC_UndeclaredTemplate: {
1927
0
    bool IsConceptName = Classification.getKind() == Sema::NC_Concept;
1928
    // We have a template name followed by '<'. Consume the identifier token so
1929
    // we reach the '<' and annotate it.
1930
0
    if (Next.is(tok::less))
1931
0
      ConsumeToken();
1932
0
    UnqualifiedId Id;
1933
0
    Id.setIdentifier(Name, NameLoc);
1934
0
    if (AnnotateTemplateIdToken(
1935
0
            TemplateTy::make(Classification.getTemplateName()),
1936
0
            Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1937
0
            /*AllowTypeAnnotation=*/!IsConceptName,
1938
0
            /*TypeConstraint=*/IsConceptName))
1939
0
      return ANK_Error;
1940
0
    if (SS.isNotEmpty())
1941
0
      AnnotateScopeToken(SS, !WasScopeAnnotation);
1942
0
    return ANK_Success;
1943
0
  }
1944
178
  }
1945
1946
  // Unable to classify the name, but maybe we can annotate a scope specifier.
1947
135
  if (SS.isNotEmpty())
1948
0
    AnnotateScopeToken(SS, !WasScopeAnnotation);
1949
135
  return ANK_Unresolved;
1950
178
}
1951
1952
0
bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1953
0
  assert(Tok.isNot(tok::identifier));
1954
0
  Diag(Tok, diag::ext_keyword_as_ident)
1955
0
    << PP.getSpelling(Tok)
1956
0
    << DisableKeyword;
1957
0
  if (DisableKeyword)
1958
0
    Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1959
0
  Tok.setKind(tok::identifier);
1960
0
  return true;
1961
0
}
1962
1963
/// TryAnnotateTypeOrScopeToken - If the current token position is on a
1964
/// typename (possibly qualified in C++) or a C++ scope specifier not followed
1965
/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1966
/// with a single annotation token representing the typename or C++ scope
1967
/// respectively.
1968
/// This simplifies handling of C++ scope specifiers and allows efficient
1969
/// backtracking without the need to re-parse and resolve nested-names and
1970
/// typenames.
1971
/// It will mainly be called when we expect to treat identifiers as typenames
1972
/// (if they are typenames). For example, in C we do not expect identifiers
1973
/// inside expressions to be treated as typenames so it will not be called
1974
/// for expressions in C.
1975
/// The benefit for C/ObjC is that a typename will be annotated and
1976
/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1977
/// will not be called twice, once to check whether we have a declaration
1978
/// specifier, and another one to get the actual type inside
1979
/// ParseDeclarationSpecifiers).
1980
///
1981
/// This returns true if an error occurred.
1982
///
1983
/// Note that this routine emits an error if you call it with ::new or ::delete
1984
/// as the current tokens, so only call it in contexts where these are invalid.
1985
bool Parser::TryAnnotateTypeOrScopeToken(
1986
1.89k
    ImplicitTypenameContext AllowImplicitTypename) {
1987
1.89k
  assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1988
1.89k
          Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1989
1.89k
          Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1990
1.89k
          Tok.is(tok::kw___super) || Tok.is(tok::kw_auto)) &&
1991
1.89k
         "Cannot be a type or scope token!");
1992
1993
1.89k
  if (Tok.is(tok::kw_typename)) {
1994
    // MSVC lets you do stuff like:
1995
    //   typename typedef T_::D D;
1996
    //
1997
    // We will consume the typedef token here and put it back after we have
1998
    // parsed the first identifier, transforming it into something more like:
1999
    //   typename T_::D typedef D;
2000
0
    if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
2001
0
      Token TypedefToken;
2002
0
      PP.Lex(TypedefToken);
2003
0
      bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
2004
0
      PP.EnterToken(Tok, /*IsReinject=*/true);
2005
0
      Tok = TypedefToken;
2006
0
      if (!Result)
2007
0
        Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
2008
0
      return Result;
2009
0
    }
2010
2011
    // Parse a C++ typename-specifier, e.g., "typename T::type".
2012
    //
2013
    //   typename-specifier:
2014
    //     'typename' '::' [opt] nested-name-specifier identifier
2015
    //     'typename' '::' [opt] nested-name-specifier template [opt]
2016
    //            simple-template-id
2017
0
    SourceLocation TypenameLoc = ConsumeToken();
2018
0
    CXXScopeSpec SS;
2019
0
    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2020
0
                                       /*ObjectHasErrors=*/false,
2021
0
                                       /*EnteringContext=*/false, nullptr,
2022
0
                                       /*IsTypename*/ true))
2023
0
      return true;
2024
0
    if (SS.isEmpty()) {
2025
0
      if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
2026
0
          Tok.is(tok::annot_decltype)) {
2027
        // Attempt to recover by skipping the invalid 'typename'
2028
0
        if (Tok.is(tok::annot_decltype) ||
2029
0
            (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
2030
0
             Tok.isAnnotation())) {
2031
0
          unsigned DiagID = diag::err_expected_qualified_after_typename;
2032
          // MS compatibility: MSVC permits using known types with typename.
2033
          // e.g. "typedef typename T* pointer_type"
2034
0
          if (getLangOpts().MicrosoftExt)
2035
0
            DiagID = diag::warn_expected_qualified_after_typename;
2036
0
          Diag(Tok.getLocation(), DiagID);
2037
0
          return false;
2038
0
        }
2039
0
      }
2040
0
      if (Tok.isEditorPlaceholder())
2041
0
        return true;
2042
2043
0
      Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
2044
0
      return true;
2045
0
    }
2046
2047
0
    TypeResult Ty;
2048
0
    if (Tok.is(tok::identifier)) {
2049
      // FIXME: check whether the next token is '<', first!
2050
0
      Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
2051
0
                                     *Tok.getIdentifierInfo(),
2052
0
                                     Tok.getLocation());
2053
0
    } else if (Tok.is(tok::annot_template_id)) {
2054
0
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2055
0
      if (!TemplateId->mightBeType()) {
2056
0
        Diag(Tok, diag::err_typename_refers_to_non_type_template)
2057
0
          << Tok.getAnnotationRange();
2058
0
        return true;
2059
0
      }
2060
2061
0
      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2062
0
                                         TemplateId->NumArgs);
2063
2064
0
      Ty = TemplateId->isInvalid()
2065
0
               ? TypeError()
2066
0
               : Actions.ActOnTypenameType(
2067
0
                     getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
2068
0
                     TemplateId->Template, TemplateId->Name,
2069
0
                     TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
2070
0
                     TemplateArgsPtr, TemplateId->RAngleLoc);
2071
0
    } else {
2072
0
      Diag(Tok, diag::err_expected_type_name_after_typename)
2073
0
        << SS.getRange();
2074
0
      return true;
2075
0
    }
2076
2077
0
    SourceLocation EndLoc = Tok.getLastLoc();
2078
0
    Tok.setKind(tok::annot_typename);
2079
0
    setTypeAnnotation(Tok, Ty);
2080
0
    Tok.setAnnotationEndLoc(EndLoc);
2081
0
    Tok.setLocation(TypenameLoc);
2082
0
    PP.AnnotateCachedTokens(Tok);
2083
0
    return false;
2084
0
  }
2085
2086
  // Remembers whether the token was originally a scope annotation.
2087
1.89k
  bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2088
2089
1.89k
  CXXScopeSpec SS;
2090
1.89k
  if (getLangOpts().CPlusPlus)
2091
1.03k
    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2092
1.03k
                                       /*ObjectHasErrors=*/false,
2093
1.03k
                                       /*EnteringContext*/ false))
2094
1
      return true;
2095
2096
1.89k
  return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2097
1.89k
                                                   AllowImplicitTypename);
2098
1.89k
}
2099
2100
/// Try to annotate a type or scope token, having already parsed an
2101
/// optional scope specifier. \p IsNewScope should be \c true unless the scope
2102
/// specifier was extracted from an existing tok::annot_cxxscope annotation.
2103
bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
2104
    CXXScopeSpec &SS, bool IsNewScope,
2105
1.89k
    ImplicitTypenameContext AllowImplicitTypename) {
2106
1.89k
  if (Tok.is(tok::identifier)) {
2107
    // Determine whether the identifier is a type name.
2108
1.89k
    if (ParsedType Ty = Actions.getTypeName(
2109
1.89k
            *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
2110
1.89k
            false, NextToken().is(tok::period), nullptr,
2111
1.89k
            /*IsCtorOrDtorName=*/false,
2112
1.89k
            /*NonTrivialTypeSourceInfo=*/true,
2113
1.89k
            /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
2114
0
      SourceLocation BeginLoc = Tok.getLocation();
2115
0
      if (SS.isNotEmpty()) // it was a C++ qualified type name.
2116
0
        BeginLoc = SS.getBeginLoc();
2117
2118
      /// An Objective-C object type followed by '<' is a specialization of
2119
      /// a parameterized class type or a protocol-qualified type.
2120
0
      if (getLangOpts().ObjC && NextToken().is(tok::less) &&
2121
0
          (Ty.get()->isObjCObjectType() ||
2122
0
           Ty.get()->isObjCObjectPointerType())) {
2123
        // Consume the name.
2124
0
        SourceLocation IdentifierLoc = ConsumeToken();
2125
0
        SourceLocation NewEndLoc;
2126
0
        TypeResult NewType
2127
0
          = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
2128
0
                                                   /*consumeLastToken=*/false,
2129
0
                                                   NewEndLoc);
2130
0
        if (NewType.isUsable())
2131
0
          Ty = NewType.get();
2132
0
        else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
2133
0
          return false;
2134
0
      }
2135
2136
      // This is a typename. Replace the current token in-place with an
2137
      // annotation type token.
2138
0
      Tok.setKind(tok::annot_typename);
2139
0
      setTypeAnnotation(Tok, Ty);
2140
0
      Tok.setAnnotationEndLoc(Tok.getLocation());
2141
0
      Tok.setLocation(BeginLoc);
2142
2143
      // In case the tokens were cached, have Preprocessor replace
2144
      // them with the annotation token.
2145
0
      PP.AnnotateCachedTokens(Tok);
2146
0
      return false;
2147
0
    }
2148
2149
1.89k
    if (!getLangOpts().CPlusPlus) {
2150
      // If we're in C, the only place we can have :: tokens is C23
2151
      // attribute which is parsed elsewhere. If the identifier is not a type,
2152
      // then it can't be scope either, just early exit.
2153
862
      return false;
2154
862
    }
2155
2156
    // If this is a template-id, annotate with a template-id or type token.
2157
    // FIXME: This appears to be dead code. We already have formed template-id
2158
    // tokens when parsing the scope specifier; this can never form a new one.
2159
1.03k
    if (NextToken().is(tok::less)) {
2160
51
      TemplateTy Template;
2161
51
      UnqualifiedId TemplateName;
2162
51
      TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2163
51
      bool MemberOfUnknownSpecialization;
2164
51
      if (TemplateNameKind TNK = Actions.isTemplateName(
2165
51
              getCurScope(), SS,
2166
51
              /*hasTemplateKeyword=*/false, TemplateName,
2167
51
              /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2168
51
              MemberOfUnknownSpecialization)) {
2169
        // Only annotate an undeclared template name as a template-id if the
2170
        // following tokens have the form of a template argument list.
2171
37
        if (TNK != TNK_Undeclared_template ||
2172
37
            isTemplateArgumentList(1) != TPResult::False) {
2173
          // Consume the identifier.
2174
0
          ConsumeToken();
2175
0
          if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
2176
0
                                      TemplateName)) {
2177
            // If an unrecoverable error occurred, we need to return true here,
2178
            // because the token stream is in a damaged state.  We may not
2179
            // return a valid identifier.
2180
0
            return true;
2181
0
          }
2182
0
        }
2183
37
      }
2184
51
    }
2185
2186
    // The current token, which is either an identifier or a
2187
    // template-id, is not part of the annotation. Fall through to
2188
    // push that token back into the stream and complete the C++ scope
2189
    // specifier annotation.
2190
1.03k
  }
2191
2192
1.03k
  if (Tok.is(tok::annot_template_id)) {
2193
4
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2194
4
    if (TemplateId->Kind == TNK_Type_template) {
2195
      // A template-id that refers to a type was parsed into a
2196
      // template-id annotation in a context where we weren't allowed
2197
      // to produce a type annotation token. Update the template-id
2198
      // annotation token to a type annotation token now.
2199
0
      AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2200
0
      return false;
2201
0
    }
2202
4
  }
2203
2204
1.03k
  if (SS.isEmpty())
2205
1.03k
    return false;
2206
2207
  // A C++ scope specifier that isn't followed by a typename.
2208
0
  AnnotateScopeToken(SS, IsNewScope);
2209
0
  return false;
2210
1.03k
}
2211
2212
/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2213
/// annotates C++ scope specifiers and template-ids.  This returns
2214
/// true if there was an error that could not be recovered from.
2215
///
2216
/// Note that this routine emits an error if you call it with ::new or ::delete
2217
/// as the current tokens, so only call it in contexts where these are invalid.
2218
5.42k
bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2219
5.42k
  assert(getLangOpts().CPlusPlus &&
2220
5.42k
         "Call sites of this function should be guarded by checking for C++");
2221
0
  assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2222
2223
0
  CXXScopeSpec SS;
2224
5.42k
  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2225
5.42k
                                     /*ObjectHasErrors=*/false,
2226
5.42k
                                     EnteringContext))
2227
6
    return true;
2228
5.41k
  if (SS.isEmpty())
2229
5.41k
    return false;
2230
2231
0
  AnnotateScopeToken(SS, true);
2232
0
  return false;
2233
5.41k
}
2234
2235
5.08k
bool Parser::isTokenEqualOrEqualTypo() {
2236
5.08k
  tok::TokenKind Kind = Tok.getKind();
2237
5.08k
  switch (Kind) {
2238
4.88k
  default:
2239
4.88k
    return false;
2240
0
  case tok::ampequal:            // &=
2241
0
  case tok::starequal:           // *=
2242
1
  case tok::plusequal:           // +=
2243
2
  case tok::minusequal:          // -=
2244
2
  case tok::exclaimequal:        // !=
2245
2
  case tok::slashequal:          // /=
2246
2
  case tok::percentequal:        // %=
2247
2
  case tok::lessequal:           // <=
2248
2
  case tok::lesslessequal:       // <<=
2249
4
  case tok::greaterequal:        // >=
2250
4
  case tok::greatergreaterequal: // >>=
2251
4
  case tok::caretequal:          // ^=
2252
5
  case tok::pipeequal:           // |=
2253
5
  case tok::equalequal:          // ==
2254
5
    Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2255
5
        << Kind
2256
5
        << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2257
5
    [[fallthrough]];
2258
209
  case tok::equal:
2259
209
    return true;
2260
5.08k
  }
2261
5.08k
}
2262
2263
0
SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2264
0
  assert(Tok.is(tok::code_completion));
2265
0
  PrevTokLocation = Tok.getLocation();
2266
2267
0
  for (Scope *S = getCurScope(); S; S = S->getParent()) {
2268
0
    if (S->isFunctionScope()) {
2269
0
      cutOffParsing();
2270
0
      Actions.CodeCompleteOrdinaryName(getCurScope(),
2271
0
                                       Sema::PCC_RecoveryInFunction);
2272
0
      return PrevTokLocation;
2273
0
    }
2274
2275
0
    if (S->isClassScope()) {
2276
0
      cutOffParsing();
2277
0
      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
2278
0
      return PrevTokLocation;
2279
0
    }
2280
0
  }
2281
2282
0
  cutOffParsing();
2283
0
  Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
2284
0
  return PrevTokLocation;
2285
0
}
2286
2287
// Code-completion pass-through functions
2288
2289
0
void Parser::CodeCompleteDirective(bool InConditional) {
2290
0
  Actions.CodeCompletePreprocessorDirective(InConditional);
2291
0
}
2292
2293
0
void Parser::CodeCompleteInConditionalExclusion() {
2294
0
  Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
2295
0
}
2296
2297
0
void Parser::CodeCompleteMacroName(bool IsDefinition) {
2298
0
  Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2299
0
}
2300
2301
0
void Parser::CodeCompletePreprocessorExpression() {
2302
0
  Actions.CodeCompletePreprocessorExpression();
2303
0
}
2304
2305
void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2306
                                       MacroInfo *MacroInfo,
2307
0
                                       unsigned ArgumentIndex) {
2308
0
  Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
2309
0
                                                ArgumentIndex);
2310
0
}
2311
2312
0
void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2313
0
  Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2314
0
}
2315
2316
0
void Parser::CodeCompleteNaturalLanguage() {
2317
0
  Actions.CodeCompleteNaturalLanguage();
2318
0
}
2319
2320
0
bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2321
0
  assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2322
0
         "Expected '__if_exists' or '__if_not_exists'");
2323
0
  Result.IsIfExists = Tok.is(tok::kw___if_exists);
2324
0
  Result.KeywordLoc = ConsumeToken();
2325
2326
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
2327
0
  if (T.consumeOpen()) {
2328
0
    Diag(Tok, diag::err_expected_lparen_after)
2329
0
      << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2330
0
    return true;
2331
0
  }
2332
2333
  // Parse nested-name-specifier.
2334
0
  if (getLangOpts().CPlusPlus)
2335
0
    ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2336
0
                                   /*ObjectHasErrors=*/false,
2337
0
                                   /*EnteringContext=*/false);
2338
2339
  // Check nested-name specifier.
2340
0
  if (Result.SS.isInvalid()) {
2341
0
    T.skipToEnd();
2342
0
    return true;
2343
0
  }
2344
2345
  // Parse the unqualified-id.
2346
0
  SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2347
0
  if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2348
0
                         /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2349
0
                         /*AllowDestructorName*/ true,
2350
0
                         /*AllowConstructorName*/ true,
2351
0
                         /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2352
0
                         Result.Name)) {
2353
0
    T.skipToEnd();
2354
0
    return true;
2355
0
  }
2356
2357
0
  if (T.consumeClose())
2358
0
    return true;
2359
2360
  // Check if the symbol exists.
2361
0
  switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2362
0
                                               Result.IsIfExists, Result.SS,
2363
0
                                               Result.Name)) {
2364
0
  case Sema::IER_Exists:
2365
0
    Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2366
0
    break;
2367
2368
0
  case Sema::IER_DoesNotExist:
2369
0
    Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2370
0
    break;
2371
2372
0
  case Sema::IER_Dependent:
2373
0
    Result.Behavior = IEB_Dependent;
2374
0
    break;
2375
2376
0
  case Sema::IER_Error:
2377
0
    return true;
2378
0
  }
2379
2380
0
  return false;
2381
0
}
2382
2383
0
void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2384
0
  IfExistsCondition Result;
2385
0
  if (ParseMicrosoftIfExistsCondition(Result))
2386
0
    return;
2387
2388
0
  BalancedDelimiterTracker Braces(*this, tok::l_brace);
2389
0
  if (Braces.consumeOpen()) {
2390
0
    Diag(Tok, diag::err_expected) << tok::l_brace;
2391
0
    return;
2392
0
  }
2393
2394
0
  switch (Result.Behavior) {
2395
0
  case IEB_Parse:
2396
    // Parse declarations below.
2397
0
    break;
2398
2399
0
  case IEB_Dependent:
2400
0
    llvm_unreachable("Cannot have a dependent external declaration");
2401
2402
0
  case IEB_Skip:
2403
0
    Braces.skipToEnd();
2404
0
    return;
2405
0
  }
2406
2407
  // Parse the declarations.
2408
  // FIXME: Support module import within __if_exists?
2409
0
  while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2410
0
    ParsedAttributes Attrs(AttrFactory);
2411
0
    MaybeParseCXX11Attributes(Attrs);
2412
0
    ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2413
0
    DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);
2414
0
    if (Result && !getCurScope()->getParent())
2415
0
      Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2416
0
  }
2417
0
  Braces.consumeClose();
2418
0
}
2419
2420
/// Parse a declaration beginning with the 'module' keyword or C++20
2421
/// context-sensitive keyword (optionally preceded by 'export').
2422
///
2423
///   module-declaration:   [C++20]
2424
///     'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2425
///
2426
///   global-module-fragment:  [C++2a]
2427
///     'module' ';' top-level-declaration-seq[opt]
2428
///   module-declaration:      [C++2a]
2429
///     'export'[opt] 'module' module-name module-partition[opt]
2430
///            attribute-specifier-seq[opt] ';'
2431
///   private-module-fragment: [C++2a]
2432
///     'module' ':' 'private' ';' top-level-declaration-seq[opt]
2433
Parser::DeclGroupPtrTy
2434
0
Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2435
0
  SourceLocation StartLoc = Tok.getLocation();
2436
2437
0
  Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2438
0
                                 ? Sema::ModuleDeclKind::Interface
2439
0
                                 : Sema::ModuleDeclKind::Implementation;
2440
2441
0
  assert(
2442
0
      (Tok.is(tok::kw_module) ||
2443
0
       (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2444
0
      "not a module declaration");
2445
0
  SourceLocation ModuleLoc = ConsumeToken();
2446
2447
  // Attributes appear after the module name, not before.
2448
  // FIXME: Suggest moving the attributes later with a fixit.
2449
0
  DiagnoseAndSkipCXX11Attributes();
2450
2451
  // Parse a global-module-fragment, if present.
2452
0
  if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2453
0
    SourceLocation SemiLoc = ConsumeToken();
2454
0
    if (ImportState != Sema::ModuleImportState::FirstDecl) {
2455
0
      Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2456
0
        << SourceRange(StartLoc, SemiLoc);
2457
0
      return nullptr;
2458
0
    }
2459
0
    if (MDK == Sema::ModuleDeclKind::Interface) {
2460
0
      Diag(StartLoc, diag::err_module_fragment_exported)
2461
0
        << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2462
0
    }
2463
0
    ImportState = Sema::ModuleImportState::GlobalFragment;
2464
0
    return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2465
0
  }
2466
2467
  // Parse a private-module-fragment, if present.
2468
0
  if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2469
0
      NextToken().is(tok::kw_private)) {
2470
0
    if (MDK == Sema::ModuleDeclKind::Interface) {
2471
0
      Diag(StartLoc, diag::err_module_fragment_exported)
2472
0
        << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2473
0
    }
2474
0
    ConsumeToken();
2475
0
    SourceLocation PrivateLoc = ConsumeToken();
2476
0
    DiagnoseAndSkipCXX11Attributes();
2477
0
    ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2478
0
    ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2479
0
                      ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2480
0
                      : Sema::ModuleImportState::PrivateFragmentImportFinished;
2481
0
    return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2482
0
  }
2483
2484
0
  SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2485
0
  if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
2486
0
    return nullptr;
2487
2488
  // Parse the optional module-partition.
2489
0
  SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
2490
0
  if (Tok.is(tok::colon)) {
2491
0
    SourceLocation ColonLoc = ConsumeToken();
2492
0
    if (!getLangOpts().CPlusPlusModules)
2493
0
      Diag(ColonLoc, diag::err_unsupported_module_partition)
2494
0
          << SourceRange(ColonLoc, Partition.back().second);
2495
    // Recover by ignoring the partition name.
2496
0
    else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))
2497
0
      return nullptr;
2498
0
  }
2499
2500
  // We don't support any module attributes yet; just parse them and diagnose.
2501
0
  ParsedAttributes Attrs(AttrFactory);
2502
0
  MaybeParseCXX11Attributes(Attrs);
2503
0
  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2504
0
                          diag::err_keyword_not_module_attr,
2505
0
                          /*DiagnoseEmptyAttrs=*/false,
2506
0
                          /*WarnOnUnknownAttrs=*/true);
2507
2508
0
  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2509
2510
0
  return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2511
0
                                 ImportState);
2512
0
}
2513
2514
/// Parse a module import declaration. This is essentially the same for
2515
/// Objective-C and C++20 except for the leading '@' (in ObjC) and the
2516
/// trailing optional attributes (in C++).
2517
///
2518
/// [ObjC]  @import declaration:
2519
///           '@' 'import' module-name ';'
2520
/// [ModTS] module-import-declaration:
2521
///           'import' module-name attribute-specifier-seq[opt] ';'
2522
/// [C++20] module-import-declaration:
2523
///           'export'[opt] 'import' module-name
2524
///                   attribute-specifier-seq[opt] ';'
2525
///           'export'[opt] 'import' module-partition
2526
///                   attribute-specifier-seq[opt] ';'
2527
///           'export'[opt] 'import' header-name
2528
///                   attribute-specifier-seq[opt] ';'
2529
Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2530
0
                                Sema::ModuleImportState &ImportState) {
2531
0
  SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2532
2533
0
  SourceLocation ExportLoc;
2534
0
  TryConsumeToken(tok::kw_export, ExportLoc);
2535
2536
0
  assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2537
0
                            : Tok.isObjCAtKeyword(tok::objc_import)) &&
2538
0
         "Improper start to module import");
2539
0
  bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2540
0
  SourceLocation ImportLoc = ConsumeToken();
2541
2542
  // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2543
0
  SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2544
0
  bool IsPartition = false;
2545
0
  Module *HeaderUnit = nullptr;
2546
0
  if (Tok.is(tok::header_name)) {
2547
    // This is a header import that the preprocessor decided we should skip
2548
    // because it was malformed in some way. Parse and ignore it; it's already
2549
    // been diagnosed.
2550
0
    ConsumeToken();
2551
0
  } else if (Tok.is(tok::annot_header_unit)) {
2552
    // This is a header import that the preprocessor mapped to a module import.
2553
0
    HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2554
0
    ConsumeAnnotationToken();
2555
0
  } else if (Tok.is(tok::colon)) {
2556
0
    SourceLocation ColonLoc = ConsumeToken();
2557
0
    if (!getLangOpts().CPlusPlusModules)
2558
0
      Diag(ColonLoc, diag::err_unsupported_module_partition)
2559
0
          << SourceRange(ColonLoc, Path.back().second);
2560
    // Recover by leaving partition empty.
2561
0
    else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
2562
0
      return nullptr;
2563
0
    else
2564
0
      IsPartition = true;
2565
0
  } else {
2566
0
    if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
2567
0
      return nullptr;
2568
0
  }
2569
2570
0
  ParsedAttributes Attrs(AttrFactory);
2571
0
  MaybeParseCXX11Attributes(Attrs);
2572
  // We don't support any module import attributes yet.
2573
0
  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2574
0
                          diag::err_keyword_not_import_attr,
2575
0
                          /*DiagnoseEmptyAttrs=*/false,
2576
0
                          /*WarnOnUnknownAttrs=*/true);
2577
2578
0
  if (PP.hadModuleLoaderFatalFailure()) {
2579
    // With a fatal failure in the module loader, we abort parsing.
2580
0
    cutOffParsing();
2581
0
    return nullptr;
2582
0
  }
2583
2584
  // Diagnose mis-imports.
2585
0
  bool SeenError = true;
2586
0
  switch (ImportState) {
2587
0
  case Sema::ModuleImportState::ImportAllowed:
2588
0
    SeenError = false;
2589
0
    break;
2590
0
  case Sema::ModuleImportState::FirstDecl:
2591
    // If we found an import decl as the first declaration, we must be not in
2592
    // a C++20 module unit or we are in an invalid state.
2593
0
    ImportState = Sema::ModuleImportState::NotACXX20Module;
2594
0
    [[fallthrough]];
2595
0
  case Sema::ModuleImportState::NotACXX20Module:
2596
    // We can only import a partition within a module purview.
2597
0
    if (IsPartition)
2598
0
      Diag(ImportLoc, diag::err_partition_import_outside_module);
2599
0
    else
2600
0
      SeenError = false;
2601
0
    break;
2602
0
  case Sema::ModuleImportState::GlobalFragment:
2603
0
  case Sema::ModuleImportState::PrivateFragmentImportAllowed:
2604
    // We can only have pre-processor directives in the global module fragment
2605
    // which allows pp-import, but not of a partition (since the global module
2606
    // does not have partitions).
2607
    // We cannot import a partition into a private module fragment, since
2608
    // [module.private.frag]/1 disallows private module fragments in a multi-
2609
    // TU module.
2610
0
    if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=
2611
0
                                          Module::ModuleKind::ModuleHeaderUnit))
2612
0
      Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2613
0
          << IsPartition
2614
0
          << (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);
2615
0
    else
2616
0
      SeenError = false;
2617
0
    break;
2618
0
  case Sema::ModuleImportState::ImportFinished:
2619
0
  case Sema::ModuleImportState::PrivateFragmentImportFinished:
2620
0
    if (getLangOpts().CPlusPlusModules)
2621
0
      Diag(ImportLoc, diag::err_import_not_allowed_here);
2622
0
    else
2623
0
      SeenError = false;
2624
0
    break;
2625
0
  }
2626
0
  if (SeenError) {
2627
0
    ExpectAndConsumeSemi(diag::err_module_expected_semi);
2628
0
    return nullptr;
2629
0
  }
2630
2631
0
  DeclResult Import;
2632
0
  if (HeaderUnit)
2633
0
    Import =
2634
0
        Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2635
0
  else if (!Path.empty())
2636
0
    Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2637
0
                                       IsPartition);
2638
0
  ExpectAndConsumeSemi(diag::err_module_expected_semi);
2639
0
  if (Import.isInvalid())
2640
0
    return nullptr;
2641
2642
  // Using '@import' in framework headers requires modules to be enabled so that
2643
  // the header is parseable. Emit a warning to make the user aware.
2644
0
  if (IsObjCAtImport && AtLoc.isValid()) {
2645
0
    auto &SrcMgr = PP.getSourceManager();
2646
0
    auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2647
0
    if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2648
0
                  .ends_with(".framework"))
2649
0
      Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2650
0
  }
2651
2652
0
  return Import.get();
2653
0
}
2654
2655
/// Parse a C++ / Objective-C module name (both forms use the same
2656
/// grammar).
2657
///
2658
///         module-name:
2659
///           module-name-qualifier[opt] identifier
2660
///         module-name-qualifier:
2661
///           module-name-qualifier[opt] identifier '.'
2662
bool Parser::ParseModuleName(
2663
    SourceLocation UseLoc,
2664
    SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2665
0
    bool IsImport) {
2666
  // Parse the module path.
2667
0
  while (true) {
2668
0
    if (!Tok.is(tok::identifier)) {
2669
0
      if (Tok.is(tok::code_completion)) {
2670
0
        cutOffParsing();
2671
0
        Actions.CodeCompleteModuleImport(UseLoc, Path);
2672
0
        return true;
2673
0
      }
2674
2675
0
      Diag(Tok, diag::err_module_expected_ident) << IsImport;
2676
0
      SkipUntil(tok::semi);
2677
0
      return true;
2678
0
    }
2679
2680
    // Record this part of the module path.
2681
0
    Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2682
0
    ConsumeToken();
2683
2684
0
    if (Tok.isNot(tok::period))
2685
0
      return false;
2686
2687
0
    ConsumeToken();
2688
0
  }
2689
0
}
2690
2691
/// Try recover parser when module annotation appears where it must not
2692
/// be found.
2693
/// \returns false if the recover was successful and parsing may be continued, or
2694
/// true if parser must bail out to top level and handle the token there.
2695
0
bool Parser::parseMisplacedModuleImport() {
2696
0
  while (true) {
2697
0
    switch (Tok.getKind()) {
2698
0
    case tok::annot_module_end:
2699
      // If we recovered from a misplaced module begin, we expect to hit a
2700
      // misplaced module end too. Stay in the current context when this
2701
      // happens.
2702
0
      if (MisplacedModuleBeginCount) {
2703
0
        --MisplacedModuleBeginCount;
2704
0
        Actions.ActOnModuleEnd(Tok.getLocation(),
2705
0
                               reinterpret_cast<Module *>(
2706
0
                                   Tok.getAnnotationValue()));
2707
0
        ConsumeAnnotationToken();
2708
0
        continue;
2709
0
      }
2710
      // Inform caller that recovery failed, the error must be handled at upper
2711
      // level. This will generate the desired "missing '}' at end of module"
2712
      // diagnostics on the way out.
2713
0
      return true;
2714
0
    case tok::annot_module_begin:
2715
      // Recover by entering the module (Sema will diagnose).
2716
0
      Actions.ActOnModuleBegin(Tok.getLocation(),
2717
0
                               reinterpret_cast<Module *>(
2718
0
                                   Tok.getAnnotationValue()));
2719
0
      ConsumeAnnotationToken();
2720
0
      ++MisplacedModuleBeginCount;
2721
0
      continue;
2722
0
    case tok::annot_module_include:
2723
      // Module import found where it should not be, for instance, inside a
2724
      // namespace. Recover by importing the module.
2725
0
      Actions.ActOnModuleInclude(Tok.getLocation(),
2726
0
                                 reinterpret_cast<Module *>(
2727
0
                                     Tok.getAnnotationValue()));
2728
0
      ConsumeAnnotationToken();
2729
      // If there is another module import, process it.
2730
0
      continue;
2731
0
    default:
2732
0
      return false;
2733
0
    }
2734
0
  }
2735
0
  return false;
2736
0
}
2737
2738
0
bool BalancedDelimiterTracker::diagnoseOverflow() {
2739
0
  P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2740
0
    << P.getLangOpts().BracketDepth;
2741
0
  P.Diag(P.Tok, diag::note_bracket_depth);
2742
0
  P.cutOffParsing();
2743
0
  return true;
2744
0
}
2745
2746
bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2747
                                                const char *Msg,
2748
0
                                                tok::TokenKind SkipToTok) {
2749
0
  LOpen = P.Tok.getLocation();
2750
0
  if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2751
0
    if (SkipToTok != tok::unknown)
2752
0
      P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2753
0
    return true;
2754
0
  }
2755
2756
0
  if (getDepth() < P.getLangOpts().BracketDepth)
2757
0
    return false;
2758
2759
0
  return diagnoseOverflow();
2760
0
}
2761
2762
383
bool BalancedDelimiterTracker::diagnoseMissingClose() {
2763
383
  assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2764
2765
383
  if (P.Tok.is(tok::annot_module_end))
2766
0
    P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2767
383
  else
2768
383
    P.Diag(P.Tok, diag::err_expected) << Close;
2769
383
  P.Diag(LOpen, diag::note_matching) << Kind;
2770
2771
  // If we're not already at some kind of closing bracket, skip to our closing
2772
  // token.
2773
383
  if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2774
383
      P.Tok.isNot(tok::r_square) &&
2775
383
      P.SkipUntil(Close, FinalToken,
2776
328
                  Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2777
383
      P.Tok.is(Close))
2778
154
    LClose = P.ConsumeAnyToken();
2779
383
  return true;
2780
383
}
2781
2782
0
void BalancedDelimiterTracker::skipToEnd() {
2783
0
  P.SkipUntil(Close, Parser::StopBeforeMatch);
2784
0
  consumeClose();
2785
0
}