Coverage Report

Created: 2022-01-18 06:27

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