Coverage Report

Created: 2020-02-25 14:32

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