Coverage Report

Created: 2021-08-24 07:12

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