Coverage Report

Created: 2022-07-16 07:03

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