Coverage Report

Created: 2020-09-19 12:23

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