Coverage Report

Created: 2021-01-19 06:58

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