Coverage Report

Created: 2019-07-24 05:18

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