Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Parse/ParseObjc.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
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 Objective-C portions of the Parser interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/ODRDiagsEmitter.h"
15
#include "clang/AST/PrettyDeclStackTrace.h"
16
#include "clang/Basic/CharInfo.h"
17
#include "clang/Basic/TargetInfo.h"
18
#include "clang/Parse/ParseDiagnostic.h"
19
#include "clang/Parse/Parser.h"
20
#include "clang/Parse/RAIIObjectsForParser.h"
21
#include "clang/Sema/DeclSpec.h"
22
#include "clang/Sema/Scope.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringExtras.h"
25
26
using namespace clang;
27
28
/// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
29
0
void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
30
0
  ParsedAttributes attrs(AttrFactory);
31
0
  if (Tok.is(tok::kw___attribute)) {
32
0
    if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
33
0
      Diag(Tok, diag::err_objc_postfix_attribute_hint)
34
0
          << (Kind == tok::objc_protocol);
35
0
    else
36
0
      Diag(Tok, diag::err_objc_postfix_attribute);
37
0
    ParseGNUAttributes(attrs);
38
0
  }
39
0
}
40
41
/// ParseObjCAtDirectives - Handle parts of the external-declaration production:
42
///       external-declaration: [C99 6.9]
43
/// [OBJC]  objc-class-definition
44
/// [OBJC]  objc-class-declaration
45
/// [OBJC]  objc-alias-declaration
46
/// [OBJC]  objc-protocol-definition
47
/// [OBJC]  objc-method-definition
48
/// [OBJC]  '@' 'end'
49
Parser::DeclGroupPtrTy
50
Parser::ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
51
55
                              ParsedAttributes &DeclSpecAttrs) {
52
55
  DeclAttrs.takeAllFrom(DeclSpecAttrs);
53
54
55
  SourceLocation AtLoc = ConsumeToken(); // the "@"
55
56
55
  if (Tok.is(tok::code_completion)) {
57
0
    cutOffParsing();
58
0
    Actions.CodeCompleteObjCAtDirective(getCurScope());
59
0
    return nullptr;
60
0
  }
61
62
55
  switch (Tok.getObjCKeywordID()) {
63
0
  case tok::objc_interface:
64
0
  case tok::objc_protocol:
65
0
  case tok::objc_implementation:
66
0
    break;
67
55
  default:
68
55
    for (const auto &Attr : DeclAttrs) {
69
0
      if (Attr.isGNUAttribute())
70
0
        Diag(Tok.getLocation(), diag::err_objc_unexpected_attr);
71
0
    }
72
55
  }
73
74
55
  Decl *SingleDecl = nullptr;
75
55
  switch (Tok.getObjCKeywordID()) {
76
0
  case tok::objc_class:
77
0
    return ParseObjCAtClassDeclaration(AtLoc);
78
0
  case tok::objc_interface:
79
0
    SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DeclAttrs);
80
0
    break;
81
0
  case tok::objc_protocol:
82
0
    return ParseObjCAtProtocolDeclaration(AtLoc, DeclAttrs);
83
0
  case tok::objc_implementation:
84
0
    return ParseObjCAtImplementationDeclaration(AtLoc, DeclAttrs);
85
0
  case tok::objc_end:
86
0
    return ParseObjCAtEndDeclaration(AtLoc);
87
0
  case tok::objc_compatibility_alias:
88
0
    SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
89
0
    break;
90
0
  case tok::objc_synthesize:
91
0
    SingleDecl = ParseObjCPropertySynthesize(AtLoc);
92
0
    break;
93
0
  case tok::objc_dynamic:
94
0
    SingleDecl = ParseObjCPropertyDynamic(AtLoc);
95
0
    break;
96
0
  case tok::objc_import:
97
0
    if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
98
0
      Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
99
0
      SingleDecl = ParseModuleImport(AtLoc, IS);
100
0
      break;
101
0
    }
102
0
    Diag(AtLoc, diag::err_atimport);
103
0
    SkipUntil(tok::semi);
104
0
    return Actions.ConvertDeclToDeclGroup(nullptr);
105
55
  default:
106
55
    Diag(AtLoc, diag::err_unexpected_at);
107
55
    SkipUntil(tok::semi);
108
55
    SingleDecl = nullptr;
109
55
    break;
110
55
  }
111
55
  return Actions.ConvertDeclToDeclGroup(SingleDecl);
112
55
}
113
114
/// Class to handle popping type parameters when leaving the scope.
115
class Parser::ObjCTypeParamListScope {
116
  Sema &Actions;
117
  Scope *S;
118
  ObjCTypeParamList *Params;
119
120
public:
121
  ObjCTypeParamListScope(Sema &Actions, Scope *S)
122
0
      : Actions(Actions), S(S), Params(nullptr) {}
123
124
0
  ~ObjCTypeParamListScope() {
125
0
    leave();
126
0
  }
127
128
0
  void enter(ObjCTypeParamList *P) {
129
0
    assert(!Params);
130
0
    Params = P;
131
0
  }
132
133
0
  void leave() {
134
0
    if (Params)
135
0
      Actions.popObjCTypeParamList(S, Params);
136
0
    Params = nullptr;
137
0
  }
138
};
139
140
///
141
/// objc-class-declaration:
142
///    '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
143
///
144
/// objc-class-forward-decl:
145
///   identifier objc-type-parameter-list[opt]
146
///
147
Parser::DeclGroupPtrTy
148
0
Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
149
0
  ConsumeToken(); // the identifier "class"
150
0
  SmallVector<IdentifierInfo *, 8> ClassNames;
151
0
  SmallVector<SourceLocation, 8> ClassLocs;
152
0
  SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
153
154
0
  while (true) {
155
0
    MaybeSkipAttributes(tok::objc_class);
156
0
    if (Tok.is(tok::code_completion)) {
157
0
      cutOffParsing();
158
0
      Actions.CodeCompleteObjCClassForwardDecl(getCurScope());
159
0
      return Actions.ConvertDeclToDeclGroup(nullptr);
160
0
    }
161
0
    if (expectIdentifier()) {
162
0
      SkipUntil(tok::semi);
163
0
      return Actions.ConvertDeclToDeclGroup(nullptr);
164
0
    }
165
0
    ClassNames.push_back(Tok.getIdentifierInfo());
166
0
    ClassLocs.push_back(Tok.getLocation());
167
0
    ConsumeToken();
168
169
    // Parse the optional objc-type-parameter-list.
170
0
    ObjCTypeParamList *TypeParams = nullptr;
171
0
    if (Tok.is(tok::less))
172
0
      TypeParams = parseObjCTypeParamList();
173
0
    ClassTypeParams.push_back(TypeParams);
174
0
    if (!TryConsumeToken(tok::comma))
175
0
      break;
176
0
  }
177
178
  // Consume the ';'.
179
0
  if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
180
0
    return Actions.ConvertDeclToDeclGroup(nullptr);
181
182
0
  return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
183
0
                                              ClassLocs.data(),
184
0
                                              ClassTypeParams,
185
0
                                              ClassNames.size());
186
0
}
187
188
void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
189
0
{
190
0
  Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
191
0
  if (ock == Sema::OCK_None)
192
0
    return;
193
194
0
  Decl *Decl = Actions.getObjCDeclContext();
195
0
  if (CurParsedObjCImpl) {
196
0
    CurParsedObjCImpl->finish(AtLoc);
197
0
  } else {
198
0
    Actions.ActOnAtEnd(getCurScope(), AtLoc);
199
0
  }
200
0
  Diag(AtLoc, diag::err_objc_missing_end)
201
0
      << FixItHint::CreateInsertion(AtLoc, "@end\n");
202
0
  if (Decl)
203
0
    Diag(Decl->getBeginLoc(), diag::note_objc_container_start) << (int)ock;
204
0
}
205
206
///
207
///   objc-interface:
208
///     objc-class-interface-attributes[opt] objc-class-interface
209
///     objc-category-interface
210
///
211
///   objc-class-interface:
212
///     '@' 'interface' identifier objc-type-parameter-list[opt]
213
///       objc-superclass[opt] objc-protocol-refs[opt]
214
///       objc-class-instance-variables[opt]
215
///       objc-interface-decl-list
216
///     @end
217
///
218
///   objc-category-interface:
219
///     '@' 'interface' identifier objc-type-parameter-list[opt]
220
///       '(' identifier[opt] ')' objc-protocol-refs[opt]
221
///       objc-interface-decl-list
222
///     @end
223
///
224
///   objc-superclass:
225
///     ':' identifier objc-type-arguments[opt]
226
///
227
///   objc-class-interface-attributes:
228
///     __attribute__((visibility("default")))
229
///     __attribute__((visibility("hidden")))
230
///     __attribute__((deprecated))
231
///     __attribute__((unavailable))
232
///     __attribute__((objc_exception)) - used by NSException on 64-bit
233
///     __attribute__((objc_root_class))
234
///
235
Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
236
0
                                              ParsedAttributes &attrs) {
237
0
  assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
238
0
         "ParseObjCAtInterfaceDeclaration(): Expected @interface");
239
0
  CheckNestedObjCContexts(AtLoc);
240
0
  ConsumeToken(); // the "interface" identifier
241
242
  // Code completion after '@interface'.
243
0
  if (Tok.is(tok::code_completion)) {
244
0
    cutOffParsing();
245
0
    Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
246
0
    return nullptr;
247
0
  }
248
249
0
  MaybeSkipAttributes(tok::objc_interface);
250
251
0
  if (expectIdentifier())
252
0
    return nullptr; // missing class or category name.
253
254
  // We have a class or category name - consume it.
255
0
  IdentifierInfo *nameId = Tok.getIdentifierInfo();
256
0
  SourceLocation nameLoc = ConsumeToken();
257
258
  // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
259
  // case, LAngleLoc will be valid and ProtocolIdents will capture the
260
  // protocol references (that have not yet been resolved).
261
0
  SourceLocation LAngleLoc, EndProtoLoc;
262
0
  SmallVector<IdentifierLocPair, 8> ProtocolIdents;
263
0
  ObjCTypeParamList *typeParameterList = nullptr;
264
0
  ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
265
0
  if (Tok.is(tok::less))
266
0
    typeParameterList = parseObjCTypeParamListOrProtocolRefs(
267
0
        typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
268
269
0
  if (Tok.is(tok::l_paren) &&
270
0
      !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
271
272
0
    BalancedDelimiterTracker T(*this, tok::l_paren);
273
0
    T.consumeOpen();
274
275
0
    SourceLocation categoryLoc;
276
0
    IdentifierInfo *categoryId = nullptr;
277
0
    if (Tok.is(tok::code_completion)) {
278
0
      cutOffParsing();
279
0
      Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
280
0
      return nullptr;
281
0
    }
282
283
    // For ObjC2, the category name is optional (not an error).
284
0
    if (Tok.is(tok::identifier)) {
285
0
      categoryId = Tok.getIdentifierInfo();
286
0
      categoryLoc = ConsumeToken();
287
0
    }
288
0
    else if (!getLangOpts().ObjC) {
289
0
      Diag(Tok, diag::err_expected)
290
0
          << tok::identifier; // missing category name.
291
0
      return nullptr;
292
0
    }
293
294
0
    T.consumeClose();
295
0
    if (T.getCloseLocation().isInvalid())
296
0
      return nullptr;
297
298
    // Next, we need to check for any protocol references.
299
0
    assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
300
0
    SmallVector<Decl *, 8> ProtocolRefs;
301
0
    SmallVector<SourceLocation, 8> ProtocolLocs;
302
0
    if (Tok.is(tok::less) &&
303
0
        ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
304
0
                                    LAngleLoc, EndProtoLoc,
305
0
                                    /*consumeLastToken=*/true))
306
0
      return nullptr;
307
308
0
    ObjCCategoryDecl *CategoryType = Actions.ActOnStartCategoryInterface(
309
0
        AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
310
0
        ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
311
0
        EndProtoLoc, attrs);
312
313
0
    if (Tok.is(tok::l_brace))
314
0
      ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
315
316
0
    ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
317
318
0
    return CategoryType;
319
0
  }
320
  // Parse a class interface.
321
0
  IdentifierInfo *superClassId = nullptr;
322
0
  SourceLocation superClassLoc;
323
0
  SourceLocation typeArgsLAngleLoc;
324
0
  SmallVector<ParsedType, 4> typeArgs;
325
0
  SourceLocation typeArgsRAngleLoc;
326
0
  SmallVector<Decl *, 4> protocols;
327
0
  SmallVector<SourceLocation, 4> protocolLocs;
328
0
  if (Tok.is(tok::colon)) { // a super class is specified.
329
0
    ConsumeToken();
330
331
    // Code completion of superclass names.
332
0
    if (Tok.is(tok::code_completion)) {
333
0
      cutOffParsing();
334
0
      Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
335
0
      return nullptr;
336
0
    }
337
338
0
    if (expectIdentifier())
339
0
      return nullptr; // missing super class name.
340
0
    superClassId = Tok.getIdentifierInfo();
341
0
    superClassLoc = ConsumeToken();
342
343
    // Type arguments for the superclass or protocol conformances.
344
0
    if (Tok.is(tok::less)) {
345
0
      parseObjCTypeArgsOrProtocolQualifiers(
346
0
          nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
347
0
          protocols, protocolLocs, EndProtoLoc,
348
0
          /*consumeLastToken=*/true,
349
0
          /*warnOnIncompleteProtocols=*/true);
350
0
      if (Tok.is(tok::eof))
351
0
        return nullptr;
352
0
    }
353
0
  }
354
355
  // Next, we need to check for any protocol references.
356
0
  if (LAngleLoc.isValid()) {
357
0
    if (!ProtocolIdents.empty()) {
358
      // We already parsed the protocols named when we thought we had a
359
      // type parameter list. Translate them into actual protocol references.
360
0
      for (const auto &pair : ProtocolIdents) {
361
0
        protocolLocs.push_back(pair.second);
362
0
      }
363
0
      Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
364
0
                                      /*ForObjCContainer=*/true,
365
0
                                      ProtocolIdents, protocols);
366
0
    }
367
0
  } else if (protocols.empty() && Tok.is(tok::less) &&
368
0
             ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
369
0
                                         LAngleLoc, EndProtoLoc,
370
0
                                         /*consumeLastToken=*/true)) {
371
0
    return nullptr;
372
0
  }
373
374
0
  if (Tok.isNot(tok::less))
375
0
    Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
376
0
                                    superClassId, superClassLoc);
377
378
0
  Sema::SkipBodyInfo SkipBody;
379
0
  ObjCInterfaceDecl *ClsType = Actions.ActOnStartClassInterface(
380
0
      getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId,
381
0
      superClassLoc, typeArgs,
382
0
      SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(),
383
0
      protocols.size(), protocolLocs.data(), EndProtoLoc, attrs, &SkipBody);
384
385
0
  if (Tok.is(tok::l_brace))
386
0
    ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
387
388
0
  ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
389
390
0
  if (SkipBody.CheckSameAsPrevious) {
391
0
    auto *PreviousDef = cast<ObjCInterfaceDecl>(SkipBody.Previous);
392
0
    if (Actions.ActOnDuplicateODRHashDefinition(ClsType, PreviousDef)) {
393
0
      ClsType->mergeDuplicateDefinitionWithCommon(PreviousDef->getDefinition());
394
0
    } else {
395
0
      ODRDiagsEmitter DiagsEmitter(Diags, Actions.getASTContext(),
396
0
                                   getPreprocessor().getLangOpts());
397
0
      DiagsEmitter.diagnoseMismatch(PreviousDef, ClsType);
398
0
      ClsType->setInvalidDecl();
399
0
    }
400
0
  }
401
402
0
  return ClsType;
403
0
}
404
405
/// Add an attribute for a context-sensitive type nullability to the given
406
/// declarator.
407
static void addContextSensitiveTypeNullability(Parser &P,
408
                                               Declarator &D,
409
                                               NullabilityKind nullability,
410
                                               SourceLocation nullabilityLoc,
411
0
                                               bool &addedToDeclSpec) {
412
  // Create the attribute.
413
0
  auto getNullabilityAttr = [&](AttributePool &Pool) -> ParsedAttr * {
414
0
    return Pool.create(P.getNullabilityKeyword(nullability),
415
0
                       SourceRange(nullabilityLoc), nullptr, SourceLocation(),
416
0
                       nullptr, 0, ParsedAttr::Form::ContextSensitiveKeyword());
417
0
  };
418
419
0
  if (D.getNumTypeObjects() > 0) {
420
    // Add the attribute to the declarator chunk nearest the declarator.
421
0
    D.getTypeObject(0).getAttrs().addAtEnd(
422
0
        getNullabilityAttr(D.getAttributePool()));
423
0
  } else if (!addedToDeclSpec) {
424
    // Otherwise, just put it on the declaration specifiers (if one
425
    // isn't there already).
426
0
    D.getMutableDeclSpec().getAttributes().addAtEnd(
427
0
        getNullabilityAttr(D.getMutableDeclSpec().getAttributes().getPool()));
428
0
    addedToDeclSpec = true;
429
0
  }
430
0
}
431
432
/// Parse an Objective-C type parameter list, if present, or capture
433
/// the locations of the protocol identifiers for a list of protocol
434
/// references.
435
///
436
///   objc-type-parameter-list:
437
///     '<' objc-type-parameter (',' objc-type-parameter)* '>'
438
///
439
///   objc-type-parameter:
440
///     objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
441
///
442
///   objc-type-parameter-bound:
443
///     ':' type-name
444
///
445
///   objc-type-parameter-variance:
446
///     '__covariant'
447
///     '__contravariant'
448
///
449
/// \param lAngleLoc The location of the starting '<'.
450
///
451
/// \param protocolIdents Will capture the list of identifiers, if the
452
/// angle brackets contain a list of protocol references rather than a
453
/// type parameter list.
454
///
455
/// \param rAngleLoc The location of the ending '>'.
456
ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
457
    ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
458
    SmallVectorImpl<IdentifierLocPair> &protocolIdents,
459
0
    SourceLocation &rAngleLoc, bool mayBeProtocolList) {
460
0
  assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
461
462
  // Within the type parameter list, don't treat '>' as an operator.
463
0
  GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
464
465
  // Local function to "flush" the protocol identifiers, turning them into
466
  // type parameters.
467
0
  SmallVector<Decl *, 4> typeParams;
468
0
  auto makeProtocolIdentsIntoTypeParameters = [&]() {
469
0
    unsigned index = 0;
470
0
    for (const auto &pair : protocolIdents) {
471
0
      DeclResult typeParam = Actions.actOnObjCTypeParam(
472
0
          getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
473
0
          index++, pair.first, pair.second, SourceLocation(), nullptr);
474
0
      if (typeParam.isUsable())
475
0
        typeParams.push_back(typeParam.get());
476
0
    }
477
478
0
    protocolIdents.clear();
479
0
    mayBeProtocolList = false;
480
0
  };
481
482
0
  bool invalid = false;
483
0
  lAngleLoc = ConsumeToken();
484
485
0
  do {
486
    // Parse the variance, if any.
487
0
    SourceLocation varianceLoc;
488
0
    ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
489
0
    if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
490
0
      variance = Tok.is(tok::kw___covariant)
491
0
                   ? ObjCTypeParamVariance::Covariant
492
0
                   : ObjCTypeParamVariance::Contravariant;
493
0
      varianceLoc = ConsumeToken();
494
495
      // Once we've seen a variance specific , we know this is not a
496
      // list of protocol references.
497
0
      if (mayBeProtocolList) {
498
        // Up until now, we have been queuing up parameters because they
499
        // might be protocol references. Turn them into parameters now.
500
0
        makeProtocolIdentsIntoTypeParameters();
501
0
      }
502
0
    }
503
504
    // Parse the identifier.
505
0
    if (!Tok.is(tok::identifier)) {
506
      // Code completion.
507
0
      if (Tok.is(tok::code_completion)) {
508
        // FIXME: If these aren't protocol references, we'll need different
509
        // completions.
510
0
        cutOffParsing();
511
0
        Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
512
513
        // FIXME: Better recovery here?.
514
0
        return nullptr;
515
0
      }
516
517
0
      Diag(Tok, diag::err_objc_expected_type_parameter);
518
0
      invalid = true;
519
0
      break;
520
0
    }
521
522
0
    IdentifierInfo *paramName = Tok.getIdentifierInfo();
523
0
    SourceLocation paramLoc = ConsumeToken();
524
525
    // If there is a bound, parse it.
526
0
    SourceLocation colonLoc;
527
0
    TypeResult boundType;
528
0
    if (TryConsumeToken(tok::colon, colonLoc)) {
529
      // Once we've seen a bound, we know this is not a list of protocol
530
      // references.
531
0
      if (mayBeProtocolList) {
532
        // Up until now, we have been queuing up parameters because they
533
        // might be protocol references. Turn them into parameters now.
534
0
        makeProtocolIdentsIntoTypeParameters();
535
0
      }
536
537
      // type-name
538
0
      boundType = ParseTypeName();
539
0
      if (boundType.isInvalid())
540
0
        invalid = true;
541
0
    } else if (mayBeProtocolList) {
542
      // If this could still be a protocol list, just capture the identifier.
543
      // We don't want to turn it into a parameter.
544
0
      protocolIdents.push_back(std::make_pair(paramName, paramLoc));
545
0
      continue;
546
0
    }
547
548
    // Create the type parameter.
549
0
    DeclResult typeParam = Actions.actOnObjCTypeParam(
550
0
        getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
551
0
        paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
552
0
    if (typeParam.isUsable())
553
0
      typeParams.push_back(typeParam.get());
554
0
  } while (TryConsumeToken(tok::comma));
555
556
  // Parse the '>'.
557
0
  if (invalid) {
558
0
    SkipUntil(tok::greater, tok::at, StopBeforeMatch);
559
0
    if (Tok.is(tok::greater))
560
0
      ConsumeToken();
561
0
  } else if (ParseGreaterThanInTemplateList(lAngleLoc, rAngleLoc,
562
0
                                            /*ConsumeLastToken=*/true,
563
0
                                            /*ObjCGenericList=*/true)) {
564
0
    SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
565
0
               tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
566
0
               tok::comma, tok::semi },
567
0
              StopBeforeMatch);
568
0
    if (Tok.is(tok::greater))
569
0
      ConsumeToken();
570
0
  }
571
572
0
  if (mayBeProtocolList) {
573
    // A type parameter list must be followed by either a ':' (indicating the
574
    // presence of a superclass) or a '(' (indicating that this is a category
575
    // or extension). This disambiguates between an objc-type-parameter-list
576
    // and a objc-protocol-refs.
577
0
    if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
578
      // Returning null indicates that we don't have a type parameter list.
579
      // The results the caller needs to handle the protocol references are
580
      // captured in the reference parameters already.
581
0
      return nullptr;
582
0
    }
583
584
    // We have a type parameter list that looks like a list of protocol
585
    // references. Turn that parameter list into type parameters.
586
0
    makeProtocolIdentsIntoTypeParameters();
587
0
  }
588
589
  // Form the type parameter list and enter its scope.
590
0
  ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
591
0
                              getCurScope(),
592
0
                              lAngleLoc,
593
0
                              typeParams,
594
0
                              rAngleLoc);
595
0
  Scope.enter(list);
596
597
  // Clear out the angle locations; they're used by the caller to indicate
598
  // whether there are any protocol references.
599
0
  lAngleLoc = SourceLocation();
600
0
  rAngleLoc = SourceLocation();
601
0
  return invalid ? nullptr : list;
602
0
}
603
604
/// Parse an objc-type-parameter-list.
605
0
ObjCTypeParamList *Parser::parseObjCTypeParamList() {
606
0
  SourceLocation lAngleLoc;
607
0
  SmallVector<IdentifierLocPair, 1> protocolIdents;
608
0
  SourceLocation rAngleLoc;
609
610
0
  ObjCTypeParamListScope Scope(Actions, getCurScope());
611
0
  return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
612
0
                                              rAngleLoc,
613
0
                                              /*mayBeProtocolList=*/false);
614
0
}
615
616
0
static bool isTopLevelObjCKeyword(tok::ObjCKeywordKind DirectiveKind) {
617
0
  switch (DirectiveKind) {
618
0
  case tok::objc_class:
619
0
  case tok::objc_compatibility_alias:
620
0
  case tok::objc_interface:
621
0
  case tok::objc_implementation:
622
0
  case tok::objc_protocol:
623
0
    return true;
624
0
  default:
625
0
    return false;
626
0
  }
627
0
}
628
629
///   objc-interface-decl-list:
630
///     empty
631
///     objc-interface-decl-list objc-property-decl [OBJC2]
632
///     objc-interface-decl-list objc-method-requirement [OBJC2]
633
///     objc-interface-decl-list objc-method-proto ';'
634
///     objc-interface-decl-list declaration
635
///     objc-interface-decl-list ';'
636
///
637
///   objc-method-requirement: [OBJC2]
638
///     @required
639
///     @optional
640
///
641
void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
642
0
                                        Decl *CDecl) {
643
0
  SmallVector<Decl *, 32> allMethods;
644
0
  SmallVector<DeclGroupPtrTy, 8> allTUVariables;
645
0
  tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
646
647
0
  SourceRange AtEnd;
648
649
0
  while (true) {
650
    // If this is a method prototype, parse it.
651
0
    if (Tok.isOneOf(tok::minus, tok::plus)) {
652
0
      if (Decl *methodPrototype =
653
0
          ParseObjCMethodPrototype(MethodImplKind, false))
654
0
        allMethods.push_back(methodPrototype);
655
      // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
656
      // method definitions.
657
0
      if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
658
        // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
659
0
        SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
660
0
        if (Tok.is(tok::semi))
661
0
          ConsumeToken();
662
0
      }
663
0
      continue;
664
0
    }
665
0
    if (Tok.is(tok::l_paren)) {
666
0
      Diag(Tok, diag::err_expected_minus_or_plus);
667
0
      ParseObjCMethodDecl(Tok.getLocation(),
668
0
                          tok::minus,
669
0
                          MethodImplKind, false);
670
0
      continue;
671
0
    }
672
    // Ignore excess semicolons.
673
0
    if (Tok.is(tok::semi)) {
674
      // FIXME: This should use ConsumeExtraSemi() for extraneous semicolons,
675
      // to make -Wextra-semi diagnose them.
676
0
      ConsumeToken();
677
0
      continue;
678
0
    }
679
680
    // If we got to the end of the file, exit the loop.
681
0
    if (isEofOrEom())
682
0
      break;
683
684
    // Code completion within an Objective-C interface.
685
0
    if (Tok.is(tok::code_completion)) {
686
0
      cutOffParsing();
687
0
      Actions.CodeCompleteOrdinaryName(getCurScope(),
688
0
                            CurParsedObjCImpl? Sema::PCC_ObjCImplementation
689
0
                                             : Sema::PCC_ObjCInterface);
690
0
      return;
691
0
    }
692
693
    // If we don't have an @ directive, parse it as a function definition.
694
0
    if (Tok.isNot(tok::at)) {
695
      // The code below does not consume '}'s because it is afraid of eating the
696
      // end of a namespace.  Because of the way this code is structured, an
697
      // erroneous r_brace would cause an infinite loop if not handled here.
698
0
      if (Tok.is(tok::r_brace))
699
0
        break;
700
701
0
      ParsedAttributes EmptyDeclAttrs(AttrFactory);
702
0
      ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
703
704
      // Since we call ParseDeclarationOrFunctionDefinition() instead of
705
      // ParseExternalDeclaration() below (so that this doesn't parse nested
706
      // @interfaces), this needs to duplicate some code from the latter.
707
0
      if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
708
0
        SourceLocation DeclEnd;
709
0
        ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
710
0
        allTUVariables.push_back(ParseDeclaration(DeclaratorContext::File,
711
0
                                                  DeclEnd, EmptyDeclAttrs,
712
0
                                                  EmptyDeclSpecAttrs));
713
0
        continue;
714
0
      }
715
716
0
      allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(
717
0
          EmptyDeclAttrs, EmptyDeclSpecAttrs));
718
0
      continue;
719
0
    }
720
721
    // Otherwise, we have an @ directive, peak at the next token
722
0
    SourceLocation AtLoc = Tok.getLocation();
723
0
    const auto &NextTok = NextToken();
724
0
    if (NextTok.is(tok::code_completion)) {
725
0
      cutOffParsing();
726
0
      Actions.CodeCompleteObjCAtDirective(getCurScope());
727
0
      return;
728
0
    }
729
730
0
    tok::ObjCKeywordKind DirectiveKind = NextTok.getObjCKeywordID();
731
0
    if (DirectiveKind == tok::objc_end) { // @end -> terminate list
732
0
      ConsumeToken();                     // the "@"
733
0
      AtEnd.setBegin(AtLoc);
734
0
      AtEnd.setEnd(Tok.getLocation());
735
0
      break;
736
0
    } else if (DirectiveKind == tok::objc_not_keyword) {
737
0
      Diag(NextTok, diag::err_objc_unknown_at);
738
0
      SkipUntil(tok::semi);
739
0
      continue;
740
0
    }
741
742
    // If we see something like '@interface' that's only allowed at the top
743
    // level, bail out as if we saw an '@end'. We'll diagnose this below.
744
0
    if (isTopLevelObjCKeyword(DirectiveKind))
745
0
      break;
746
747
    // Otherwise parse it as part of the current declaration. Eat "@identifier".
748
0
    ConsumeToken();
749
0
    ConsumeToken();
750
751
0
    switch (DirectiveKind) {
752
0
    default:
753
      // FIXME: If someone forgets an @end on a protocol, this loop will
754
      // continue to eat up tons of stuff and spew lots of nonsense errors.  It
755
      // would probably be better to bail out if we saw an @class or @interface
756
      // or something like that.
757
0
      Diag(AtLoc, diag::err_objc_illegal_interface_qual);
758
      // Skip until we see an '@' or '}' or ';'.
759
0
      SkipUntil(tok::r_brace, tok::at, StopAtSemi);
760
0
      break;
761
762
0
    case tok::objc_required:
763
0
    case tok::objc_optional:
764
      // This is only valid on protocols.
765
0
      if (contextKey != tok::objc_protocol)
766
0
        Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
767
0
      else
768
0
        MethodImplKind = DirectiveKind;
769
0
      break;
770
771
0
    case tok::objc_property:
772
0
      ObjCDeclSpec OCDS;
773
0
      SourceLocation LParenLoc;
774
      // Parse property attribute list, if any.
775
0
      if (Tok.is(tok::l_paren)) {
776
0
        LParenLoc = Tok.getLocation();
777
0
        ParseObjCPropertyAttribute(OCDS);
778
0
      }
779
780
0
      bool addedToDeclSpec = false;
781
0
      auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
782
0
        if (FD.D.getIdentifier() == nullptr) {
783
0
          Diag(AtLoc, diag::err_objc_property_requires_field_name)
784
0
              << FD.D.getSourceRange();
785
0
          return;
786
0
        }
787
0
        if (FD.BitfieldSize) {
788
0
          Diag(AtLoc, diag::err_objc_property_bitfield)
789
0
              << FD.D.getSourceRange();
790
0
          return;
791
0
        }
792
793
        // Map a nullability property attribute to a context-sensitive keyword
794
        // attribute.
795
0
        if (OCDS.getPropertyAttributes() &
796
0
            ObjCPropertyAttribute::kind_nullability)
797
0
          addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
798
0
                                             OCDS.getNullabilityLoc(),
799
0
                                             addedToDeclSpec);
800
801
        // Install the property declarator into interfaceDecl.
802
0
        IdentifierInfo *SelName =
803
0
            OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
804
805
0
        Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
806
0
        IdentifierInfo *SetterName = OCDS.getSetterName();
807
0
        Selector SetterSel;
808
0
        if (SetterName)
809
0
          SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
810
0
        else
811
0
          SetterSel = SelectorTable::constructSetterSelector(
812
0
              PP.getIdentifierTable(), PP.getSelectorTable(),
813
0
              FD.D.getIdentifier());
814
0
        Decl *Property = Actions.ActOnProperty(
815
0
            getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
816
0
            MethodImplKind);
817
818
0
        FD.complete(Property);
819
0
      };
820
821
      // Parse all the comma separated declarators.
822
0
      ParsingDeclSpec DS(*this);
823
0
      ParseStructDeclaration(DS, ObjCPropertyCallback);
824
825
0
      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
826
0
      break;
827
0
    }
828
0
  }
829
830
  // We break out of the big loop in 3 cases: when we see @end or when we see
831
  // top-level ObjC keyword or EOF. In the former case, eat the @end. In the
832
  // later cases, emit an error.
833
0
  if (Tok.isObjCAtKeyword(tok::objc_end)) {
834
0
    ConsumeToken(); // the "end" identifier
835
0
  } else {
836
0
    Diag(Tok, diag::err_objc_missing_end)
837
0
        << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
838
0
    Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
839
0
        << (int)Actions.getObjCContainerKind();
840
0
    AtEnd.setBegin(Tok.getLocation());
841
0
    AtEnd.setEnd(Tok.getLocation());
842
0
  }
843
844
  // Insert collected methods declarations into the @interface object.
845
  // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
846
0
  Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
847
0
}
848
849
/// Diagnose redundant or conflicting nullability information.
850
static void diagnoseRedundantPropertyNullability(Parser &P,
851
                                                 ObjCDeclSpec &DS,
852
                                                 NullabilityKind nullability,
853
0
                                                 SourceLocation nullabilityLoc){
854
0
  if (DS.getNullability() == nullability) {
855
0
    P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
856
0
      << DiagNullabilityKind(nullability, true)
857
0
      << SourceRange(DS.getNullabilityLoc());
858
0
    return;
859
0
  }
860
861
0
  P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
862
0
    << DiagNullabilityKind(nullability, true)
863
0
    << DiagNullabilityKind(DS.getNullability(), true)
864
0
    << SourceRange(DS.getNullabilityLoc());
865
0
}
866
867
///   Parse property attribute declarations.
868
///
869
///   property-attr-decl: '(' property-attrlist ')'
870
///   property-attrlist:
871
///     property-attribute
872
///     property-attrlist ',' property-attribute
873
///   property-attribute:
874
///     getter '=' identifier
875
///     setter '=' identifier ':'
876
///     direct
877
///     readonly
878
///     readwrite
879
///     assign
880
///     retain
881
///     copy
882
///     nonatomic
883
///     atomic
884
///     strong
885
///     weak
886
///     unsafe_unretained
887
///     nonnull
888
///     nullable
889
///     null_unspecified
890
///     null_resettable
891
///     class
892
///
893
0
void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
894
0
  assert(Tok.getKind() == tok::l_paren);
895
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
896
0
  T.consumeOpen();
897
898
0
  while (true) {
899
0
    if (Tok.is(tok::code_completion)) {
900
0
      cutOffParsing();
901
0
      Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
902
0
      return;
903
0
    }
904
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
905
906
    // If this is not an identifier at all, bail out early.
907
0
    if (!II) {
908
0
      T.consumeClose();
909
0
      return;
910
0
    }
911
912
0
    SourceLocation AttrName = ConsumeToken(); // consume last attribute name
913
914
0
    if (II->isStr("readonly"))
915
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
916
0
    else if (II->isStr("assign"))
917
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
918
0
    else if (II->isStr("unsafe_unretained"))
919
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_unsafe_unretained);
920
0
    else if (II->isStr("readwrite"))
921
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
922
0
    else if (II->isStr("retain"))
923
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
924
0
    else if (II->isStr("strong"))
925
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_strong);
926
0
    else if (II->isStr("copy"))
927
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
928
0
    else if (II->isStr("nonatomic"))
929
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
930
0
    else if (II->isStr("atomic"))
931
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_atomic);
932
0
    else if (II->isStr("weak"))
933
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_weak);
934
0
    else if (II->isStr("getter") || II->isStr("setter")) {
935
0
      bool IsSetter = II->getNameStart()[0] == 's';
936
937
      // getter/setter require extra treatment.
938
0
      unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
939
0
                                   diag::err_objc_expected_equal_for_getter;
940
941
0
      if (ExpectAndConsume(tok::equal, DiagID)) {
942
0
        SkipUntil(tok::r_paren, StopAtSemi);
943
0
        return;
944
0
      }
945
946
0
      if (Tok.is(tok::code_completion)) {
947
0
        cutOffParsing();
948
0
        if (IsSetter)
949
0
          Actions.CodeCompleteObjCPropertySetter(getCurScope());
950
0
        else
951
0
          Actions.CodeCompleteObjCPropertyGetter(getCurScope());
952
0
        return;
953
0
      }
954
955
0
      SourceLocation SelLoc;
956
0
      IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
957
958
0
      if (!SelIdent) {
959
0
        Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
960
0
          << IsSetter;
961
0
        SkipUntil(tok::r_paren, StopAtSemi);
962
0
        return;
963
0
      }
964
965
0
      if (IsSetter) {
966
0
        DS.setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
967
0
        DS.setSetterName(SelIdent, SelLoc);
968
969
0
        if (ExpectAndConsume(tok::colon,
970
0
                             diag::err_expected_colon_after_setter_name)) {
971
0
          SkipUntil(tok::r_paren, StopAtSemi);
972
0
          return;
973
0
        }
974
0
      } else {
975
0
        DS.setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
976
0
        DS.setGetterName(SelIdent, SelLoc);
977
0
      }
978
0
    } else if (II->isStr("nonnull")) {
979
0
      if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
980
0
        diagnoseRedundantPropertyNullability(*this, DS,
981
0
                                             NullabilityKind::NonNull,
982
0
                                             Tok.getLocation());
983
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
984
0
      DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
985
0
    } else if (II->isStr("nullable")) {
986
0
      if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
987
0
        diagnoseRedundantPropertyNullability(*this, DS,
988
0
                                             NullabilityKind::Nullable,
989
0
                                             Tok.getLocation());
990
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
991
0
      DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
992
0
    } else if (II->isStr("null_unspecified")) {
993
0
      if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
994
0
        diagnoseRedundantPropertyNullability(*this, DS,
995
0
                                             NullabilityKind::Unspecified,
996
0
                                             Tok.getLocation());
997
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
998
0
      DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
999
0
    } else if (II->isStr("null_resettable")) {
1000
0
      if (DS.getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)
1001
0
        diagnoseRedundantPropertyNullability(*this, DS,
1002
0
                                             NullabilityKind::Unspecified,
1003
0
                                             Tok.getLocation());
1004
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
1005
0
      DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
1006
1007
      // Also set the null_resettable bit.
1008
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_null_resettable);
1009
0
    } else if (II->isStr("class")) {
1010
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_class);
1011
0
    } else if (II->isStr("direct")) {
1012
0
      DS.setPropertyAttributes(ObjCPropertyAttribute::kind_direct);
1013
0
    } else {
1014
0
      Diag(AttrName, diag::err_objc_expected_property_attr) << II;
1015
0
      SkipUntil(tok::r_paren, StopAtSemi);
1016
0
      return;
1017
0
    }
1018
1019
0
    if (Tok.isNot(tok::comma))
1020
0
      break;
1021
1022
0
    ConsumeToken();
1023
0
  }
1024
1025
0
  T.consumeClose();
1026
0
}
1027
1028
///   objc-method-proto:
1029
///     objc-instance-method objc-method-decl objc-method-attributes[opt]
1030
///     objc-class-method objc-method-decl objc-method-attributes[opt]
1031
///
1032
///   objc-instance-method: '-'
1033
///   objc-class-method: '+'
1034
///
1035
///   objc-method-attributes:         [OBJC2]
1036
///     __attribute__((deprecated))
1037
///
1038
Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
1039
170
                                       bool MethodDefinition) {
1040
170
  assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
1041
1042
0
  tok::TokenKind methodType = Tok.getKind();
1043
170
  SourceLocation mLoc = ConsumeToken();
1044
170
  Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
1045
170
                                    MethodDefinition);
1046
  // Since this rule is used for both method declarations and definitions,
1047
  // the caller is (optionally) responsible for consuming the ';'.
1048
170
  return MDecl;
1049
170
}
1050
1051
///   objc-selector:
1052
///     identifier
1053
///     one of
1054
///       enum struct union if else while do for switch case default
1055
///       break continue return goto asm sizeof typeof __alignof
1056
///       unsigned long const short volatile signed restrict _Complex
1057
///       in out inout bycopy byref oneway int char float double void _Bool
1058
///
1059
171
IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
1060
1061
171
  switch (Tok.getKind()) {
1062
82
  default:
1063
82
    return nullptr;
1064
0
  case tok::colon:
1065
    // Empty selector piece uses the location of the ':'.
1066
0
    SelectorLoc = Tok.getLocation();
1067
0
    return nullptr;
1068
0
  case tok::ampamp:
1069
0
  case tok::ampequal:
1070
1
  case tok::amp:
1071
2
  case tok::pipe:
1072
3
  case tok::tilde:
1073
6
  case tok::exclaim:
1074
6
  case tok::exclaimequal:
1075
6
  case tok::pipepipe:
1076
6
  case tok::pipeequal:
1077
7
  case tok::caret:
1078
7
  case tok::caretequal: {
1079
7
    std::string ThisTok(PP.getSpelling(Tok));
1080
7
    if (isLetter(ThisTok[0])) {
1081
0
      IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1082
0
      Tok.setKind(tok::identifier);
1083
0
      SelectorLoc = ConsumeToken();
1084
0
      return II;
1085
0
    }
1086
7
    return nullptr;
1087
7
  }
1088
1089
82
  case tok::identifier:
1090
82
  case tok::kw_asm:
1091
82
  case tok::kw_auto:
1092
82
  case tok::kw_bool:
1093
82
  case tok::kw_break:
1094
82
  case tok::kw_case:
1095
82
  case tok::kw_catch:
1096
82
  case tok::kw_char:
1097
82
  case tok::kw_class:
1098
82
  case tok::kw_const:
1099
82
  case tok::kw_const_cast:
1100
82
  case tok::kw_continue:
1101
82
  case tok::kw_default:
1102
82
  case tok::kw_delete:
1103
82
  case tok::kw_do:
1104
82
  case tok::kw_double:
1105
82
  case tok::kw_dynamic_cast:
1106
82
  case tok::kw_else:
1107
82
  case tok::kw_enum:
1108
82
  case tok::kw_explicit:
1109
82
  case tok::kw_export:
1110
82
  case tok::kw_extern:
1111
82
  case tok::kw_false:
1112
82
  case tok::kw_float:
1113
82
  case tok::kw_for:
1114
82
  case tok::kw_friend:
1115
82
  case tok::kw_goto:
1116
82
  case tok::kw_if:
1117
82
  case tok::kw_inline:
1118
82
  case tok::kw_int:
1119
82
  case tok::kw_long:
1120
82
  case tok::kw_mutable:
1121
82
  case tok::kw_namespace:
1122
82
  case tok::kw_new:
1123
82
  case tok::kw_operator:
1124
82
  case tok::kw_private:
1125
82
  case tok::kw_protected:
1126
82
  case tok::kw_public:
1127
82
  case tok::kw_register:
1128
82
  case tok::kw_reinterpret_cast:
1129
82
  case tok::kw_restrict:
1130
82
  case tok::kw_return:
1131
82
  case tok::kw_short:
1132
82
  case tok::kw_signed:
1133
82
  case tok::kw_sizeof:
1134
82
  case tok::kw_static:
1135
82
  case tok::kw_static_cast:
1136
82
  case tok::kw_struct:
1137
82
  case tok::kw_switch:
1138
82
  case tok::kw_template:
1139
82
  case tok::kw_this:
1140
82
  case tok::kw_throw:
1141
82
  case tok::kw_true:
1142
82
  case tok::kw_try:
1143
82
  case tok::kw_typedef:
1144
82
  case tok::kw_typeid:
1145
82
  case tok::kw_typename:
1146
82
  case tok::kw_typeof:
1147
82
  case tok::kw_union:
1148
82
  case tok::kw_unsigned:
1149
82
  case tok::kw_using:
1150
82
  case tok::kw_virtual:
1151
82
  case tok::kw_void:
1152
82
  case tok::kw_volatile:
1153
82
  case tok::kw_wchar_t:
1154
82
  case tok::kw_while:
1155
82
  case tok::kw__Bool:
1156
82
  case tok::kw__Complex:
1157
82
  case tok::kw___alignof:
1158
82
  case tok::kw___auto_type:
1159
82
    IdentifierInfo *II = Tok.getIdentifierInfo();
1160
82
    SelectorLoc = ConsumeToken();
1161
82
    return II;
1162
171
  }
1163
171
}
1164
1165
///  objc-for-collection-in: 'in'
1166
///
1167
0
bool Parser::isTokIdentifier_in() const {
1168
  // FIXME: May have to do additional look-ahead to only allow for
1169
  // valid tokens following an 'in'; such as an identifier, unary operators,
1170
  // '[' etc.
1171
0
  return (getLangOpts().ObjC && Tok.is(tok::identifier) &&
1172
0
          Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1173
0
}
1174
1175
/// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1176
/// qualifier list and builds their bitmask representation in the input
1177
/// argument.
1178
///
1179
///   objc-type-qualifiers:
1180
///     objc-type-qualifier
1181
///     objc-type-qualifiers objc-type-qualifier
1182
///
1183
///   objc-type-qualifier:
1184
///     'in'
1185
///     'out'
1186
///     'inout'
1187
///     'oneway'
1188
///     'bycopy'
1189
///     'byref'
1190
///     'nonnull'
1191
///     'nullable'
1192
///     'null_unspecified'
1193
///
1194
void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1195
3
                                        DeclaratorContext Context) {
1196
3
  assert(Context == DeclaratorContext::ObjCParameter ||
1197
3
         Context == DeclaratorContext::ObjCResult);
1198
1199
3
  while (true) {
1200
3
    if (Tok.is(tok::code_completion)) {
1201
0
      cutOffParsing();
1202
0
      Actions.CodeCompleteObjCPassingType(
1203
0
          getCurScope(), DS, Context == DeclaratorContext::ObjCParameter);
1204
0
      return;
1205
0
    }
1206
1207
3
    if (Tok.isNot(tok::identifier))
1208
1
      return;
1209
1210
2
    const IdentifierInfo *II = Tok.getIdentifierInfo();
1211
20
    for (unsigned i = 0; i != objc_NumQuals; ++i) {
1212
18
      if (II != ObjCTypeQuals[i] ||
1213
18
          NextToken().is(tok::less) ||
1214
18
          NextToken().is(tok::coloncolon))
1215
18
        continue;
1216
1217
0
      ObjCDeclSpec::ObjCDeclQualifier Qual;
1218
0
      NullabilityKind Nullability;
1219
0
      switch (i) {
1220
0
      default: llvm_unreachable("Unknown decl qualifier");
1221
0
      case objc_in:     Qual = ObjCDeclSpec::DQ_In; break;
1222
0
      case objc_out:    Qual = ObjCDeclSpec::DQ_Out; break;
1223
0
      case objc_inout:  Qual = ObjCDeclSpec::DQ_Inout; break;
1224
0
      case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1225
0
      case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1226
0
      case objc_byref:  Qual = ObjCDeclSpec::DQ_Byref; break;
1227
1228
0
      case objc_nonnull:
1229
0
        Qual = ObjCDeclSpec::DQ_CSNullability;
1230
0
        Nullability = NullabilityKind::NonNull;
1231
0
        break;
1232
1233
0
      case objc_nullable:
1234
0
        Qual = ObjCDeclSpec::DQ_CSNullability;
1235
0
        Nullability = NullabilityKind::Nullable;
1236
0
        break;
1237
1238
0
      case objc_null_unspecified:
1239
0
        Qual = ObjCDeclSpec::DQ_CSNullability;
1240
0
        Nullability = NullabilityKind::Unspecified;
1241
0
        break;
1242
0
      }
1243
1244
      // FIXME: Diagnose redundant specifiers.
1245
0
      DS.setObjCDeclQualifier(Qual);
1246
0
      if (Qual == ObjCDeclSpec::DQ_CSNullability)
1247
0
        DS.setNullability(Tok.getLocation(), Nullability);
1248
1249
0
      ConsumeToken();
1250
0
      II = nullptr;
1251
0
      break;
1252
0
    }
1253
1254
    // If this wasn't a recognized qualifier, bail out.
1255
2
    if (II) return;
1256
2
  }
1257
3
}
1258
1259
/// Take all the decl attributes out of the given list and add
1260
/// them to the given attribute set.
1261
static void takeDeclAttributes(ParsedAttributesView &attrs,
1262
0
                               ParsedAttributesView &from) {
1263
0
  for (auto &AL : llvm::reverse(from)) {
1264
0
    if (!AL.isUsedAsTypeAttr()) {
1265
0
      from.remove(&AL);
1266
0
      attrs.addAtEnd(&AL);
1267
0
    }
1268
0
  }
1269
0
}
1270
1271
/// takeDeclAttributes - Take all the decl attributes from the given
1272
/// declarator and add them to the given list.
1273
static void takeDeclAttributes(ParsedAttributes &attrs,
1274
0
                               Declarator &D) {
1275
  // This gets called only from Parser::ParseObjCTypeName(), and that should
1276
  // never add declaration attributes to the Declarator.
1277
0
  assert(D.getDeclarationAttributes().empty());
1278
1279
  // First, take ownership of all attributes.
1280
0
  attrs.getPool().takeAllFrom(D.getAttributePool());
1281
0
  attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1282
1283
  // Now actually move the attributes over.
1284
0
  takeDeclAttributes(attrs, D.getMutableDeclSpec().getAttributes());
1285
0
  takeDeclAttributes(attrs, D.getAttributes());
1286
0
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1287
0
    takeDeclAttributes(attrs, D.getTypeObject(i).getAttrs());
1288
0
}
1289
1290
///   objc-type-name:
1291
///     '(' objc-type-qualifiers[opt] type-name ')'
1292
///     '(' objc-type-qualifiers[opt] ')'
1293
///
1294
ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1295
                                     DeclaratorContext context,
1296
3
                                     ParsedAttributes *paramAttrs) {
1297
3
  assert(context == DeclaratorContext::ObjCParameter ||
1298
3
         context == DeclaratorContext::ObjCResult);
1299
0
  assert((paramAttrs != nullptr) ==
1300
3
         (context == DeclaratorContext::ObjCParameter));
1301
1302
0
  assert(Tok.is(tok::l_paren) && "expected (");
1303
1304
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
1305
3
  T.consumeOpen();
1306
1307
3
  ObjCDeclContextSwitch ObjCDC(*this);
1308
1309
  // Parse type qualifiers, in, inout, etc.
1310
3
  ParseObjCTypeQualifierList(DS, context);
1311
3
  SourceLocation TypeStartLoc = Tok.getLocation();
1312
1313
3
  ParsedType Ty;
1314
3
  if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1315
    // Parse an abstract declarator.
1316
0
    DeclSpec declSpec(AttrFactory);
1317
0
    declSpec.setObjCQualifiers(&DS);
1318
0
    DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
1319
0
    if (context == DeclaratorContext::ObjCResult)
1320
0
      dsContext = DeclSpecContext::DSC_objc_method_result;
1321
0
    ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1322
0
    Declarator declarator(declSpec, ParsedAttributesView::none(), context);
1323
0
    ParseDeclarator(declarator);
1324
1325
    // If that's not invalid, extract a type.
1326
0
    if (!declarator.isInvalidType()) {
1327
      // Map a nullability specifier to a context-sensitive keyword attribute.
1328
0
      bool addedToDeclSpec = false;
1329
0
      if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1330
0
        addContextSensitiveTypeNullability(*this, declarator,
1331
0
                                           DS.getNullability(),
1332
0
                                           DS.getNullabilityLoc(),
1333
0
                                           addedToDeclSpec);
1334
1335
0
      TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1336
0
      if (!type.isInvalid())
1337
0
        Ty = type.get();
1338
1339
      // If we're parsing a parameter, steal all the decl attributes
1340
      // and add them to the decl spec.
1341
0
      if (context == DeclaratorContext::ObjCParameter)
1342
0
        takeDeclAttributes(*paramAttrs, declarator);
1343
0
    }
1344
0
  }
1345
1346
3
  if (Tok.is(tok::r_paren))
1347
1
    T.consumeClose();
1348
2
  else if (Tok.getLocation() == TypeStartLoc) {
1349
    // If we didn't eat any tokens, then this isn't a type.
1350
2
    Diag(Tok, diag::err_expected_type);
1351
2
    SkipUntil(tok::r_paren, StopAtSemi);
1352
2
  } else {
1353
    // Otherwise, we found *something*, but didn't get a ')' in the right
1354
    // place.  Emit an error then return what we have as the type.
1355
0
    T.consumeClose();
1356
0
  }
1357
3
  return Ty;
1358
3
}
1359
1360
///   objc-method-decl:
1361
///     objc-selector
1362
///     objc-keyword-selector objc-parmlist[opt]
1363
///     objc-type-name objc-selector
1364
///     objc-type-name objc-keyword-selector objc-parmlist[opt]
1365
///
1366
///   objc-keyword-selector:
1367
///     objc-keyword-decl
1368
///     objc-keyword-selector objc-keyword-decl
1369
///
1370
///   objc-keyword-decl:
1371
///     objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1372
///     objc-selector ':' objc-keyword-attributes[opt] identifier
1373
///     ':' objc-type-name objc-keyword-attributes[opt] identifier
1374
///     ':' objc-keyword-attributes[opt] identifier
1375
///
1376
///   objc-parmlist:
1377
///     objc-parms objc-ellipsis[opt]
1378
///
1379
///   objc-parms:
1380
///     objc-parms , parameter-declaration
1381
///
1382
///   objc-ellipsis:
1383
///     , ...
1384
///
1385
///   objc-keyword-attributes:         [OBJC2]
1386
///     __attribute__((unused))
1387
///
1388
Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1389
                                  tok::TokenKind mType,
1390
                                  tok::ObjCKeywordKind MethodImplKind,
1391
170
                                  bool MethodDefinition) {
1392
170
  ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1393
1394
170
  if (Tok.is(tok::code_completion)) {
1395
0
    cutOffParsing();
1396
0
    Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1397
0
                                       /*ReturnType=*/nullptr);
1398
0
    return nullptr;
1399
0
  }
1400
1401
  // Parse the return type if present.
1402
170
  ParsedType ReturnType;
1403
170
  ObjCDeclSpec DSRet;
1404
170
  if (Tok.is(tok::l_paren))
1405
3
    ReturnType =
1406
3
        ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResult, nullptr);
1407
1408
  // If attributes exist before the method, parse them.
1409
170
  ParsedAttributes methodAttrs(AttrFactory);
1410
170
  MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
1411
170
                       methodAttrs);
1412
1413
170
  if (Tok.is(tok::code_completion)) {
1414
0
    cutOffParsing();
1415
0
    Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1416
0
                                       ReturnType);
1417
0
    return nullptr;
1418
0
  }
1419
1420
  // Now parse the selector.
1421
170
  SourceLocation selLoc;
1422
170
  IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1423
1424
  // An unnamed colon is valid.
1425
170
  if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1426
88
    Diag(Tok, diag::err_expected_selector_for_method)
1427
88
      << SourceRange(mLoc, Tok.getLocation());
1428
    // Skip until we get a ; or @.
1429
88
    SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1430
88
    return nullptr;
1431
88
  }
1432
1433
82
  SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1434
82
  if (Tok.isNot(tok::colon)) {
1435
    // If attributes exist after the method, parse them.
1436
82
    MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
1437
82
                         methodAttrs);
1438
1439
82
    Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1440
82
    Decl *Result = Actions.ActOnMethodDeclaration(
1441
82
        getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType,
1442
82
        selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs,
1443
82
        MethodImplKind, false, MethodDefinition);
1444
82
    PD.complete(Result);
1445
82
    return Result;
1446
82
  }
1447
1448
0
  SmallVector<IdentifierInfo *, 12> KeyIdents;
1449
0
  SmallVector<SourceLocation, 12> KeyLocs;
1450
0
  SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1451
0
  ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1452
0
                            Scope::FunctionDeclarationScope | Scope::DeclScope);
1453
1454
0
  AttributePool allParamAttrs(AttrFactory);
1455
0
  while (true) {
1456
0
    ParsedAttributes paramAttrs(AttrFactory);
1457
0
    Sema::ObjCArgInfo ArgInfo;
1458
1459
    // Each iteration parses a single keyword argument.
1460
0
    if (ExpectAndConsume(tok::colon))
1461
0
      break;
1462
1463
0
    ArgInfo.Type = nullptr;
1464
0
    if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1465
0
      ArgInfo.Type = ParseObjCTypeName(
1466
0
          ArgInfo.DeclSpec, DeclaratorContext::ObjCParameter, &paramAttrs);
1467
1468
    // If attributes exist before the argument name, parse them.
1469
    // Regardless, collect all the attributes we've parsed so far.
1470
0
    MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
1471
0
                         paramAttrs);
1472
0
    ArgInfo.ArgAttrs = paramAttrs;
1473
1474
    // Code completion for the next piece of the selector.
1475
0
    if (Tok.is(tok::code_completion)) {
1476
0
      cutOffParsing();
1477
0
      KeyIdents.push_back(SelIdent);
1478
0
      Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1479
0
                                                 mType == tok::minus,
1480
0
                                                 /*AtParameterName=*/true,
1481
0
                                                 ReturnType, KeyIdents);
1482
0
      return nullptr;
1483
0
    }
1484
1485
0
    if (expectIdentifier())
1486
0
      break; // missing argument name.
1487
1488
0
    ArgInfo.Name = Tok.getIdentifierInfo();
1489
0
    ArgInfo.NameLoc = Tok.getLocation();
1490
0
    ConsumeToken(); // Eat the identifier.
1491
1492
0
    ArgInfos.push_back(ArgInfo);
1493
0
    KeyIdents.push_back(SelIdent);
1494
0
    KeyLocs.push_back(selLoc);
1495
1496
    // Make sure the attributes persist.
1497
0
    allParamAttrs.takeAllFrom(paramAttrs.getPool());
1498
1499
    // Code completion for the next piece of the selector.
1500
0
    if (Tok.is(tok::code_completion)) {
1501
0
      cutOffParsing();
1502
0
      Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1503
0
                                                 mType == tok::minus,
1504
0
                                                 /*AtParameterName=*/false,
1505
0
                                                 ReturnType, KeyIdents);
1506
0
      return nullptr;
1507
0
    }
1508
1509
    // Check for another keyword selector.
1510
0
    SelIdent = ParseObjCSelectorPiece(selLoc);
1511
0
    if (!SelIdent && Tok.isNot(tok::colon))
1512
0
      break;
1513
0
    if (!SelIdent) {
1514
0
      SourceLocation ColonLoc = Tok.getLocation();
1515
0
      if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1516
0
        Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1517
0
        Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1518
0
        Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1519
0
      }
1520
0
    }
1521
    // We have a selector or a colon, continue parsing.
1522
0
  }
1523
1524
0
  bool isVariadic = false;
1525
0
  bool cStyleParamWarned = false;
1526
  // Parse the (optional) parameter list.
1527
0
  while (Tok.is(tok::comma)) {
1528
0
    ConsumeToken();
1529
0
    if (Tok.is(tok::ellipsis)) {
1530
0
      isVariadic = true;
1531
0
      ConsumeToken();
1532
0
      break;
1533
0
    }
1534
0
    if (!cStyleParamWarned) {
1535
0
      Diag(Tok, diag::warn_cstyle_param);
1536
0
      cStyleParamWarned = true;
1537
0
    }
1538
0
    DeclSpec DS(AttrFactory);
1539
0
    ParseDeclarationSpecifiers(DS);
1540
    // Parse the declarator.
1541
0
    Declarator ParmDecl(DS, ParsedAttributesView::none(),
1542
0
                        DeclaratorContext::Prototype);
1543
0
    ParseDeclarator(ParmDecl);
1544
0
    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1545
0
    Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1546
0
    CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1547
0
                                                    ParmDecl.getIdentifierLoc(),
1548
0
                                                    Param,
1549
0
                                                    nullptr));
1550
0
  }
1551
1552
  // FIXME: Add support for optional parameter list...
1553
  // If attributes exist after the method, parse them.
1554
0
  MaybeParseAttributes(PAKM_CXX11 | (getLangOpts().ObjC ? PAKM_GNU : 0),
1555
0
                       methodAttrs);
1556
1557
0
  if (KeyIdents.size() == 0)
1558
0
    return nullptr;
1559
1560
0
  Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1561
0
                                                   &KeyIdents[0]);
1562
0
  Decl *Result = Actions.ActOnMethodDeclaration(
1563
0
      getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs,
1564
0
      Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs,
1565
0
      MethodImplKind, isVariadic, MethodDefinition);
1566
1567
0
  PD.complete(Result);
1568
0
  return Result;
1569
0
}
1570
1571
///   objc-protocol-refs:
1572
///     '<' identifier-list '>'
1573
///
1574
bool Parser::
1575
ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1576
                            SmallVectorImpl<SourceLocation> &ProtocolLocs,
1577
                            bool WarnOnDeclarations, bool ForObjCContainer,
1578
                            SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1579
80
                            bool consumeLastToken) {
1580
80
  assert(Tok.is(tok::less) && "expected <");
1581
1582
0
  LAngleLoc = ConsumeToken(); // the "<"
1583
1584
80
  SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1585
1586
81
  while (true) {
1587
81
    if (Tok.is(tok::code_completion)) {
1588
0
      cutOffParsing();
1589
0
      Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1590
0
      return true;
1591
0
    }
1592
1593
81
    if (expectIdentifier()) {
1594
40
      SkipUntil(tok::greater, StopAtSemi);
1595
40
      return true;
1596
40
    }
1597
41
    ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1598
41
                                       Tok.getLocation()));
1599
41
    ProtocolLocs.push_back(Tok.getLocation());
1600
41
    ConsumeToken();
1601
1602
41
    if (!TryConsumeToken(tok::comma))
1603
40
      break;
1604
41
  }
1605
1606
  // Consume the '>'.
1607
40
  if (ParseGreaterThanInTemplateList(LAngleLoc, EndLoc, consumeLastToken,
1608
40
                                     /*ObjCGenericList=*/false))
1609
40
    return true;
1610
1611
  // Convert the list of protocols identifiers into a list of protocol decls.
1612
0
  Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1613
0
                                  ProtocolIdents, Protocols);
1614
0
  return false;
1615
40
}
1616
1617
80
TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1618
80
  assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1619
0
  assert(getLangOpts().ObjC && "Protocol qualifiers only exist in Objective-C");
1620
1621
0
  SourceLocation lAngleLoc;
1622
80
  SmallVector<Decl *, 8> protocols;
1623
80
  SmallVector<SourceLocation, 8> protocolLocs;
1624
80
  (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1625
80
                                    lAngleLoc, rAngleLoc,
1626
80
                                    /*consumeLastToken=*/true);
1627
80
  TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1628
80
                                                             protocols,
1629
80
                                                             protocolLocs,
1630
80
                                                             rAngleLoc);
1631
80
  if (result.isUsable()) {
1632
80
    Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1633
80
      << FixItHint::CreateInsertion(lAngleLoc, "id")
1634
80
      << SourceRange(lAngleLoc, rAngleLoc);
1635
80
  }
1636
1637
80
  return result;
1638
80
}
1639
1640
/// Parse Objective-C type arguments or protocol qualifiers.
1641
///
1642
///   objc-type-arguments:
1643
///     '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1644
///
1645
void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1646
       ParsedType baseType,
1647
       SourceLocation &typeArgsLAngleLoc,
1648
       SmallVectorImpl<ParsedType> &typeArgs,
1649
       SourceLocation &typeArgsRAngleLoc,
1650
       SourceLocation &protocolLAngleLoc,
1651
       SmallVectorImpl<Decl *> &protocols,
1652
       SmallVectorImpl<SourceLocation> &protocolLocs,
1653
       SourceLocation &protocolRAngleLoc,
1654
       bool consumeLastToken,
1655
0
       bool warnOnIncompleteProtocols) {
1656
0
  assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1657
0
  SourceLocation lAngleLoc = ConsumeToken();
1658
1659
  // Whether all of the elements we've parsed thus far are single
1660
  // identifiers, which might be types or might be protocols.
1661
0
  bool allSingleIdentifiers = true;
1662
0
  SmallVector<IdentifierInfo *, 4> identifiers;
1663
0
  SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1664
1665
  // Parse a list of comma-separated identifiers, bailing out if we
1666
  // see something different.
1667
0
  do {
1668
    // Parse a single identifier.
1669
0
    if (Tok.is(tok::identifier) &&
1670
0
        (NextToken().is(tok::comma) ||
1671
0
         NextToken().is(tok::greater) ||
1672
0
         NextToken().is(tok::greatergreater))) {
1673
0
      identifiers.push_back(Tok.getIdentifierInfo());
1674
0
      identifierLocs.push_back(ConsumeToken());
1675
0
      continue;
1676
0
    }
1677
1678
0
    if (Tok.is(tok::code_completion)) {
1679
      // FIXME: Also include types here.
1680
0
      SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1681
0
      for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1682
0
        identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1683
0
                                                       identifierLocs[i]));
1684
0
      }
1685
1686
0
      QualType BaseT = Actions.GetTypeFromParser(baseType);
1687
0
      cutOffParsing();
1688
0
      if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1689
0
        Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1690
0
      } else {
1691
0
        Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1692
0
      }
1693
0
      return;
1694
0
    }
1695
1696
0
    allSingleIdentifiers = false;
1697
0
    break;
1698
0
  } while (TryConsumeToken(tok::comma));
1699
1700
  // If we parsed an identifier list, semantic analysis sorts out
1701
  // whether it refers to protocols or to type arguments.
1702
0
  if (allSingleIdentifiers) {
1703
    // Parse the closing '>'.
1704
0
    SourceLocation rAngleLoc;
1705
0
    (void)ParseGreaterThanInTemplateList(lAngleLoc, rAngleLoc, consumeLastToken,
1706
0
                                         /*ObjCGenericList=*/true);
1707
1708
    // Let Sema figure out what we parsed.
1709
0
    Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1710
0
                                                  baseType,
1711
0
                                                  lAngleLoc,
1712
0
                                                  identifiers,
1713
0
                                                  identifierLocs,
1714
0
                                                  rAngleLoc,
1715
0
                                                  typeArgsLAngleLoc,
1716
0
                                                  typeArgs,
1717
0
                                                  typeArgsRAngleLoc,
1718
0
                                                  protocolLAngleLoc,
1719
0
                                                  protocols,
1720
0
                                                  protocolRAngleLoc,
1721
0
                                                  warnOnIncompleteProtocols);
1722
0
    return;
1723
0
  }
1724
1725
  // We parsed an identifier list but stumbled into non single identifiers, this
1726
  // means we might (a) check that what we already parsed is a legitimate type
1727
  // (not a protocol or unknown type) and (b) parse the remaining ones, which
1728
  // must all be type args.
1729
1730
  // Convert the identifiers into type arguments.
1731
0
  bool invalid = false;
1732
0
  IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1733
0
  SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1734
0
  SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1735
0
  SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1736
1737
0
  for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1738
0
    ParsedType typeArg
1739
0
      = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1740
0
    if (typeArg) {
1741
0
      DeclSpec DS(AttrFactory);
1742
0
      const char *prevSpec = nullptr;
1743
0
      unsigned diagID;
1744
0
      DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1745
0
                         typeArg, Actions.getASTContext().getPrintingPolicy());
1746
1747
      // Form a declarator to turn this into a type.
1748
0
      Declarator D(DS, ParsedAttributesView::none(),
1749
0
                   DeclaratorContext::TypeName);
1750
0
      TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1751
0
      if (fullTypeArg.isUsable()) {
1752
0
        typeArgs.push_back(fullTypeArg.get());
1753
0
        if (!foundValidTypeId) {
1754
0
          foundValidTypeId = identifiers[i];
1755
0
          foundValidTypeSrcLoc = identifierLocs[i];
1756
0
        }
1757
0
      } else {
1758
0
        invalid = true;
1759
0
        unknownTypeArgs.push_back(identifiers[i]);
1760
0
        unknownTypeArgsLoc.push_back(identifierLocs[i]);
1761
0
      }
1762
0
    } else {
1763
0
      invalid = true;
1764
0
      if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1765
0
        unknownTypeArgs.push_back(identifiers[i]);
1766
0
        unknownTypeArgsLoc.push_back(identifierLocs[i]);
1767
0
      } else if (!foundProtocolId) {
1768
0
        foundProtocolId = identifiers[i];
1769
0
        foundProtocolSrcLoc = identifierLocs[i];
1770
0
      }
1771
0
    }
1772
0
  }
1773
1774
  // Continue parsing type-names.
1775
0
  do {
1776
0
    Token CurTypeTok = Tok;
1777
0
    TypeResult typeArg = ParseTypeName();
1778
1779
    // Consume the '...' for a pack expansion.
1780
0
    SourceLocation ellipsisLoc;
1781
0
    TryConsumeToken(tok::ellipsis, ellipsisLoc);
1782
0
    if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1783
0
      typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1784
0
    }
1785
1786
0
    if (typeArg.isUsable()) {
1787
0
      typeArgs.push_back(typeArg.get());
1788
0
      if (!foundValidTypeId) {
1789
0
        foundValidTypeId = CurTypeTok.getIdentifierInfo();
1790
0
        foundValidTypeSrcLoc = CurTypeTok.getLocation();
1791
0
      }
1792
0
    } else {
1793
0
      invalid = true;
1794
0
    }
1795
0
  } while (TryConsumeToken(tok::comma));
1796
1797
  // Diagnose the mix between type args and protocols.
1798
0
  if (foundProtocolId && foundValidTypeId)
1799
0
    Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1800
0
                                         foundValidTypeId,
1801
0
                                         foundValidTypeSrcLoc);
1802
1803
  // Diagnose unknown arg types.
1804
0
  ParsedType T;
1805
0
  if (unknownTypeArgs.size())
1806
0
    for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1807
0
      Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1808
0
                                      getCurScope(), nullptr, T);
1809
1810
  // Parse the closing '>'.
1811
0
  SourceLocation rAngleLoc;
1812
0
  (void)ParseGreaterThanInTemplateList(lAngleLoc, rAngleLoc, consumeLastToken,
1813
0
                                       /*ObjCGenericList=*/true);
1814
1815
0
  if (invalid) {
1816
0
    typeArgs.clear();
1817
0
    return;
1818
0
  }
1819
1820
  // Record left/right angle locations.
1821
0
  typeArgsLAngleLoc = lAngleLoc;
1822
0
  typeArgsRAngleLoc = rAngleLoc;
1823
0
}
1824
1825
void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1826
       ParsedType baseType,
1827
       SourceLocation &typeArgsLAngleLoc,
1828
       SmallVectorImpl<ParsedType> &typeArgs,
1829
       SourceLocation &typeArgsRAngleLoc,
1830
       SourceLocation &protocolLAngleLoc,
1831
       SmallVectorImpl<Decl *> &protocols,
1832
       SmallVectorImpl<SourceLocation> &protocolLocs,
1833
       SourceLocation &protocolRAngleLoc,
1834
0
       bool consumeLastToken) {
1835
0
  assert(Tok.is(tok::less));
1836
1837
  // Parse the first angle-bracket-delimited clause.
1838
0
  parseObjCTypeArgsOrProtocolQualifiers(baseType,
1839
0
                                        typeArgsLAngleLoc,
1840
0
                                        typeArgs,
1841
0
                                        typeArgsRAngleLoc,
1842
0
                                        protocolLAngleLoc,
1843
0
                                        protocols,
1844
0
                                        protocolLocs,
1845
0
                                        protocolRAngleLoc,
1846
0
                                        consumeLastToken,
1847
0
                                        /*warnOnIncompleteProtocols=*/false);
1848
0
  if (Tok.is(tok::eof)) // Nothing else to do here...
1849
0
    return;
1850
1851
  // An Objective-C object pointer followed by type arguments
1852
  // can then be followed again by a set of protocol references, e.g.,
1853
  // \c NSArray<NSView><NSTextDelegate>
1854
0
  if ((consumeLastToken && Tok.is(tok::less)) ||
1855
0
      (!consumeLastToken && NextToken().is(tok::less))) {
1856
    // If we aren't consuming the last token, the prior '>' is still hanging
1857
    // there. Consume it before we parse the protocol qualifiers.
1858
0
    if (!consumeLastToken)
1859
0
      ConsumeToken();
1860
1861
0
    if (!protocols.empty()) {
1862
0
      SkipUntilFlags skipFlags = SkipUntilFlags();
1863
0
      if (!consumeLastToken)
1864
0
        skipFlags = skipFlags | StopBeforeMatch;
1865
0
      Diag(Tok, diag::err_objc_type_args_after_protocols)
1866
0
        << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1867
0
      SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1868
0
    } else {
1869
0
      ParseObjCProtocolReferences(protocols, protocolLocs,
1870
0
                                  /*WarnOnDeclarations=*/false,
1871
0
                                  /*ForObjCContainer=*/false,
1872
0
                                  protocolLAngleLoc, protocolRAngleLoc,
1873
0
                                  consumeLastToken);
1874
0
    }
1875
0
  }
1876
0
}
1877
1878
TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1879
             SourceLocation loc,
1880
             ParsedType type,
1881
             bool consumeLastToken,
1882
0
             SourceLocation &endLoc) {
1883
0
  assert(Tok.is(tok::less));
1884
0
  SourceLocation typeArgsLAngleLoc;
1885
0
  SmallVector<ParsedType, 4> typeArgs;
1886
0
  SourceLocation typeArgsRAngleLoc;
1887
0
  SourceLocation protocolLAngleLoc;
1888
0
  SmallVector<Decl *, 4> protocols;
1889
0
  SmallVector<SourceLocation, 4> protocolLocs;
1890
0
  SourceLocation protocolRAngleLoc;
1891
1892
  // Parse type arguments and protocol qualifiers.
1893
0
  parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1894
0
                                         typeArgsRAngleLoc, protocolLAngleLoc,
1895
0
                                         protocols, protocolLocs,
1896
0
                                         protocolRAngleLoc, consumeLastToken);
1897
1898
0
  if (Tok.is(tok::eof))
1899
0
    return true; // Invalid type result.
1900
1901
  // Compute the location of the last token.
1902
0
  if (consumeLastToken)
1903
0
    endLoc = PrevTokLocation;
1904
0
  else
1905
0
    endLoc = Tok.getLocation();
1906
1907
0
  return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1908
0
           getCurScope(),
1909
0
           loc,
1910
0
           type,
1911
0
           typeArgsLAngleLoc,
1912
0
           typeArgs,
1913
0
           typeArgsRAngleLoc,
1914
0
           protocolLAngleLoc,
1915
0
           protocols,
1916
0
           protocolLocs,
1917
0
           protocolRAngleLoc);
1918
0
}
1919
1920
void Parser::HelperActionsForIvarDeclarations(
1921
    ObjCContainerDecl *interfaceDecl, SourceLocation atLoc,
1922
    BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls,
1923
0
    bool RBraceMissing) {
1924
0
  if (!RBraceMissing)
1925
0
    T.consumeClose();
1926
1927
0
  assert(getObjCDeclContext() == interfaceDecl &&
1928
0
         "Ivars should have interfaceDecl as their decl context");
1929
0
  Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1930
  // Call ActOnFields() even if we don't have any decls. This is useful
1931
  // for code rewriting tools that need to be aware of the empty list.
1932
0
  Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls,
1933
0
                      T.getOpenLocation(), T.getCloseLocation(),
1934
0
                      ParsedAttributesView());
1935
0
}
1936
1937
///   objc-class-instance-variables:
1938
///     '{' objc-instance-variable-decl-list[opt] '}'
1939
///
1940
///   objc-instance-variable-decl-list:
1941
///     objc-visibility-spec
1942
///     objc-instance-variable-decl ';'
1943
///     ';'
1944
///     objc-instance-variable-decl-list objc-visibility-spec
1945
///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
1946
///     objc-instance-variable-decl-list static_assert-declaration
1947
///     objc-instance-variable-decl-list ';'
1948
///
1949
///   objc-visibility-spec:
1950
///     @private
1951
///     @protected
1952
///     @public
1953
///     @package [OBJC2]
1954
///
1955
///   objc-instance-variable-decl:
1956
///     struct-declaration
1957
///
1958
void Parser::ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
1959
                                             tok::ObjCKeywordKind visibility,
1960
0
                                             SourceLocation atLoc) {
1961
0
  assert(Tok.is(tok::l_brace) && "expected {");
1962
0
  SmallVector<Decl *, 32> AllIvarDecls;
1963
1964
0
  ParseScope ClassScope(this, Scope::DeclScope | Scope::ClassScope);
1965
1966
0
  BalancedDelimiterTracker T(*this, tok::l_brace);
1967
0
  T.consumeOpen();
1968
  // While we still have something to read, read the instance variables.
1969
0
  while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1970
    // Each iteration of this loop reads one objc-instance-variable-decl.
1971
1972
    // Check for extraneous top-level semicolon.
1973
0
    if (Tok.is(tok::semi)) {
1974
0
      ConsumeExtraSemi(InstanceVariableList);
1975
0
      continue;
1976
0
    }
1977
1978
    // Set the default visibility to private.
1979
0
    if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1980
0
      if (Tok.is(tok::code_completion)) {
1981
0
        cutOffParsing();
1982
0
        Actions.CodeCompleteObjCAtVisibility(getCurScope());
1983
0
        return;
1984
0
      }
1985
1986
0
      switch (Tok.getObjCKeywordID()) {
1987
0
      case tok::objc_private:
1988
0
      case tok::objc_public:
1989
0
      case tok::objc_protected:
1990
0
      case tok::objc_package:
1991
0
        visibility = Tok.getObjCKeywordID();
1992
0
        ConsumeToken();
1993
0
        continue;
1994
1995
0
      case tok::objc_end:
1996
0
        Diag(Tok, diag::err_objc_unexpected_atend);
1997
0
        Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1998
0
        Tok.setKind(tok::at);
1999
0
        Tok.setLength(1);
2000
0
        PP.EnterToken(Tok, /*IsReinject*/true);
2001
0
        HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
2002
0
                                         T, AllIvarDecls, true);
2003
0
        return;
2004
2005
0
      default:
2006
0
        Diag(Tok, diag::err_objc_illegal_visibility_spec);
2007
0
        continue;
2008
0
      }
2009
0
    }
2010
2011
0
    if (Tok.is(tok::code_completion)) {
2012
0
      cutOffParsing();
2013
0
      Actions.CodeCompleteOrdinaryName(getCurScope(),
2014
0
                                       Sema::PCC_ObjCInstanceVariableList);
2015
0
      return;
2016
0
    }
2017
2018
    // This needs to duplicate a small amount of code from
2019
    // ParseStructUnionBody() for things that should work in both
2020
    // C struct and in Objective-C class instance variables.
2021
0
    if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2022
0
      SourceLocation DeclEnd;
2023
0
      ParseStaticAssertDeclaration(DeclEnd);
2024
0
      continue;
2025
0
    }
2026
2027
0
    auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
2028
0
      assert(getObjCDeclContext() == interfaceDecl &&
2029
0
             "Ivar should have interfaceDecl as its decl context");
2030
      // Install the declarator into the interface decl.
2031
0
      FD.D.setObjCIvar(true);
2032
0
      Decl *Field = Actions.ActOnIvar(
2033
0
          getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
2034
0
          FD.BitfieldSize, visibility);
2035
0
      if (Field)
2036
0
        AllIvarDecls.push_back(Field);
2037
0
      FD.complete(Field);
2038
0
    };
2039
2040
    // Parse all the comma separated declarators.
2041
0
    ParsingDeclSpec DS(*this);
2042
0
    ParseStructDeclaration(DS, ObjCIvarCallback);
2043
2044
0
    if (Tok.is(tok::semi)) {
2045
0
      ConsumeToken();
2046
0
    } else {
2047
0
      Diag(Tok, diag::err_expected_semi_decl_list);
2048
      // Skip to end of block or statement
2049
0
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2050
0
    }
2051
0
  }
2052
0
  HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
2053
0
                                   T, AllIvarDecls, false);
2054
0
}
2055
2056
///   objc-protocol-declaration:
2057
///     objc-protocol-definition
2058
///     objc-protocol-forward-reference
2059
///
2060
///   objc-protocol-definition:
2061
///     \@protocol identifier
2062
///       objc-protocol-refs[opt]
2063
///       objc-interface-decl-list
2064
///     \@end
2065
///
2066
///   objc-protocol-forward-reference:
2067
///     \@protocol identifier-list ';'
2068
///
2069
///   "\@protocol identifier ;" should be resolved as "\@protocol
2070
///   identifier-list ;": objc-interface-decl-list may not start with a
2071
///   semicolon in the first alternative if objc-protocol-refs are omitted.
2072
Parser::DeclGroupPtrTy
2073
Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2074
0
                                       ParsedAttributes &attrs) {
2075
0
  assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2076
0
         "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2077
0
  ConsumeToken(); // the "protocol" identifier
2078
2079
0
  if (Tok.is(tok::code_completion)) {
2080
0
    cutOffParsing();
2081
0
    Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2082
0
    return nullptr;
2083
0
  }
2084
2085
0
  MaybeSkipAttributes(tok::objc_protocol);
2086
2087
0
  if (expectIdentifier())
2088
0
    return nullptr; // missing protocol name.
2089
  // Save the protocol name, then consume it.
2090
0
  IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2091
0
  SourceLocation nameLoc = ConsumeToken();
2092
2093
0
  if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2094
0
    IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2095
0
    return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, attrs);
2096
0
  }
2097
2098
0
  CheckNestedObjCContexts(AtLoc);
2099
2100
0
  if (Tok.is(tok::comma)) { // list of forward declarations.
2101
0
    SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2102
0
    ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2103
2104
    // Parse the list of forward declarations.
2105
0
    while (true) {
2106
0
      ConsumeToken(); // the ','
2107
0
      if (expectIdentifier()) {
2108
0
        SkipUntil(tok::semi);
2109
0
        return nullptr;
2110
0
      }
2111
0
      ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2112
0
                                               Tok.getLocation()));
2113
0
      ConsumeToken(); // the identifier
2114
2115
0
      if (Tok.isNot(tok::comma))
2116
0
        break;
2117
0
    }
2118
    // Consume the ';'.
2119
0
    if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2120
0
      return nullptr;
2121
2122
0
    return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, attrs);
2123
0
  }
2124
2125
  // Last, and definitely not least, parse a protocol declaration.
2126
0
  SourceLocation LAngleLoc, EndProtoLoc;
2127
2128
0
  SmallVector<Decl *, 8> ProtocolRefs;
2129
0
  SmallVector<SourceLocation, 8> ProtocolLocs;
2130
0
  if (Tok.is(tok::less) &&
2131
0
      ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2132
0
                                  LAngleLoc, EndProtoLoc,
2133
0
                                  /*consumeLastToken=*/true))
2134
0
    return nullptr;
2135
2136
0
  Sema::SkipBodyInfo SkipBody;
2137
0
  ObjCProtocolDecl *ProtoType = Actions.ActOnStartProtocolInterface(
2138
0
      AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(),
2139
0
      ProtocolLocs.data(), EndProtoLoc, attrs, &SkipBody);
2140
2141
0
  ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2142
0
  if (SkipBody.CheckSameAsPrevious) {
2143
0
    auto *PreviousDef = cast<ObjCProtocolDecl>(SkipBody.Previous);
2144
0
    if (Actions.ActOnDuplicateODRHashDefinition(ProtoType, PreviousDef)) {
2145
0
      ProtoType->mergeDuplicateDefinitionWithCommon(
2146
0
          PreviousDef->getDefinition());
2147
0
    } else {
2148
0
      ODRDiagsEmitter DiagsEmitter(Diags, Actions.getASTContext(),
2149
0
                                   getPreprocessor().getLangOpts());
2150
0
      DiagsEmitter.diagnoseMismatch(PreviousDef, ProtoType);
2151
0
    }
2152
0
  }
2153
0
  return Actions.ConvertDeclToDeclGroup(ProtoType);
2154
0
}
2155
2156
///   objc-implementation:
2157
///     objc-class-implementation-prologue
2158
///     objc-category-implementation-prologue
2159
///
2160
///   objc-class-implementation-prologue:
2161
///     @implementation identifier objc-superclass[opt]
2162
///       objc-class-instance-variables[opt]
2163
///
2164
///   objc-category-implementation-prologue:
2165
///     @implementation identifier ( identifier )
2166
Parser::DeclGroupPtrTy
2167
Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
2168
0
                                             ParsedAttributes &Attrs) {
2169
0
  assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2170
0
         "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2171
0
  CheckNestedObjCContexts(AtLoc);
2172
0
  ConsumeToken(); // the "implementation" identifier
2173
2174
  // Code completion after '@implementation'.
2175
0
  if (Tok.is(tok::code_completion)) {
2176
0
    cutOffParsing();
2177
0
    Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2178
0
    return nullptr;
2179
0
  }
2180
2181
0
  MaybeSkipAttributes(tok::objc_implementation);
2182
2183
0
  if (expectIdentifier())
2184
0
    return nullptr; // missing class or category name.
2185
  // We have a class or category name - consume it.
2186
0
  IdentifierInfo *nameId = Tok.getIdentifierInfo();
2187
0
  SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2188
0
  ObjCImplDecl *ObjCImpDecl = nullptr;
2189
2190
  // Neither a type parameter list nor a list of protocol references is
2191
  // permitted here. Parse and diagnose them.
2192
0
  if (Tok.is(tok::less)) {
2193
0
    SourceLocation lAngleLoc, rAngleLoc;
2194
0
    SmallVector<IdentifierLocPair, 8> protocolIdents;
2195
0
    SourceLocation diagLoc = Tok.getLocation();
2196
0
    ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2197
0
    if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2198
0
                                             protocolIdents, rAngleLoc)) {
2199
0
      Diag(diagLoc, diag::err_objc_parameterized_implementation)
2200
0
        << SourceRange(diagLoc, PrevTokLocation);
2201
0
    } else if (lAngleLoc.isValid()) {
2202
0
      Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2203
0
        << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2204
0
    }
2205
0
  }
2206
2207
0
  if (Tok.is(tok::l_paren)) {
2208
    // we have a category implementation.
2209
0
    ConsumeParen();
2210
0
    SourceLocation categoryLoc, rparenLoc;
2211
0
    IdentifierInfo *categoryId = nullptr;
2212
2213
0
    if (Tok.is(tok::code_completion)) {
2214
0
      cutOffParsing();
2215
0
      Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2216
0
      return nullptr;
2217
0
    }
2218
2219
0
    if (Tok.is(tok::identifier)) {
2220
0
      categoryId = Tok.getIdentifierInfo();
2221
0
      categoryLoc = ConsumeToken();
2222
0
    } else {
2223
0
      Diag(Tok, diag::err_expected)
2224
0
          << tok::identifier; // missing category name.
2225
0
      return nullptr;
2226
0
    }
2227
0
    if (Tok.isNot(tok::r_paren)) {
2228
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2229
0
      SkipUntil(tok::r_paren); // don't stop at ';'
2230
0
      return nullptr;
2231
0
    }
2232
0
    rparenLoc = ConsumeParen();
2233
0
    if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2234
0
      Diag(Tok, diag::err_unexpected_protocol_qualifier);
2235
0
      SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2236
0
      SmallVector<Decl *, 4> protocols;
2237
0
      SmallVector<SourceLocation, 4> protocolLocs;
2238
0
      (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2239
0
                                        /*warnOnIncompleteProtocols=*/false,
2240
0
                                        /*ForObjCContainer=*/false,
2241
0
                                        protocolLAngleLoc, protocolRAngleLoc,
2242
0
                                        /*consumeLastToken=*/true);
2243
0
    }
2244
0
    ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2245
0
        AtLoc, nameId, nameLoc, categoryId, categoryLoc, Attrs);
2246
2247
0
  } else {
2248
    // We have a class implementation
2249
0
    SourceLocation superClassLoc;
2250
0
    IdentifierInfo *superClassId = nullptr;
2251
0
    if (TryConsumeToken(tok::colon)) {
2252
      // We have a super class
2253
0
      if (expectIdentifier())
2254
0
        return nullptr; // missing super class name.
2255
0
      superClassId = Tok.getIdentifierInfo();
2256
0
      superClassLoc = ConsumeToken(); // Consume super class name
2257
0
    }
2258
0
    ObjCImpDecl = Actions.ActOnStartClassImplementation(
2259
0
        AtLoc, nameId, nameLoc, superClassId, superClassLoc, Attrs);
2260
2261
0
    if (Tok.is(tok::l_brace)) // we have ivars
2262
0
      ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2263
0
    else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2264
0
      Diag(Tok, diag::err_unexpected_protocol_qualifier);
2265
2266
0
      SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2267
0
      SmallVector<Decl *, 4> protocols;
2268
0
      SmallVector<SourceLocation, 4> protocolLocs;
2269
0
      (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2270
0
                                        /*warnOnIncompleteProtocols=*/false,
2271
0
                                        /*ForObjCContainer=*/false,
2272
0
                                        protocolLAngleLoc, protocolRAngleLoc,
2273
0
                                        /*consumeLastToken=*/true);
2274
0
    }
2275
0
  }
2276
0
  assert(ObjCImpDecl);
2277
2278
0
  SmallVector<Decl *, 8> DeclsInGroup;
2279
2280
0
  {
2281
0
    ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2282
0
    while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2283
0
      ParsedAttributes DeclAttrs(AttrFactory);
2284
0
      MaybeParseCXX11Attributes(DeclAttrs);
2285
0
      ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2286
0
      if (DeclGroupPtrTy DGP =
2287
0
              ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs)) {
2288
0
        DeclGroupRef DG = DGP.get();
2289
0
        DeclsInGroup.append(DG.begin(), DG.end());
2290
0
      }
2291
0
    }
2292
0
  }
2293
2294
0
  return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2295
0
}
2296
2297
Parser::DeclGroupPtrTy
2298
0
Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2299
0
  assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2300
0
         "ParseObjCAtEndDeclaration(): Expected @end");
2301
0
  ConsumeToken(); // the "end" identifier
2302
0
  if (CurParsedObjCImpl)
2303
0
    CurParsedObjCImpl->finish(atEnd);
2304
0
  else
2305
    // missing @implementation
2306
0
    Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2307
0
  return nullptr;
2308
0
}
2309
2310
0
Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2311
0
  if (!Finished) {
2312
0
    finish(P.Tok.getLocation());
2313
0
    if (P.isEofOrEom()) {
2314
0
      P.Diag(P.Tok, diag::err_objc_missing_end)
2315
0
          << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2316
0
      P.Diag(Dcl->getBeginLoc(), diag::note_objc_container_start)
2317
0
          << Sema::OCK_Implementation;
2318
0
    }
2319
0
  }
2320
0
  P.CurParsedObjCImpl = nullptr;
2321
0
  assert(LateParsedObjCMethods.empty());
2322
0
}
2323
2324
0
void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2325
0
  assert(!Finished);
2326
0
  P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2327
0
  for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2328
0
    P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2329
0
                               true/*Methods*/);
2330
2331
0
  P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2332
2333
0
  if (HasCFunction)
2334
0
    for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2335
0
      P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2336
0
                                 false/*c-functions*/);
2337
2338
  /// Clear and free the cached objc methods.
2339
0
  for (LateParsedObjCMethodContainer::iterator
2340
0
         I = LateParsedObjCMethods.begin(),
2341
0
         E = LateParsedObjCMethods.end(); I != E; ++I)
2342
0
    delete *I;
2343
0
  LateParsedObjCMethods.clear();
2344
2345
0
  Finished = true;
2346
0
}
2347
2348
///   compatibility-alias-decl:
2349
///     @compatibility_alias alias-name  class-name ';'
2350
///
2351
0
Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2352
0
  assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2353
0
         "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2354
0
  ConsumeToken(); // consume compatibility_alias
2355
0
  if (expectIdentifier())
2356
0
    return nullptr;
2357
0
  IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2358
0
  SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2359
0
  if (expectIdentifier())
2360
0
    return nullptr;
2361
0
  IdentifierInfo *classId = Tok.getIdentifierInfo();
2362
0
  SourceLocation classLoc = ConsumeToken(); // consume class-name;
2363
0
  ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2364
0
  return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2365
0
                                         classId, classLoc);
2366
0
}
2367
2368
///   property-synthesis:
2369
///     @synthesize property-ivar-list ';'
2370
///
2371
///   property-ivar-list:
2372
///     property-ivar
2373
///     property-ivar-list ',' property-ivar
2374
///
2375
///   property-ivar:
2376
///     identifier
2377
///     identifier '=' identifier
2378
///
2379
0
Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2380
0
  assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2381
0
         "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2382
0
  ConsumeToken(); // consume synthesize
2383
2384
0
  while (true) {
2385
0
    if (Tok.is(tok::code_completion)) {
2386
0
      cutOffParsing();
2387
0
      Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2388
0
      return nullptr;
2389
0
    }
2390
2391
0
    if (Tok.isNot(tok::identifier)) {
2392
0
      Diag(Tok, diag::err_synthesized_property_name);
2393
0
      SkipUntil(tok::semi);
2394
0
      return nullptr;
2395
0
    }
2396
2397
0
    IdentifierInfo *propertyIvar = nullptr;
2398
0
    IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2399
0
    SourceLocation propertyLoc = ConsumeToken(); // consume property name
2400
0
    SourceLocation propertyIvarLoc;
2401
0
    if (TryConsumeToken(tok::equal)) {
2402
      // property '=' ivar-name
2403
0
      if (Tok.is(tok::code_completion)) {
2404
0
        cutOffParsing();
2405
0
        Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2406
0
        return nullptr;
2407
0
      }
2408
2409
0
      if (expectIdentifier())
2410
0
        break;
2411
0
      propertyIvar = Tok.getIdentifierInfo();
2412
0
      propertyIvarLoc = ConsumeToken(); // consume ivar-name
2413
0
    }
2414
0
    Actions.ActOnPropertyImplDecl(
2415
0
        getCurScope(), atLoc, propertyLoc, true,
2416
0
        propertyId, propertyIvar, propertyIvarLoc,
2417
0
        ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2418
0
    if (Tok.isNot(tok::comma))
2419
0
      break;
2420
0
    ConsumeToken(); // consume ','
2421
0
  }
2422
0
  ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2423
0
  return nullptr;
2424
0
}
2425
2426
///   property-dynamic:
2427
///     @dynamic  property-list
2428
///
2429
///   property-list:
2430
///     identifier
2431
///     property-list ',' identifier
2432
///
2433
0
Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2434
0
  assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2435
0
         "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2436
0
  ConsumeToken(); // consume dynamic
2437
2438
0
  bool isClassProperty = false;
2439
0
  if (Tok.is(tok::l_paren)) {
2440
0
    ConsumeParen();
2441
0
    const IdentifierInfo *II = Tok.getIdentifierInfo();
2442
2443
0
    if (!II) {
2444
0
      Diag(Tok, diag::err_objc_expected_property_attr) << II;
2445
0
      SkipUntil(tok::r_paren, StopAtSemi);
2446
0
    } else {
2447
0
      SourceLocation AttrName = ConsumeToken(); // consume attribute name
2448
0
      if (II->isStr("class")) {
2449
0
        isClassProperty = true;
2450
0
        if (Tok.isNot(tok::r_paren)) {
2451
0
          Diag(Tok, diag::err_expected) << tok::r_paren;
2452
0
          SkipUntil(tok::r_paren, StopAtSemi);
2453
0
        } else
2454
0
          ConsumeParen();
2455
0
      } else {
2456
0
        Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2457
0
        SkipUntil(tok::r_paren, StopAtSemi);
2458
0
      }
2459
0
    }
2460
0
  }
2461
2462
0
  while (true) {
2463
0
    if (Tok.is(tok::code_completion)) {
2464
0
      cutOffParsing();
2465
0
      Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2466
0
      return nullptr;
2467
0
    }
2468
2469
0
    if (expectIdentifier()) {
2470
0
      SkipUntil(tok::semi);
2471
0
      return nullptr;
2472
0
    }
2473
2474
0
    IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2475
0
    SourceLocation propertyLoc = ConsumeToken(); // consume property name
2476
0
    Actions.ActOnPropertyImplDecl(
2477
0
        getCurScope(), atLoc, propertyLoc, false,
2478
0
        propertyId, nullptr, SourceLocation(),
2479
0
        isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2480
0
        ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2481
2482
0
    if (Tok.isNot(tok::comma))
2483
0
      break;
2484
0
    ConsumeToken(); // consume ','
2485
0
  }
2486
0
  ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2487
0
  return nullptr;
2488
0
}
2489
2490
///  objc-throw-statement:
2491
///    throw expression[opt];
2492
///
2493
0
StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2494
0
  ExprResult Res;
2495
0
  ConsumeToken(); // consume throw
2496
0
  if (Tok.isNot(tok::semi)) {
2497
0
    Res = ParseExpression();
2498
0
    if (Res.isInvalid()) {
2499
0
      SkipUntil(tok::semi);
2500
0
      return StmtError();
2501
0
    }
2502
0
  }
2503
  // consume ';'
2504
0
  ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2505
0
  return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2506
0
}
2507
2508
/// objc-synchronized-statement:
2509
///   @synchronized '(' expression ')' compound-statement
2510
///
2511
StmtResult
2512
0
Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2513
0
  ConsumeToken(); // consume synchronized
2514
0
  if (Tok.isNot(tok::l_paren)) {
2515
0
    Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2516
0
    return StmtError();
2517
0
  }
2518
2519
  // The operand is surrounded with parentheses.
2520
0
  ConsumeParen();  // '('
2521
0
  ExprResult operand(ParseExpression());
2522
2523
0
  if (Tok.is(tok::r_paren)) {
2524
0
    ConsumeParen();  // ')'
2525
0
  } else {
2526
0
    if (!operand.isInvalid())
2527
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2528
2529
    // Skip forward until we see a left brace, but don't consume it.
2530
0
    SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2531
0
  }
2532
2533
  // Require a compound statement.
2534
0
  if (Tok.isNot(tok::l_brace)) {
2535
0
    if (!operand.isInvalid())
2536
0
      Diag(Tok, diag::err_expected) << tok::l_brace;
2537
0
    return StmtError();
2538
0
  }
2539
2540
  // Check the @synchronized operand now.
2541
0
  if (!operand.isInvalid())
2542
0
    operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2543
2544
  // Parse the compound statement within a new scope.
2545
0
  ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2546
0
  StmtResult body(ParseCompoundStatementBody());
2547
0
  bodyScope.Exit();
2548
2549
  // If there was a semantic or parse error earlier with the
2550
  // operand, fail now.
2551
0
  if (operand.isInvalid())
2552
0
    return StmtError();
2553
2554
0
  if (body.isInvalid())
2555
0
    body = Actions.ActOnNullStmt(Tok.getLocation());
2556
2557
0
  return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2558
0
}
2559
2560
///  objc-try-catch-statement:
2561
///    @try compound-statement objc-catch-list[opt]
2562
///    @try compound-statement objc-catch-list[opt] @finally compound-statement
2563
///
2564
///  objc-catch-list:
2565
///    @catch ( parameter-declaration ) compound-statement
2566
///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2567
///  catch-parameter-declaration:
2568
///     parameter-declaration
2569
///     '...' [OBJC2]
2570
///
2571
0
StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2572
0
  bool catch_or_finally_seen = false;
2573
2574
0
  ConsumeToken(); // consume try
2575
0
  if (Tok.isNot(tok::l_brace)) {
2576
0
    Diag(Tok, diag::err_expected) << tok::l_brace;
2577
0
    return StmtError();
2578
0
  }
2579
0
  StmtVector CatchStmts;
2580
0
  StmtResult FinallyStmt;
2581
0
  ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2582
0
  StmtResult TryBody(ParseCompoundStatementBody());
2583
0
  TryScope.Exit();
2584
0
  if (TryBody.isInvalid())
2585
0
    TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2586
2587
0
  while (Tok.is(tok::at)) {
2588
    // At this point, we need to lookahead to determine if this @ is the start
2589
    // of an @catch or @finally.  We don't want to consume the @ token if this
2590
    // is an @try or @encode or something else.
2591
0
    Token AfterAt = GetLookAheadToken(1);
2592
0
    if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2593
0
        !AfterAt.isObjCAtKeyword(tok::objc_finally))
2594
0
      break;
2595
2596
0
    SourceLocation AtCatchFinallyLoc = ConsumeToken();
2597
0
    if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2598
0
      Decl *FirstPart = nullptr;
2599
0
      ConsumeToken(); // consume catch
2600
0
      if (Tok.is(tok::l_paren)) {
2601
0
        ConsumeParen();
2602
0
        ParseScope CatchScope(this, Scope::DeclScope |
2603
0
                                        Scope::CompoundStmtScope |
2604
0
                                        Scope::AtCatchScope);
2605
0
        if (Tok.isNot(tok::ellipsis)) {
2606
0
          DeclSpec DS(AttrFactory);
2607
0
          ParseDeclarationSpecifiers(DS);
2608
0
          Declarator ParmDecl(DS, ParsedAttributesView::none(),
2609
0
                              DeclaratorContext::ObjCCatch);
2610
0
          ParseDeclarator(ParmDecl);
2611
2612
          // Inform the actions module about the declarator, so it
2613
          // gets added to the current scope.
2614
0
          FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2615
0
        } else
2616
0
          ConsumeToken(); // consume '...'
2617
2618
0
        SourceLocation RParenLoc;
2619
2620
0
        if (Tok.is(tok::r_paren))
2621
0
          RParenLoc = ConsumeParen();
2622
0
        else // Skip over garbage, until we get to ')'.  Eat the ')'.
2623
0
          SkipUntil(tok::r_paren, StopAtSemi);
2624
2625
0
        StmtResult CatchBody(true);
2626
0
        if (Tok.is(tok::l_brace))
2627
0
          CatchBody = ParseCompoundStatementBody();
2628
0
        else
2629
0
          Diag(Tok, diag::err_expected) << tok::l_brace;
2630
0
        if (CatchBody.isInvalid())
2631
0
          CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2632
2633
0
        StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2634
0
                                                              RParenLoc,
2635
0
                                                              FirstPart,
2636
0
                                                              CatchBody.get());
2637
0
        if (!Catch.isInvalid())
2638
0
          CatchStmts.push_back(Catch.get());
2639
2640
0
      } else {
2641
0
        Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2642
0
          << "@catch clause";
2643
0
        return StmtError();
2644
0
      }
2645
0
      catch_or_finally_seen = true;
2646
0
    } else {
2647
0
      assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2648
0
      ConsumeToken(); // consume finally
2649
0
      ParseScope FinallyScope(this,
2650
0
                              Scope::DeclScope | Scope::CompoundStmtScope);
2651
2652
0
      bool ShouldCapture =
2653
0
          getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2654
0
      if (ShouldCapture)
2655
0
        Actions.ActOnCapturedRegionStart(Tok.getLocation(), getCurScope(),
2656
0
                                         CR_ObjCAtFinally, 1);
2657
2658
0
      StmtResult FinallyBody(true);
2659
0
      if (Tok.is(tok::l_brace))
2660
0
        FinallyBody = ParseCompoundStatementBody();
2661
0
      else
2662
0
        Diag(Tok, diag::err_expected) << tok::l_brace;
2663
2664
0
      if (FinallyBody.isInvalid()) {
2665
0
        FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2666
0
        if (ShouldCapture)
2667
0
          Actions.ActOnCapturedRegionError();
2668
0
      } else if (ShouldCapture) {
2669
0
        FinallyBody = Actions.ActOnCapturedRegionEnd(FinallyBody.get());
2670
0
      }
2671
2672
0
      FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2673
0
                                                   FinallyBody.get());
2674
0
      catch_or_finally_seen = true;
2675
0
      break;
2676
0
    }
2677
0
  }
2678
0
  if (!catch_or_finally_seen) {
2679
0
    Diag(atLoc, diag::err_missing_catch_finally);
2680
0
    return StmtError();
2681
0
  }
2682
2683
0
  return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2684
0
                                    CatchStmts,
2685
0
                                    FinallyStmt.get());
2686
0
}
2687
2688
/// objc-autoreleasepool-statement:
2689
///   @autoreleasepool compound-statement
2690
///
2691
StmtResult
2692
0
Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2693
0
  ConsumeToken(); // consume autoreleasepool
2694
0
  if (Tok.isNot(tok::l_brace)) {
2695
0
    Diag(Tok, diag::err_expected) << tok::l_brace;
2696
0
    return StmtError();
2697
0
  }
2698
  // Enter a scope to hold everything within the compound stmt.  Compound
2699
  // statements can always hold declarations.
2700
0
  ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2701
2702
0
  StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2703
2704
0
  BodyScope.Exit();
2705
0
  if (AutoreleasePoolBody.isInvalid())
2706
0
    AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2707
0
  return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2708
0
                                                AutoreleasePoolBody.get());
2709
0
}
2710
2711
/// StashAwayMethodOrFunctionBodyTokens -  Consume the tokens and store them
2712
/// for later parsing.
2713
0
void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2714
0
  if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2715
0
      trySkippingFunctionBody()) {
2716
0
    Actions.ActOnSkippedFunctionBody(MDecl);
2717
0
    return;
2718
0
  }
2719
2720
0
  LexedMethod* LM = new LexedMethod(this, MDecl);
2721
0
  CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2722
0
  CachedTokens &Toks = LM->Toks;
2723
  // Begin by storing the '{' or 'try' or ':' token.
2724
0
  Toks.push_back(Tok);
2725
0
  if (Tok.is(tok::kw_try)) {
2726
0
    ConsumeToken();
2727
0
    if (Tok.is(tok::colon)) {
2728
0
      Toks.push_back(Tok);
2729
0
      ConsumeToken();
2730
0
      while (Tok.isNot(tok::l_brace)) {
2731
0
        ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2732
0
        ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2733
0
      }
2734
0
    }
2735
0
    Toks.push_back(Tok); // also store '{'
2736
0
  }
2737
0
  else if (Tok.is(tok::colon)) {
2738
0
    ConsumeToken();
2739
    // FIXME: This is wrong, due to C++11 braced initialization.
2740
0
    while (Tok.isNot(tok::l_brace)) {
2741
0
      ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2742
0
      ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2743
0
    }
2744
0
    Toks.push_back(Tok); // also store '{'
2745
0
  }
2746
0
  ConsumeBrace();
2747
  // Consume everything up to (and including) the matching right brace.
2748
0
  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2749
0
  while (Tok.is(tok::kw_catch)) {
2750
0
    ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2751
0
    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2752
0
  }
2753
0
}
2754
2755
///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2756
///
2757
170
Decl *Parser::ParseObjCMethodDefinition() {
2758
170
  Decl *MDecl = ParseObjCMethodPrototype();
2759
2760
170
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, MDecl, Tok.getLocation(),
2761
170
                                      "parsing Objective-C method");
2762
2763
  // parse optional ';'
2764
170
  if (Tok.is(tok::semi)) {
2765
20
    if (CurParsedObjCImpl) {
2766
0
      Diag(Tok, diag::warn_semicolon_before_method_body)
2767
0
        << FixItHint::CreateRemoval(Tok.getLocation());
2768
0
    }
2769
20
    ConsumeToken();
2770
20
  }
2771
2772
  // We should have an opening brace now.
2773
170
  if (Tok.isNot(tok::l_brace)) {
2774
169
    Diag(Tok, diag::err_expected_method_body);
2775
2776
    // Skip over garbage, until we get to '{'.  Don't eat the '{'.
2777
169
    SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2778
2779
    // If we didn't find the '{', bail out.
2780
169
    if (Tok.isNot(tok::l_brace))
2781
133
      return nullptr;
2782
169
  }
2783
2784
37
  if (!MDecl) {
2785
37
    ConsumeBrace();
2786
37
    SkipUntil(tok::r_brace);
2787
37
    return nullptr;
2788
37
  }
2789
2790
  // Allow the rest of sema to find private method decl implementations.
2791
0
  Actions.AddAnyMethodToGlobalPool(MDecl);
2792
0
  assert (CurParsedObjCImpl
2793
0
          && "ParseObjCMethodDefinition - Method out of @implementation");
2794
  // Consume the tokens and store them for later parsing.
2795
0
  StashAwayMethodOrFunctionBodyTokens(MDecl);
2796
0
  return MDecl;
2797
37
}
2798
2799
StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc,
2800
0
                                        ParsedStmtContext StmtCtx) {
2801
0
  if (Tok.is(tok::code_completion)) {
2802
0
    cutOffParsing();
2803
0
    Actions.CodeCompleteObjCAtStatement(getCurScope());
2804
0
    return StmtError();
2805
0
  }
2806
2807
0
  if (Tok.isObjCAtKeyword(tok::objc_try))
2808
0
    return ParseObjCTryStmt(AtLoc);
2809
2810
0
  if (Tok.isObjCAtKeyword(tok::objc_throw))
2811
0
    return ParseObjCThrowStmt(AtLoc);
2812
2813
0
  if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2814
0
    return ParseObjCSynchronizedStmt(AtLoc);
2815
2816
0
  if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2817
0
    return ParseObjCAutoreleasePoolStmt(AtLoc);
2818
2819
0
  if (Tok.isObjCAtKeyword(tok::objc_import) &&
2820
0
      getLangOpts().DebuggerSupport) {
2821
0
    SkipUntil(tok::semi);
2822
0
    return Actions.ActOnNullStmt(Tok.getLocation());
2823
0
  }
2824
2825
0
  ExprStatementTokLoc = AtLoc;
2826
0
  ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2827
0
  if (Res.isInvalid()) {
2828
    // If the expression is invalid, skip ahead to the next semicolon. Not
2829
    // doing this opens us up to the possibility of infinite loops if
2830
    // ParseExpression does not consume any tokens.
2831
0
    SkipUntil(tok::semi);
2832
0
    return StmtError();
2833
0
  }
2834
2835
  // Otherwise, eat the semicolon.
2836
0
  ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2837
0
  return handleExprStmt(Res, StmtCtx);
2838
0
}
2839
2840
3
ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2841
3
  switch (Tok.getKind()) {
2842
0
  case tok::code_completion:
2843
0
    cutOffParsing();
2844
0
    Actions.CodeCompleteObjCAtExpression(getCurScope());
2845
0
    return ExprError();
2846
2847
0
  case tok::minus:
2848
0
  case tok::plus: {
2849
0
    tok::TokenKind Kind = Tok.getKind();
2850
0
    SourceLocation OpLoc = ConsumeToken();
2851
2852
0
    if (!Tok.is(tok::numeric_constant)) {
2853
0
      const char *Symbol = nullptr;
2854
0
      switch (Kind) {
2855
0
      case tok::minus: Symbol = "-"; break;
2856
0
      case tok::plus: Symbol = "+"; break;
2857
0
      default: llvm_unreachable("missing unary operator case");
2858
0
      }
2859
0
      Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2860
0
        << Symbol;
2861
0
      return ExprError();
2862
0
    }
2863
2864
0
    ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2865
0
    if (Lit.isInvalid()) {
2866
0
      return Lit;
2867
0
    }
2868
0
    ConsumeToken(); // Consume the literal token.
2869
2870
0
    Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2871
0
    if (Lit.isInvalid())
2872
0
      return Lit;
2873
2874
0
    return ParsePostfixExpressionSuffix(
2875
0
             Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2876
0
  }
2877
2878
0
  case tok::string_literal:    // primary-expression: string-literal
2879
0
  case tok::wide_string_literal:
2880
0
    return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2881
2882
0
  case tok::char_constant:
2883
0
    return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2884
2885
0
  case tok::numeric_constant:
2886
0
    return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2887
2888
0
  case tok::kw_true:  // Objective-C++, etc.
2889
0
  case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2890
0
    return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2891
0
  case tok::kw_false: // Objective-C++, etc.
2892
0
  case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2893
0
    return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2894
2895
0
  case tok::l_square:
2896
    // Objective-C array literal
2897
0
    return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2898
2899
0
  case tok::l_brace:
2900
    // Objective-C dictionary literal
2901
0
    return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2902
2903
0
  case tok::l_paren:
2904
    // Objective-C boxed expression
2905
0
    return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2906
2907
3
  default:
2908
3
    if (Tok.getIdentifierInfo() == nullptr)
2909
3
      return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2910
2911
0
    switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2912
0
    case tok::objc_encode:
2913
0
      return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2914
0
    case tok::objc_protocol:
2915
0
      return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2916
0
    case tok::objc_selector:
2917
0
      return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2918
0
    case tok::objc_available:
2919
0
      return ParseAvailabilityCheckExpr(AtLoc);
2920
0
      default: {
2921
0
        const char *str = nullptr;
2922
        // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2923
        // that this is a proper statement where such directives could actually
2924
        // occur.
2925
0
        if (GetLookAheadToken(1).is(tok::l_brace) &&
2926
0
            ExprStatementTokLoc == AtLoc) {
2927
0
          char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2928
0
          str =
2929
0
            ch == 't' ? "try"
2930
0
                      : (ch == 'f' ? "finally"
2931
0
                                   : (ch == 'a' ? "autoreleasepool" : nullptr));
2932
0
        }
2933
0
        if (str) {
2934
0
          SourceLocation kwLoc = Tok.getLocation();
2935
0
          return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2936
0
                             FixItHint::CreateReplacement(kwLoc, str));
2937
0
        }
2938
0
        else
2939
0
          return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2940
0
      }
2941
0
    }
2942
3
  }
2943
3
}
2944
2945
/// Parse the receiver of an Objective-C++ message send.
2946
///
2947
/// This routine parses the receiver of a message send in
2948
/// Objective-C++ either as a type or as an expression. Note that this
2949
/// routine must not be called to parse a send to 'super', since it
2950
/// has no way to return such a result.
2951
///
2952
/// \param IsExpr Whether the receiver was parsed as an expression.
2953
///
2954
/// \param TypeOrExpr If the receiver was parsed as an expression (\c
2955
/// IsExpr is true), the parsed expression. If the receiver was parsed
2956
/// as a type (\c IsExpr is false), the parsed type.
2957
///
2958
/// \returns True if an error occurred during parsing or semantic
2959
/// analysis, in which case the arguments do not have valid
2960
/// values. Otherwise, returns false for a successful parse.
2961
///
2962
///   objc-receiver: [C++]
2963
///     'super' [not parsed here]
2964
///     expression
2965
///     simple-type-specifier
2966
///     typename-specifier
2967
0
bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2968
0
  InMessageExpressionRAIIObject InMessage(*this, true);
2969
2970
0
  if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2971
0
                  tok::annot_cxxscope))
2972
0
    TryAnnotateTypeOrScopeToken();
2973
2974
0
  if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2975
    //   objc-receiver:
2976
    //     expression
2977
    // Make sure any typos in the receiver are corrected or diagnosed, so that
2978
    // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2979
    // only the things that are valid ObjC receivers?
2980
0
    ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2981
0
    if (Receiver.isInvalid())
2982
0
      return true;
2983
2984
0
    IsExpr = true;
2985
0
    TypeOrExpr = Receiver.get();
2986
0
    return false;
2987
0
  }
2988
2989
  // objc-receiver:
2990
  //   typename-specifier
2991
  //   simple-type-specifier
2992
  //   expression (that starts with one of the above)
2993
0
  DeclSpec DS(AttrFactory);
2994
0
  ParseCXXSimpleTypeSpecifier(DS);
2995
2996
0
  if (Tok.is(tok::l_paren)) {
2997
    // If we see an opening parentheses at this point, we are
2998
    // actually parsing an expression that starts with a
2999
    // function-style cast, e.g.,
3000
    //
3001
    //   postfix-expression:
3002
    //     simple-type-specifier ( expression-list [opt] )
3003
    //     typename-specifier ( expression-list [opt] )
3004
    //
3005
    // Parse the remainder of this case, then the (optional)
3006
    // postfix-expression suffix, followed by the (optional)
3007
    // right-hand side of the binary expression. We have an
3008
    // instance method.
3009
0
    ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
3010
0
    if (!Receiver.isInvalid())
3011
0
      Receiver = ParsePostfixExpressionSuffix(Receiver.get());
3012
0
    if (!Receiver.isInvalid())
3013
0
      Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
3014
0
    if (Receiver.isInvalid())
3015
0
      return true;
3016
3017
0
    IsExpr = true;
3018
0
    TypeOrExpr = Receiver.get();
3019
0
    return false;
3020
0
  }
3021
3022
  // We have a class message. Turn the simple-type-specifier or
3023
  // typename-specifier we parsed into a type and parse the
3024
  // remainder of the class message.
3025
0
  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3026
0
                            DeclaratorContext::TypeName);
3027
0
  TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3028
0
  if (Type.isInvalid())
3029
0
    return true;
3030
3031
0
  IsExpr = false;
3032
0
  TypeOrExpr = Type.get().getAsOpaquePtr();
3033
0
  return false;
3034
0
}
3035
3036
/// Determine whether the parser is currently referring to a an
3037
/// Objective-C message send, using a simplified heuristic to avoid overhead.
3038
///
3039
/// This routine will only return true for a subset of valid message-send
3040
/// expressions.
3041
0
bool Parser::isSimpleObjCMessageExpression() {
3042
0
  assert(Tok.is(tok::l_square) && getLangOpts().ObjC &&
3043
0
         "Incorrect start for isSimpleObjCMessageExpression");
3044
0
  return GetLookAheadToken(1).is(tok::identifier) &&
3045
0
         GetLookAheadToken(2).is(tok::identifier);
3046
0
}
3047
3048
0
bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
3049
0
  if (!getLangOpts().ObjC || !NextToken().is(tok::identifier) ||
3050
0
      InMessageExpression)
3051
0
    return false;
3052
3053
0
  TypeResult Type;
3054
3055
0
  if (Tok.is(tok::annot_typename))
3056
0
    Type = getTypeAnnotation(Tok);
3057
0
  else if (Tok.is(tok::identifier))
3058
0
    Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
3059
0
                               getCurScope());
3060
0
  else
3061
0
    return false;
3062
3063
  // FIXME: Should not be querying properties of types from the parser.
3064
0
  if (Type.isUsable() && Type.get().get()->isObjCObjectOrInterfaceType()) {
3065
0
    const Token &AfterNext = GetLookAheadToken(2);
3066
0
    if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
3067
0
      if (Tok.is(tok::identifier))
3068
0
        TryAnnotateTypeOrScopeToken();
3069
3070
0
      return Tok.is(tok::annot_typename);
3071
0
    }
3072
0
  }
3073
3074
0
  return false;
3075
0
}
3076
3077
///   objc-message-expr:
3078
///     '[' objc-receiver objc-message-args ']'
3079
///
3080
///   objc-receiver: [C]
3081
///     'super'
3082
///     expression
3083
///     class-name
3084
///     type-name
3085
///
3086
4
ExprResult Parser::ParseObjCMessageExpression() {
3087
4
  assert(Tok.is(tok::l_square) && "'[' expected");
3088
0
  SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3089
3090
4
  if (Tok.is(tok::code_completion)) {
3091
0
    cutOffParsing();
3092
0
    Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3093
0
    return ExprError();
3094
0
  }
3095
3096
4
  InMessageExpressionRAIIObject InMessage(*this, true);
3097
3098
4
  if (getLangOpts().CPlusPlus) {
3099
    // We completely separate the C and C++ cases because C++ requires
3100
    // more complicated (read: slower) parsing.
3101
3102
    // Handle send to super.
3103
    // FIXME: This doesn't benefit from the same typo-correction we
3104
    // get in Objective-C.
3105
0
    if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3106
0
        NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3107
0
      return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3108
0
                                            nullptr);
3109
3110
    // Parse the receiver, which is either a type or an expression.
3111
0
    bool IsExpr;
3112
0
    void *TypeOrExpr = nullptr;
3113
0
    if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3114
0
      SkipUntil(tok::r_square, StopAtSemi);
3115
0
      return ExprError();
3116
0
    }
3117
3118
0
    if (IsExpr)
3119
0
      return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3120
0
                                            static_cast<Expr *>(TypeOrExpr));
3121
3122
0
    return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3123
0
                              ParsedType::getFromOpaquePtr(TypeOrExpr),
3124
0
                                          nullptr);
3125
0
  }
3126
3127
4
  if (Tok.is(tok::identifier)) {
3128
0
    IdentifierInfo *Name = Tok.getIdentifierInfo();
3129
0
    SourceLocation NameLoc = Tok.getLocation();
3130
0
    ParsedType ReceiverType;
3131
0
    switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3132
0
                                       Name == Ident_super,
3133
0
                                       NextToken().is(tok::period),
3134
0
                                       ReceiverType)) {
3135
0
    case Sema::ObjCSuperMessage:
3136
0
      return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3137
0
                                            nullptr);
3138
3139
0
    case Sema::ObjCClassMessage:
3140
0
      if (!ReceiverType) {
3141
0
        SkipUntil(tok::r_square, StopAtSemi);
3142
0
        return ExprError();
3143
0
      }
3144
3145
0
      ConsumeToken(); // the type name
3146
3147
      // Parse type arguments and protocol qualifiers.
3148
0
      if (Tok.is(tok::less)) {
3149
0
        SourceLocation NewEndLoc;
3150
0
        TypeResult NewReceiverType
3151
0
          = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3152
0
                                                   /*consumeLastToken=*/true,
3153
0
                                                   NewEndLoc);
3154
0
        if (!NewReceiverType.isUsable()) {
3155
0
          SkipUntil(tok::r_square, StopAtSemi);
3156
0
          return ExprError();
3157
0
        }
3158
3159
0
        ReceiverType = NewReceiverType.get();
3160
0
      }
3161
3162
0
      return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3163
0
                                            ReceiverType, nullptr);
3164
3165
0
    case Sema::ObjCInstanceMessage:
3166
      // Fall through to parse an expression.
3167
0
      break;
3168
0
    }
3169
0
  }
3170
3171
  // Otherwise, an arbitrary expression can be the receiver of a send.
3172
4
  ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3173
4
  if (Res.isInvalid()) {
3174
3
    SkipUntil(tok::r_square, StopAtSemi);
3175
3
    return Res;
3176
3
  }
3177
3178
1
  return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3179
1
                                        Res.get());
3180
4
}
3181
3182
/// Parse the remainder of an Objective-C message following the
3183
/// '[' objc-receiver.
3184
///
3185
/// This routine handles sends to super, class messages (sent to a
3186
/// class name), and instance messages (sent to an object), and the
3187
/// target is represented by \p SuperLoc, \p ReceiverType, or \p
3188
/// ReceiverExpr, respectively. Only one of these parameters may have
3189
/// a valid value.
3190
///
3191
/// \param LBracLoc The location of the opening '['.
3192
///
3193
/// \param SuperLoc If this is a send to 'super', the location of the
3194
/// 'super' keyword that indicates a send to the superclass.
3195
///
3196
/// \param ReceiverType If this is a class message, the type of the
3197
/// class we are sending a message to.
3198
///
3199
/// \param ReceiverExpr If this is an instance message, the expression
3200
/// used to compute the receiver object.
3201
///
3202
///   objc-message-args:
3203
///     objc-selector
3204
///     objc-keywordarg-list
3205
///
3206
///   objc-keywordarg-list:
3207
///     objc-keywordarg
3208
///     objc-keywordarg-list objc-keywordarg
3209
///
3210
///   objc-keywordarg:
3211
///     selector-name[opt] ':' objc-keywordexpr
3212
///
3213
///   objc-keywordexpr:
3214
///     nonempty-expr-list
3215
///
3216
///   nonempty-expr-list:
3217
///     assignment-expression
3218
///     nonempty-expr-list , assignment-expression
3219
///
3220
ExprResult
3221
Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3222
                                       SourceLocation SuperLoc,
3223
                                       ParsedType ReceiverType,
3224
1
                                       Expr *ReceiverExpr) {
3225
1
  InMessageExpressionRAIIObject InMessage(*this, true);
3226
3227
1
  if (Tok.is(tok::code_completion)) {
3228
0
    cutOffParsing();
3229
0
    if (SuperLoc.isValid())
3230
0
      Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3231
0
                                           std::nullopt, false);
3232
0
    else if (ReceiverType)
3233
0
      Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3234
0
                                           std::nullopt, false);
3235
0
    else
3236
0
      Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3237
0
                                              std::nullopt, false);
3238
0
    return ExprError();
3239
0
  }
3240
3241
  // Parse objc-selector
3242
1
  SourceLocation Loc;
3243
1
  IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3244
3245
1
  SmallVector<IdentifierInfo *, 12> KeyIdents;
3246
1
  SmallVector<SourceLocation, 12> KeyLocs;
3247
1
  ExprVector KeyExprs;
3248
3249
1
  if (Tok.is(tok::colon)) {
3250
0
    while (true) {
3251
      // Each iteration parses a single keyword argument.
3252
0
      KeyIdents.push_back(selIdent);
3253
0
      KeyLocs.push_back(Loc);
3254
3255
0
      if (ExpectAndConsume(tok::colon)) {
3256
        // We must manually skip to a ']', otherwise the expression skipper will
3257
        // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3258
        // the enclosing expression.
3259
0
        SkipUntil(tok::r_square, StopAtSemi);
3260
0
        return ExprError();
3261
0
      }
3262
3263
      ///  Parse the expression after ':'
3264
3265
0
      if (Tok.is(tok::code_completion)) {
3266
0
        cutOffParsing();
3267
0
        if (SuperLoc.isValid())
3268
0
          Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3269
0
                                               KeyIdents,
3270
0
                                               /*AtArgumentExpression=*/true);
3271
0
        else if (ReceiverType)
3272
0
          Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3273
0
                                               KeyIdents,
3274
0
                                               /*AtArgumentExpression=*/true);
3275
0
        else
3276
0
          Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3277
0
                                                  KeyIdents,
3278
0
                                                  /*AtArgumentExpression=*/true);
3279
3280
0
        return ExprError();
3281
0
      }
3282
3283
0
      ExprResult Expr;
3284
0
      if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3285
0
        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3286
0
        Expr = ParseBraceInitializer();
3287
0
      } else
3288
0
        Expr = ParseAssignmentExpression();
3289
3290
0
      ExprResult Res(Expr);
3291
0
      if (Res.isInvalid()) {
3292
        // We must manually skip to a ']', otherwise the expression skipper will
3293
        // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3294
        // the enclosing expression.
3295
0
        SkipUntil(tok::r_square, StopAtSemi);
3296
0
        return Res;
3297
0
      }
3298
3299
      // We have a valid expression.
3300
0
      KeyExprs.push_back(Res.get());
3301
3302
      // Code completion after each argument.
3303
0
      if (Tok.is(tok::code_completion)) {
3304
0
        cutOffParsing();
3305
0
        if (SuperLoc.isValid())
3306
0
          Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3307
0
                                               KeyIdents,
3308
0
                                               /*AtArgumentExpression=*/false);
3309
0
        else if (ReceiverType)
3310
0
          Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3311
0
                                               KeyIdents,
3312
0
                                               /*AtArgumentExpression=*/false);
3313
0
        else
3314
0
          Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3315
0
                                                  KeyIdents,
3316
0
                                                /*AtArgumentExpression=*/false);
3317
0
        return ExprError();
3318
0
      }
3319
3320
      // Check for another keyword selector.
3321
0
      selIdent = ParseObjCSelectorPiece(Loc);
3322
0
      if (!selIdent && Tok.isNot(tok::colon))
3323
0
        break;
3324
      // We have a selector or a colon, continue parsing.
3325
0
    }
3326
    // Parse the, optional, argument list, comma separated.
3327
0
    while (Tok.is(tok::comma)) {
3328
0
      SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3329
      ///  Parse the expression after ','
3330
0
      ExprResult Res(ParseAssignmentExpression());
3331
0
      if (Tok.is(tok::colon))
3332
0
        Res = Actions.CorrectDelayedTyposInExpr(Res);
3333
0
      if (Res.isInvalid()) {
3334
0
        if (Tok.is(tok::colon)) {
3335
0
          Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3336
0
            FixItHint::CreateRemoval(commaLoc);
3337
0
        }
3338
        // We must manually skip to a ']', otherwise the expression skipper will
3339
        // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3340
        // the enclosing expression.
3341
0
        SkipUntil(tok::r_square, StopAtSemi);
3342
0
        return Res;
3343
0
      }
3344
3345
      // We have a valid expression.
3346
0
      KeyExprs.push_back(Res.get());
3347
0
    }
3348
1
  } else if (!selIdent) {
3349
1
    Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3350
3351
    // We must manually skip to a ']', otherwise the expression skipper will
3352
    // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3353
    // the enclosing expression.
3354
1
    SkipUntil(tok::r_square, StopAtSemi);
3355
1
    return ExprError();
3356
1
  }
3357
3358
0
  if (Tok.isNot(tok::r_square)) {
3359
0
    Diag(Tok, diag::err_expected)
3360
0
        << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3361
    // We must manually skip to a ']', otherwise the expression skipper will
3362
    // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3363
    // the enclosing expression.
3364
0
    SkipUntil(tok::r_square, StopAtSemi);
3365
0
    return ExprError();
3366
0
  }
3367
3368
0
  SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3369
3370
0
  unsigned nKeys = KeyIdents.size();
3371
0
  if (nKeys == 0) {
3372
0
    KeyIdents.push_back(selIdent);
3373
0
    KeyLocs.push_back(Loc);
3374
0
  }
3375
0
  Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3376
3377
0
  if (SuperLoc.isValid())
3378
0
    return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3379
0
                                     LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3380
0
  else if (ReceiverType)
3381
0
    return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3382
0
                                     LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3383
0
  return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3384
0
                                      LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3385
0
}
3386
3387
0
ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3388
0
  ExprResult Res(ParseStringLiteralExpression());
3389
0
  if (Res.isInvalid()) return Res;
3390
3391
  // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
3392
  // expressions.  At this point, we know that the only valid thing that starts
3393
  // with '@' is an @"".
3394
0
  SmallVector<SourceLocation, 4> AtLocs;
3395
0
  ExprVector AtStrings;
3396
0
  AtLocs.push_back(AtLoc);
3397
0
  AtStrings.push_back(Res.get());
3398
3399
0
  while (Tok.is(tok::at)) {
3400
0
    AtLocs.push_back(ConsumeToken()); // eat the @.
3401
3402
    // Invalid unless there is a string literal.
3403
0
    if (!isTokenStringLiteral())
3404
0
      return ExprError(Diag(Tok, diag::err_objc_concat_string));
3405
3406
0
    ExprResult Lit(ParseStringLiteralExpression());
3407
0
    if (Lit.isInvalid())
3408
0
      return Lit;
3409
3410
0
    AtStrings.push_back(Lit.get());
3411
0
  }
3412
3413
0
  return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3414
0
}
3415
3416
/// ParseObjCBooleanLiteral -
3417
/// objc-scalar-literal : '@' boolean-keyword
3418
///                        ;
3419
/// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3420
///                        ;
3421
ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3422
0
                                           bool ArgValue) {
3423
0
  SourceLocation EndLoc = ConsumeToken();             // consume the keyword.
3424
0
  return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3425
0
}
3426
3427
/// ParseObjCCharacterLiteral -
3428
/// objc-scalar-literal : '@' character-literal
3429
///                        ;
3430
0
ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3431
0
  ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3432
0
  if (Lit.isInvalid()) {
3433
0
    return Lit;
3434
0
  }
3435
0
  ConsumeToken(); // Consume the literal token.
3436
0
  return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3437
0
}
3438
3439
/// ParseObjCNumericLiteral -
3440
/// objc-scalar-literal : '@' scalar-literal
3441
///                        ;
3442
/// scalar-literal : | numeric-constant     /* any numeric constant. */
3443
///                    ;
3444
0
ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3445
0
  ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3446
0
  if (Lit.isInvalid()) {
3447
0
    return Lit;
3448
0
  }
3449
0
  ConsumeToken(); // Consume the literal token.
3450
0
  return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3451
0
}
3452
3453
/// ParseObjCBoxedExpr -
3454
/// objc-box-expression:
3455
///       @( assignment-expression )
3456
ExprResult
3457
0
Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3458
0
  if (Tok.isNot(tok::l_paren))
3459
0
    return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3460
3461
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
3462
0
  T.consumeOpen();
3463
0
  ExprResult ValueExpr(ParseAssignmentExpression());
3464
0
  if (T.consumeClose())
3465
0
    return ExprError();
3466
3467
0
  if (ValueExpr.isInvalid())
3468
0
    return ExprError();
3469
3470
  // Wrap the sub-expression in a parenthesized expression, to distinguish
3471
  // a boxed expression from a literal.
3472
0
  SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3473
0
  ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3474
0
  return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3475
0
                                    ValueExpr.get());
3476
0
}
3477
3478
0
ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3479
0
  ExprVector ElementExprs;                   // array elements.
3480
0
  ConsumeBracket(); // consume the l_square.
3481
3482
0
  bool HasInvalidEltExpr = false;
3483
0
  while (Tok.isNot(tok::r_square)) {
3484
    // Parse list of array element expressions (all must be id types).
3485
0
    ExprResult Res(ParseAssignmentExpression());
3486
0
    if (Res.isInvalid()) {
3487
      // We must manually skip to a ']', otherwise the expression skipper will
3488
      // stop at the ']' when it skips to the ';'.  We want it to skip beyond
3489
      // the enclosing expression.
3490
0
      SkipUntil(tok::r_square, StopAtSemi);
3491
0
      return Res;
3492
0
    }
3493
3494
0
    Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3495
0
    if (Res.isInvalid())
3496
0
      HasInvalidEltExpr = true;
3497
3498
    // Parse the ellipsis that indicates a pack expansion.
3499
0
    if (Tok.is(tok::ellipsis))
3500
0
      Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3501
0
    if (Res.isInvalid())
3502
0
      HasInvalidEltExpr = true;
3503
3504
0
    ElementExprs.push_back(Res.get());
3505
3506
0
    if (Tok.is(tok::comma))
3507
0
      ConsumeToken(); // Eat the ','.
3508
0
    else if (Tok.isNot(tok::r_square))
3509
0
      return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3510
0
                                                            << tok::comma);
3511
0
  }
3512
0
  SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3513
3514
0
  if (HasInvalidEltExpr)
3515
0
    return ExprError();
3516
3517
0
  MultiExprArg Args(ElementExprs);
3518
0
  return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3519
0
}
3520
3521
0
ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3522
0
  SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3523
0
  ConsumeBrace(); // consume the l_square.
3524
0
  bool HasInvalidEltExpr = false;
3525
0
  while (Tok.isNot(tok::r_brace)) {
3526
    // Parse the comma separated key : value expressions.
3527
0
    ExprResult KeyExpr;
3528
0
    {
3529
0
      ColonProtectionRAIIObject X(*this);
3530
0
      KeyExpr = ParseAssignmentExpression();
3531
0
      if (KeyExpr.isInvalid()) {
3532
        // We must manually skip to a '}', otherwise the expression skipper will
3533
        // stop at the '}' when it skips to the ';'.  We want it to skip beyond
3534
        // the enclosing expression.
3535
0
        SkipUntil(tok::r_brace, StopAtSemi);
3536
0
        return KeyExpr;
3537
0
      }
3538
0
    }
3539
3540
0
    if (ExpectAndConsume(tok::colon)) {
3541
0
      SkipUntil(tok::r_brace, StopAtSemi);
3542
0
      return ExprError();
3543
0
    }
3544
3545
0
    ExprResult ValueExpr(ParseAssignmentExpression());
3546
0
    if (ValueExpr.isInvalid()) {
3547
      // We must manually skip to a '}', otherwise the expression skipper will
3548
      // stop at the '}' when it skips to the ';'.  We want it to skip beyond
3549
      // the enclosing expression.
3550
0
      SkipUntil(tok::r_brace, StopAtSemi);
3551
0
      return ValueExpr;
3552
0
    }
3553
3554
    // Check the key and value for possible typos
3555
0
    KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3556
0
    ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3557
0
    if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3558
0
      HasInvalidEltExpr = true;
3559
3560
    // Parse the ellipsis that designates this as a pack expansion. Do not
3561
    // ActOnPackExpansion here, leave it to template instantiation time where
3562
    // we can get better diagnostics.
3563
0
    SourceLocation EllipsisLoc;
3564
0
    if (getLangOpts().CPlusPlus)
3565
0
      TryConsumeToken(tok::ellipsis, EllipsisLoc);
3566
3567
    // We have a valid expression. Collect it in a vector so we can
3568
    // build the argument list.
3569
0
    ObjCDictionaryElement Element = {KeyExpr.get(), ValueExpr.get(),
3570
0
                                     EllipsisLoc, std::nullopt};
3571
0
    Elements.push_back(Element);
3572
3573
0
    if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3574
0
      return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3575
0
                                                            << tok::comma);
3576
0
  }
3577
0
  SourceLocation EndLoc = ConsumeBrace();
3578
3579
0
  if (HasInvalidEltExpr)
3580
0
    return ExprError();
3581
3582
  // Create the ObjCDictionaryLiteral.
3583
0
  return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3584
0
                                            Elements);
3585
0
}
3586
3587
///    objc-encode-expression:
3588
///      \@encode ( type-name )
3589
ExprResult
3590
0
Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3591
0
  assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3592
3593
0
  SourceLocation EncLoc = ConsumeToken();
3594
3595
0
  if (Tok.isNot(tok::l_paren))
3596
0
    return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3597
3598
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
3599
0
  T.consumeOpen();
3600
3601
0
  TypeResult Ty = ParseTypeName();
3602
3603
0
  T.consumeClose();
3604
3605
0
  if (Ty.isInvalid())
3606
0
    return ExprError();
3607
3608
0
  return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3609
0
                                           Ty.get(), T.getCloseLocation());
3610
0
}
3611
3612
///     objc-protocol-expression
3613
///       \@protocol ( protocol-name )
3614
ExprResult
3615
0
Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3616
0
  SourceLocation ProtoLoc = ConsumeToken();
3617
3618
0
  if (Tok.isNot(tok::l_paren))
3619
0
    return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3620
3621
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
3622
0
  T.consumeOpen();
3623
3624
0
  if (expectIdentifier())
3625
0
    return ExprError();
3626
3627
0
  IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3628
0
  SourceLocation ProtoIdLoc = ConsumeToken();
3629
3630
0
  T.consumeClose();
3631
3632
0
  return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3633
0
                                             T.getOpenLocation(), ProtoIdLoc,
3634
0
                                             T.getCloseLocation());
3635
0
}
3636
3637
///     objc-selector-expression
3638
///       @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3639
0
ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3640
0
  SourceLocation SelectorLoc = ConsumeToken();
3641
3642
0
  if (Tok.isNot(tok::l_paren))
3643
0
    return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3644
3645
0
  SmallVector<IdentifierInfo *, 12> KeyIdents;
3646
0
  SourceLocation sLoc;
3647
3648
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
3649
0
  T.consumeOpen();
3650
0
  bool HasOptionalParen = Tok.is(tok::l_paren);
3651
0
  if (HasOptionalParen)
3652
0
    ConsumeParen();
3653
3654
0
  if (Tok.is(tok::code_completion)) {
3655
0
    cutOffParsing();
3656
0
    Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3657
0
    return ExprError();
3658
0
  }
3659
3660
0
  IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3661
0
  if (!SelIdent &&  // missing selector name.
3662
0
      Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3663
0
    return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3664
3665
0
  KeyIdents.push_back(SelIdent);
3666
3667
0
  unsigned nColons = 0;
3668
0
  if (Tok.isNot(tok::r_paren)) {
3669
0
    while (true) {
3670
0
      if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3671
0
        ++nColons;
3672
0
        KeyIdents.push_back(nullptr);
3673
0
      } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3674
0
        return ExprError();
3675
0
      ++nColons;
3676
3677
0
      if (Tok.is(tok::r_paren))
3678
0
        break;
3679
3680
0
      if (Tok.is(tok::code_completion)) {
3681
0
        cutOffParsing();
3682
0
        Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3683
0
        return ExprError();
3684
0
      }
3685
3686
      // Check for another keyword selector.
3687
0
      SourceLocation Loc;
3688
0
      SelIdent = ParseObjCSelectorPiece(Loc);
3689
0
      KeyIdents.push_back(SelIdent);
3690
0
      if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3691
0
        break;
3692
0
    }
3693
0
  }
3694
0
  if (HasOptionalParen && Tok.is(tok::r_paren))
3695
0
    ConsumeParen(); // ')'
3696
0
  T.consumeClose();
3697
0
  Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3698
0
  return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3699
0
                                             T.getOpenLocation(),
3700
0
                                             T.getCloseLocation(),
3701
0
                                             !HasOptionalParen);
3702
0
}
3703
3704
0
void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3705
  // MCDecl might be null due to error in method or c-function  prototype, etc.
3706
0
  Decl *MCDecl = LM.D;
3707
0
  bool skip = MCDecl &&
3708
0
              ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3709
0
              (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3710
0
  if (skip)
3711
0
    return;
3712
3713
  // Save the current token position.
3714
0
  SourceLocation OrigLoc = Tok.getLocation();
3715
3716
0
  assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3717
  // Store an artificial EOF token to ensure that we don't run off the end of
3718
  // the method's body when we come to parse it.
3719
0
  Token Eof;
3720
0
  Eof.startToken();
3721
0
  Eof.setKind(tok::eof);
3722
0
  Eof.setEofData(MCDecl);
3723
0
  Eof.setLocation(OrigLoc);
3724
0
  LM.Toks.push_back(Eof);
3725
  // Append the current token at the end of the new token stream so that it
3726
  // doesn't get lost.
3727
0
  LM.Toks.push_back(Tok);
3728
0
  PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
3729
3730
  // Consume the previously pushed token.
3731
0
  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3732
3733
0
  assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3734
0
         "Inline objective-c method not starting with '{' or 'try' or ':'");
3735
  // Enter a scope for the method or c-function body.
3736
0
  ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3737
0
                                 Scope::FnScope | Scope::DeclScope |
3738
0
                                 Scope::CompoundStmtScope);
3739
3740
  // Tell the actions module that we have entered a method or c-function definition
3741
  // with the specified Declarator for the method/function.
3742
0
  if (parseMethod)
3743
0
    Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3744
0
  else
3745
0
    Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3746
0
  if (Tok.is(tok::kw_try))
3747
0
    ParseFunctionTryBlock(MCDecl, BodyScope);
3748
0
  else {
3749
0
    if (Tok.is(tok::colon))
3750
0
      ParseConstructorInitializer(MCDecl);
3751
0
    else
3752
0
      Actions.ActOnDefaultCtorInitializers(MCDecl);
3753
0
    ParseFunctionStatementBody(MCDecl, BodyScope);
3754
0
  }
3755
3756
0
  if (Tok.getLocation() != OrigLoc) {
3757
    // Due to parsing error, we either went over the cached tokens or
3758
    // there are still cached tokens left. If it's the latter case skip the
3759
    // leftover tokens.
3760
    // Since this is an uncommon situation that should be avoided, use the
3761
    // expensive isBeforeInTranslationUnit call.
3762
0
    if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3763
0
                                                     OrigLoc))
3764
0
      while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3765
0
        ConsumeAnyToken();
3766
0
  }
3767
  // Clean up the remaining EOF token, only if it's inserted by us. Otherwise
3768
  // this might be code-completion token, which must be propagated to callers.
3769
0
  if (Tok.is(tok::eof) && Tok.getEofData() == MCDecl)
3770
0
    ConsumeAnyToken();
3771
0
}