1 | //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// |
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 defines the Parser interface. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_PARSE_PARSER_H |
14 | #define LLVM_CLANG_PARSE_PARSER_H |
15 | |
16 | #include "clang/Basic/OpenACCKinds.h" |
17 | #include "clang/Basic/OperatorPrecedence.h" |
18 | #include "clang/Lex/CodeCompletionHandler.h" |
19 | #include "clang/Lex/Preprocessor.h" |
20 | #include "clang/Sema/Sema.h" |
21 | #include "llvm/ADT/SmallVector.h" |
22 | #include "llvm/Frontend/OpenMP/OMPContext.h" |
23 | #include "llvm/Support/SaveAndRestore.h" |
24 | #include <optional> |
25 | #include <stack> |
26 | |
27 | namespace clang { |
28 | class PragmaHandler; |
29 | class Scope; |
30 | class BalancedDelimiterTracker; |
31 | class CorrectionCandidateCallback; |
32 | class DeclGroupRef; |
33 | class DiagnosticBuilder; |
34 | struct LoopHint; |
35 | class Parser; |
36 | class ParsingDeclRAIIObject; |
37 | class ParsingDeclSpec; |
38 | class ParsingDeclarator; |
39 | class ParsingFieldDeclarator; |
40 | class ColonProtectionRAIIObject; |
41 | class InMessageExpressionRAIIObject; |
42 | class PoisonSEHIdentifiersRAIIObject; |
43 | class OMPClause; |
44 | class ObjCTypeParamList; |
45 | struct OMPTraitProperty; |
46 | struct OMPTraitSelector; |
47 | struct OMPTraitSet; |
48 | class OMPTraitInfo; |
49 | |
50 | /// Parser - This implements a parser for the C family of languages. After |
51 | /// parsing units of the grammar, productions are invoked to handle whatever has |
52 | /// been read. |
53 | /// |
54 | class Parser : public CodeCompletionHandler { |
55 | friend class ColonProtectionRAIIObject; |
56 | friend class ParsingOpenMPDirectiveRAII; |
57 | friend class ParsingOpenACCDirectiveRAII; |
58 | friend class InMessageExpressionRAIIObject; |
59 | friend class OffsetOfStateRAIIObject; |
60 | friend class PoisonSEHIdentifiersRAIIObject; |
61 | friend class ObjCDeclContextSwitch; |
62 | friend class ParenBraceBracketBalancer; |
63 | friend class BalancedDelimiterTracker; |
64 | |
65 | Preprocessor &PP; |
66 | |
67 | /// Tok - The current token we are peeking ahead. All parsing methods assume |
68 | /// that this is valid. |
69 | Token Tok; |
70 | |
71 | // PrevTokLocation - The location of the token we previously |
72 | // consumed. This token is used for diagnostics where we expected to |
73 | // see a token following another token (e.g., the ';' at the end of |
74 | // a statement). |
75 | SourceLocation PrevTokLocation; |
76 | |
77 | /// Tracks an expected type for the current token when parsing an expression. |
78 | /// Used by code completion for ranking. |
79 | PreferredTypeBuilder PreferredType; |
80 | |
81 | unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; |
82 | unsigned short MisplacedModuleBeginCount = 0; |
83 | |
84 | /// Actions - These are the callbacks we invoke as we parse various constructs |
85 | /// in the file. |
86 | Sema &Actions; |
87 | |
88 | DiagnosticsEngine &Diags; |
89 | |
90 | /// ScopeCache - Cache scopes to reduce malloc traffic. |
91 | enum { ScopeCacheSize = 16 }; |
92 | unsigned NumCachedScopes; |
93 | Scope *ScopeCache[ScopeCacheSize]; |
94 | |
95 | /// Identifiers used for SEH handling in Borland. These are only |
96 | /// allowed in particular circumstances |
97 | // __except block |
98 | IdentifierInfo *Ident__exception_code, |
99 | *Ident___exception_code, |
100 | *Ident_GetExceptionCode; |
101 | // __except filter expression |
102 | IdentifierInfo *Ident__exception_info, |
103 | *Ident___exception_info, |
104 | *Ident_GetExceptionInfo; |
105 | // __finally |
106 | IdentifierInfo *Ident__abnormal_termination, |
107 | *Ident___abnormal_termination, |
108 | *Ident_AbnormalTermination; |
109 | |
110 | /// Contextual keywords for Microsoft extensions. |
111 | IdentifierInfo *Ident__except; |
112 | mutable IdentifierInfo *Ident_sealed; |
113 | mutable IdentifierInfo *Ident_abstract; |
114 | |
115 | /// Ident_super - IdentifierInfo for "super", to support fast |
116 | /// comparison. |
117 | IdentifierInfo *Ident_super; |
118 | /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector" |
119 | /// and "bool" fast comparison. Only present if AltiVec or ZVector are |
120 | /// enabled. |
121 | IdentifierInfo *Ident_vector; |
122 | IdentifierInfo *Ident_bool; |
123 | IdentifierInfo *Ident_Bool; |
124 | /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. |
125 | /// Only present if AltiVec enabled. |
126 | IdentifierInfo *Ident_pixel; |
127 | |
128 | /// Objective-C contextual keywords. |
129 | IdentifierInfo *Ident_instancetype; |
130 | |
131 | /// Identifier for "introduced". |
132 | IdentifierInfo *Ident_introduced; |
133 | |
134 | /// Identifier for "deprecated". |
135 | IdentifierInfo *Ident_deprecated; |
136 | |
137 | /// Identifier for "obsoleted". |
138 | IdentifierInfo *Ident_obsoleted; |
139 | |
140 | /// Identifier for "unavailable". |
141 | IdentifierInfo *Ident_unavailable; |
142 | |
143 | /// Identifier for "message". |
144 | IdentifierInfo *Ident_message; |
145 | |
146 | /// Identifier for "strict". |
147 | IdentifierInfo *Ident_strict; |
148 | |
149 | /// Identifier for "replacement". |
150 | IdentifierInfo *Ident_replacement; |
151 | |
152 | /// Identifiers used by the 'external_source_symbol' attribute. |
153 | IdentifierInfo *Ident_language, *Ident_defined_in, |
154 | *Ident_generated_declaration, *Ident_USR; |
155 | |
156 | /// C++11 contextual keywords. |
157 | mutable IdentifierInfo *Ident_final; |
158 | mutable IdentifierInfo *Ident_GNU_final; |
159 | mutable IdentifierInfo *Ident_override; |
160 | |
161 | // C++2a contextual keywords. |
162 | mutable IdentifierInfo *Ident_import; |
163 | mutable IdentifierInfo *Ident_module; |
164 | |
165 | // C++ type trait keywords that can be reverted to identifiers and still be |
166 | // used as type traits. |
167 | llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; |
168 | |
169 | std::unique_ptr<PragmaHandler> AlignHandler; |
170 | std::unique_ptr<PragmaHandler> GCCVisibilityHandler; |
171 | std::unique_ptr<PragmaHandler> OptionsHandler; |
172 | std::unique_ptr<PragmaHandler> PackHandler; |
173 | std::unique_ptr<PragmaHandler> MSStructHandler; |
174 | std::unique_ptr<PragmaHandler> UnusedHandler; |
175 | std::unique_ptr<PragmaHandler> WeakHandler; |
176 | std::unique_ptr<PragmaHandler> RedefineExtnameHandler; |
177 | std::unique_ptr<PragmaHandler> FPContractHandler; |
178 | std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; |
179 | std::unique_ptr<PragmaHandler> OpenMPHandler; |
180 | std::unique_ptr<PragmaHandler> OpenACCHandler; |
181 | std::unique_ptr<PragmaHandler> PCSectionHandler; |
182 | std::unique_ptr<PragmaHandler> MSCommentHandler; |
183 | std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; |
184 | std::unique_ptr<PragmaHandler> FPEvalMethodHandler; |
185 | std::unique_ptr<PragmaHandler> FloatControlHandler; |
186 | std::unique_ptr<PragmaHandler> MSPointersToMembers; |
187 | std::unique_ptr<PragmaHandler> MSVtorDisp; |
188 | std::unique_ptr<PragmaHandler> MSInitSeg; |
189 | std::unique_ptr<PragmaHandler> MSDataSeg; |
190 | std::unique_ptr<PragmaHandler> MSBSSSeg; |
191 | std::unique_ptr<PragmaHandler> MSConstSeg; |
192 | std::unique_ptr<PragmaHandler> MSCodeSeg; |
193 | std::unique_ptr<PragmaHandler> MSSection; |
194 | std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck; |
195 | std::unique_ptr<PragmaHandler> MSRuntimeChecks; |
196 | std::unique_ptr<PragmaHandler> MSIntrinsic; |
197 | std::unique_ptr<PragmaHandler> MSFunction; |
198 | std::unique_ptr<PragmaHandler> MSOptimize; |
199 | std::unique_ptr<PragmaHandler> MSFenvAccess; |
200 | std::unique_ptr<PragmaHandler> MSAllocText; |
201 | std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; |
202 | std::unique_ptr<PragmaHandler> OptimizeHandler; |
203 | std::unique_ptr<PragmaHandler> LoopHintHandler; |
204 | std::unique_ptr<PragmaHandler> UnrollHintHandler; |
205 | std::unique_ptr<PragmaHandler> NoUnrollHintHandler; |
206 | std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; |
207 | std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; |
208 | std::unique_ptr<PragmaHandler> FPHandler; |
209 | std::unique_ptr<PragmaHandler> STDCFenvAccessHandler; |
210 | std::unique_ptr<PragmaHandler> STDCFenvRoundHandler; |
211 | std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; |
212 | std::unique_ptr<PragmaHandler> STDCUnknownHandler; |
213 | std::unique_ptr<PragmaHandler> AttributePragmaHandler; |
214 | std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; |
215 | std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; |
216 | std::unique_ptr<PragmaHandler> RISCVPragmaHandler; |
217 | |
218 | std::unique_ptr<CommentHandler> CommentSemaHandler; |
219 | |
220 | /// Whether the '>' token acts as an operator or not. This will be |
221 | /// true except when we are parsing an expression within a C++ |
222 | /// template argument list, where the '>' closes the template |
223 | /// argument list. |
224 | bool GreaterThanIsOperator; |
225 | |
226 | /// ColonIsSacred - When this is false, we aggressively try to recover from |
227 | /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not |
228 | /// safe in case statements and a few other things. This is managed by the |
229 | /// ColonProtectionRAIIObject RAII object. |
230 | bool ColonIsSacred; |
231 | |
232 | /// Parsing OpenMP directive mode. |
233 | bool OpenMPDirectiveParsing = false; |
234 | |
235 | /// Parsing OpenACC directive mode. |
236 | bool OpenACCDirectiveParsing = false; |
237 | |
238 | /// Currently parsing a situation where an OpenACC array section could be |
239 | /// legal, such as a 'var-list'. |
240 | bool AllowOpenACCArraySections = false; |
241 | |
242 | /// RAII object to set reset OpenACC parsing a context where Array Sections |
243 | /// are allowed. |
244 | class OpenACCArraySectionRAII { |
245 | Parser &P; |
246 | |
247 | public: |
248 | OpenACCArraySectionRAII(Parser &P) : P(P) { |
249 | assert(!P.AllowOpenACCArraySections); |
250 | P.AllowOpenACCArraySections = true; |
251 | } |
252 | ~OpenACCArraySectionRAII() { |
253 | assert(P.AllowOpenACCArraySections); |
254 | P.AllowOpenACCArraySections = false; |
255 | } |
256 | }; |
257 | |
258 | /// When true, we are directly inside an Objective-C message |
259 | /// send expression. |
260 | /// |
261 | /// This is managed by the \c InMessageExpressionRAIIObject class, and |
262 | /// should not be set directly. |
263 | bool InMessageExpression; |
264 | |
265 | /// Gets set to true after calling ProduceSignatureHelp, it is for a |
266 | /// workaround to make sure ProduceSignatureHelp is only called at the deepest |
267 | /// function call. |
268 | bool CalledSignatureHelp = false; |
269 | |
270 | Sema::OffsetOfKind OffsetOfState = Sema::OffsetOfKind::OOK_Outside; |
271 | |
272 | /// The "depth" of the template parameters currently being parsed. |
273 | unsigned TemplateParameterDepth; |
274 | |
275 | /// Current kind of OpenMP clause |
276 | OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown; |
277 | |
278 | /// RAII class that manages the template parameter depth. |
279 | class TemplateParameterDepthRAII { |
280 | unsigned &Depth; |
281 | unsigned AddedLevels; |
282 | public: |
283 | explicit TemplateParameterDepthRAII(unsigned &Depth) |
284 | : Depth(Depth), AddedLevels(0) {} |
285 | |
286 | ~TemplateParameterDepthRAII() { |
287 | Depth -= AddedLevels; |
288 | } |
289 | |
290 | void operator++() { |
291 | ++Depth; |
292 | ++AddedLevels; |
293 | } |
294 | void addDepth(unsigned D) { |
295 | Depth += D; |
296 | AddedLevels += D; |
297 | } |
298 | void setAddedDepth(unsigned D) { |
299 | Depth = Depth - AddedLevels + D; |
300 | AddedLevels = D; |
301 | } |
302 | |
303 | unsigned getDepth() const { return Depth; } |
304 | unsigned getOriginalDepth() const { return Depth - AddedLevels; } |
305 | }; |
306 | |
307 | /// Factory object for creating ParsedAttr objects. |
308 | AttributeFactory AttrFactory; |
309 | |
310 | /// Gathers and cleans up TemplateIdAnnotations when parsing of a |
311 | /// top-level declaration is finished. |
312 | SmallVector<TemplateIdAnnotation *, 16> TemplateIds; |
313 | |
314 | void MaybeDestroyTemplateIds() { |
315 | if (!TemplateIds.empty() && |
316 | (Tok.is(K: tok::eof) || !PP.mightHavePendingAnnotationTokens())) |
317 | DestroyTemplateIds(); |
318 | } |
319 | void DestroyTemplateIds(); |
320 | |
321 | /// RAII object to destroy TemplateIdAnnotations where possible, from a |
322 | /// likely-good position during parsing. |
323 | struct DestroyTemplateIdAnnotationsRAIIObj { |
324 | Parser &Self; |
325 | |
326 | DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} |
327 | ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } |
328 | }; |
329 | |
330 | /// Identifiers which have been declared within a tentative parse. |
331 | SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; |
332 | |
333 | /// Tracker for '<' tokens that might have been intended to be treated as an |
334 | /// angle bracket instead of a less-than comparison. |
335 | /// |
336 | /// This happens when the user intends to form a template-id, but typoes the |
337 | /// template-name or forgets a 'template' keyword for a dependent template |
338 | /// name. |
339 | /// |
340 | /// We track these locations from the point where we see a '<' with a |
341 | /// name-like expression on its left until we see a '>' or '>>' that might |
342 | /// match it. |
343 | struct AngleBracketTracker { |
344 | /// Flags used to rank candidate template names when there is more than one |
345 | /// '<' in a scope. |
346 | enum Priority : unsigned short { |
347 | /// A non-dependent name that is a potential typo for a template name. |
348 | PotentialTypo = 0x0, |
349 | /// A dependent name that might instantiate to a template-name. |
350 | DependentName = 0x2, |
351 | |
352 | /// A space appears before the '<' token. |
353 | SpaceBeforeLess = 0x0, |
354 | /// No space before the '<' token |
355 | NoSpaceBeforeLess = 0x1, |
356 | |
357 | LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) |
358 | }; |
359 | |
360 | struct Loc { |
361 | Expr *TemplateName; |
362 | SourceLocation LessLoc; |
363 | AngleBracketTracker::Priority Priority; |
364 | unsigned short ParenCount, BracketCount, BraceCount; |
365 | |
366 | bool isActive(Parser &P) const { |
367 | return P.ParenCount == ParenCount && P.BracketCount == BracketCount && |
368 | P.BraceCount == BraceCount; |
369 | } |
370 | |
371 | bool isActiveOrNested(Parser &P) const { |
372 | return isActive(P) || P.ParenCount > ParenCount || |
373 | P.BracketCount > BracketCount || P.BraceCount > BraceCount; |
374 | } |
375 | }; |
376 | |
377 | SmallVector<Loc, 8> Locs; |
378 | |
379 | /// Add an expression that might have been intended to be a template name. |
380 | /// In the case of ambiguity, we arbitrarily select the innermost such |
381 | /// expression, for example in 'foo < bar < baz', 'bar' is the current |
382 | /// candidate. No attempt is made to track that 'foo' is also a candidate |
383 | /// for the case where we see a second suspicious '>' token. |
384 | void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, |
385 | Priority Prio) { |
386 | if (!Locs.empty() && Locs.back().isActive(P)) { |
387 | if (Locs.back().Priority <= Prio) { |
388 | Locs.back().TemplateName = TemplateName; |
389 | Locs.back().LessLoc = LessLoc; |
390 | Locs.back().Priority = Prio; |
391 | } |
392 | } else { |
393 | Locs.push_back(Elt: {.TemplateName: TemplateName, .LessLoc: LessLoc, .Priority: Prio, |
394 | .ParenCount: P.ParenCount, .BracketCount: P.BracketCount, .BraceCount: P.BraceCount}); |
395 | } |
396 | } |
397 | |
398 | /// Mark the current potential missing template location as having been |
399 | /// handled (this happens if we pass a "corresponding" '>' or '>>' token |
400 | /// or leave a bracket scope). |
401 | void clear(Parser &P) { |
402 | while (!Locs.empty() && Locs.back().isActiveOrNested(P)) |
403 | Locs.pop_back(); |
404 | } |
405 | |
406 | /// Get the current enclosing expression that might hve been intended to be |
407 | /// a template name. |
408 | Loc *getCurrent(Parser &P) { |
409 | if (!Locs.empty() && Locs.back().isActive(P)) |
410 | return &Locs.back(); |
411 | return nullptr; |
412 | } |
413 | }; |
414 | |
415 | AngleBracketTracker AngleBrackets; |
416 | |
417 | IdentifierInfo *getSEHExceptKeyword(); |
418 | |
419 | /// True if we are within an Objective-C container while parsing C-like decls. |
420 | /// |
421 | /// This is necessary because Sema thinks we have left the container |
422 | /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will |
423 | /// be NULL. |
424 | bool ParsingInObjCContainer; |
425 | |
426 | /// Whether to skip parsing of function bodies. |
427 | /// |
428 | /// This option can be used, for example, to speed up searches for |
429 | /// declarations/definitions when indexing. |
430 | bool SkipFunctionBodies; |
431 | |
432 | /// The location of the expression statement that is being parsed right now. |
433 | /// Used to determine if an expression that is being parsed is a statement or |
434 | /// just a regular sub-expression. |
435 | SourceLocation ExprStatementTokLoc; |
436 | |
437 | /// Flags describing a context in which we're parsing a statement. |
438 | enum class ParsedStmtContext { |
439 | /// This context permits standalone OpenMP directives. |
440 | AllowStandaloneOpenMPDirectives = 0x1, |
441 | /// This context is at the top level of a GNU statement expression. |
442 | InStmtExpr = 0x2, |
443 | |
444 | /// The context of a regular substatement. |
445 | SubStmt = 0, |
446 | /// The context of a compound-statement. |
447 | Compound = AllowStandaloneOpenMPDirectives, |
448 | |
449 | LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) |
450 | }; |
451 | |
452 | /// Act on an expression statement that might be the last statement in a |
453 | /// GNU statement expression. Checks whether we are actually at the end of |
454 | /// a statement expression and builds a suitable expression statement. |
455 | StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); |
456 | |
457 | public: |
458 | Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); |
459 | ~Parser() override; |
460 | |
461 | const LangOptions &getLangOpts() const { return PP.getLangOpts(); } |
462 | const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } |
463 | Preprocessor &getPreprocessor() const { return PP; } |
464 | Sema &getActions() const { return Actions; } |
465 | AttributeFactory &getAttrFactory() { return AttrFactory; } |
466 | |
467 | const Token &getCurToken() const { return Tok; } |
468 | Scope *getCurScope() const { return Actions.getCurScope(); } |
469 | void incrementMSManglingNumber() const { |
470 | return Actions.incrementMSManglingNumber(); |
471 | } |
472 | |
473 | ObjCContainerDecl *getObjCDeclContext() const { |
474 | return Actions.getObjCDeclContext(); |
475 | } |
476 | |
477 | // Type forwarding. All of these are statically 'void*', but they may all be |
478 | // different actual classes based on the actions in place. |
479 | typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; |
480 | typedef OpaquePtr<TemplateName> TemplateTy; |
481 | |
482 | typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; |
483 | |
484 | typedef Sema::FullExprArg FullExprArg; |
485 | |
486 | /// A SmallVector of statements. |
487 | typedef SmallVector<Stmt *, 32> StmtVector; |
488 | |
489 | // Parsing methods. |
490 | |
491 | /// Initialize - Warm up the parser. |
492 | /// |
493 | void Initialize(); |
494 | |
495 | /// Parse the first top-level declaration in a translation unit. |
496 | bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, |
497 | Sema::ModuleImportState &ImportState); |
498 | |
499 | /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if |
500 | /// the EOF was encountered. |
501 | bool ParseTopLevelDecl(DeclGroupPtrTy &Result, |
502 | Sema::ModuleImportState &ImportState); |
503 | bool ParseTopLevelDecl() { |
504 | DeclGroupPtrTy Result; |
505 | Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module; |
506 | return ParseTopLevelDecl(Result, ImportState&: IS); |
507 | } |
508 | |
509 | /// ConsumeToken - Consume the current 'peek token' and lex the next one. |
510 | /// This does not work with special tokens: string literals, code completion, |
511 | /// annotation tokens and balanced tokens must be handled using the specific |
512 | /// consume methods. |
513 | /// Returns the location of the consumed token. |
514 | SourceLocation ConsumeToken() { |
515 | assert(!isTokenSpecial() && |
516 | "Should consume special tokens with Consume*Token" ); |
517 | PrevTokLocation = Tok.getLocation(); |
518 | PP.Lex(Result&: Tok); |
519 | return PrevTokLocation; |
520 | } |
521 | |
522 | bool TryConsumeToken(tok::TokenKind Expected) { |
523 | if (Tok.isNot(K: Expected)) |
524 | return false; |
525 | assert(!isTokenSpecial() && |
526 | "Should consume special tokens with Consume*Token" ); |
527 | PrevTokLocation = Tok.getLocation(); |
528 | PP.Lex(Result&: Tok); |
529 | return true; |
530 | } |
531 | |
532 | bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { |
533 | if (!TryConsumeToken(Expected)) |
534 | return false; |
535 | Loc = PrevTokLocation; |
536 | return true; |
537 | } |
538 | |
539 | /// ConsumeAnyToken - Dispatch to the right Consume* method based on the |
540 | /// current token type. This should only be used in cases where the type of |
541 | /// the token really isn't known, e.g. in error recovery. |
542 | SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { |
543 | if (isTokenParen()) |
544 | return ConsumeParen(); |
545 | if (isTokenBracket()) |
546 | return ConsumeBracket(); |
547 | if (isTokenBrace()) |
548 | return ConsumeBrace(); |
549 | if (isTokenStringLiteral()) |
550 | return ConsumeStringToken(); |
551 | if (Tok.is(K: tok::code_completion)) |
552 | return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() |
553 | : handleUnexpectedCodeCompletionToken(); |
554 | if (Tok.isAnnotation()) |
555 | return ConsumeAnnotationToken(); |
556 | return ConsumeToken(); |
557 | } |
558 | |
559 | |
560 | SourceLocation getEndOfPreviousToken() { |
561 | return PP.getLocForEndOfToken(Loc: PrevTokLocation); |
562 | } |
563 | |
564 | /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds |
565 | /// to the given nullability kind. |
566 | IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { |
567 | return Actions.getNullabilityKeyword(nullability); |
568 | } |
569 | |
570 | private: |
571 | //===--------------------------------------------------------------------===// |
572 | // Low-Level token peeking and consumption methods. |
573 | // |
574 | |
575 | /// isTokenParen - Return true if the cur token is '(' or ')'. |
576 | bool isTokenParen() const { |
577 | return Tok.isOneOf(K1: tok::l_paren, K2: tok::r_paren); |
578 | } |
579 | /// isTokenBracket - Return true if the cur token is '[' or ']'. |
580 | bool isTokenBracket() const { |
581 | return Tok.isOneOf(K1: tok::l_square, K2: tok::r_square); |
582 | } |
583 | /// isTokenBrace - Return true if the cur token is '{' or '}'. |
584 | bool isTokenBrace() const { |
585 | return Tok.isOneOf(K1: tok::l_brace, K2: tok::r_brace); |
586 | } |
587 | /// isTokenStringLiteral - True if this token is a string-literal. |
588 | bool isTokenStringLiteral() const { |
589 | return tok::isStringLiteral(K: Tok.getKind()); |
590 | } |
591 | /// isTokenSpecial - True if this token requires special consumption methods. |
592 | bool isTokenSpecial() const { |
593 | return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || |
594 | isTokenBrace() || Tok.is(K: tok::code_completion) || Tok.isAnnotation(); |
595 | } |
596 | |
597 | /// Returns true if the current token is '=' or is a type of '='. |
598 | /// For typos, give a fixit to '=' |
599 | bool isTokenEqualOrEqualTypo(); |
600 | |
601 | /// Return the current token to the token stream and make the given |
602 | /// token the current token. |
603 | void UnconsumeToken(Token &Consumed) { |
604 | Token Next = Tok; |
605 | PP.EnterToken(Tok: Consumed, /*IsReinject*/IsReinject: true); |
606 | PP.Lex(Result&: Tok); |
607 | PP.EnterToken(Tok: Next, /*IsReinject*/IsReinject: true); |
608 | } |
609 | |
610 | SourceLocation ConsumeAnnotationToken() { |
611 | assert(Tok.isAnnotation() && "wrong consume method" ); |
612 | SourceLocation Loc = Tok.getLocation(); |
613 | PrevTokLocation = Tok.getAnnotationEndLoc(); |
614 | PP.Lex(Result&: Tok); |
615 | return Loc; |
616 | } |
617 | |
618 | /// ConsumeParen - This consume method keeps the paren count up-to-date. |
619 | /// |
620 | SourceLocation ConsumeParen() { |
621 | assert(isTokenParen() && "wrong consume method" ); |
622 | if (Tok.getKind() == tok::l_paren) |
623 | ++ParenCount; |
624 | else if (ParenCount) { |
625 | AngleBrackets.clear(P&: *this); |
626 | --ParenCount; // Don't let unbalanced )'s drive the count negative. |
627 | } |
628 | PrevTokLocation = Tok.getLocation(); |
629 | PP.Lex(Result&: Tok); |
630 | return PrevTokLocation; |
631 | } |
632 | |
633 | /// ConsumeBracket - This consume method keeps the bracket count up-to-date. |
634 | /// |
635 | SourceLocation ConsumeBracket() { |
636 | assert(isTokenBracket() && "wrong consume method" ); |
637 | if (Tok.getKind() == tok::l_square) |
638 | ++BracketCount; |
639 | else if (BracketCount) { |
640 | AngleBrackets.clear(P&: *this); |
641 | --BracketCount; // Don't let unbalanced ]'s drive the count negative. |
642 | } |
643 | |
644 | PrevTokLocation = Tok.getLocation(); |
645 | PP.Lex(Result&: Tok); |
646 | return PrevTokLocation; |
647 | } |
648 | |
649 | /// ConsumeBrace - This consume method keeps the brace count up-to-date. |
650 | /// |
651 | SourceLocation ConsumeBrace() { |
652 | assert(isTokenBrace() && "wrong consume method" ); |
653 | if (Tok.getKind() == tok::l_brace) |
654 | ++BraceCount; |
655 | else if (BraceCount) { |
656 | AngleBrackets.clear(P&: *this); |
657 | --BraceCount; // Don't let unbalanced }'s drive the count negative. |
658 | } |
659 | |
660 | PrevTokLocation = Tok.getLocation(); |
661 | PP.Lex(Result&: Tok); |
662 | return PrevTokLocation; |
663 | } |
664 | |
665 | /// ConsumeStringToken - Consume the current 'peek token', lexing a new one |
666 | /// and returning the token kind. This method is specific to strings, as it |
667 | /// handles string literal concatenation, as per C99 5.1.1.2, translation |
668 | /// phase #6. |
669 | SourceLocation ConsumeStringToken() { |
670 | assert(isTokenStringLiteral() && |
671 | "Should only consume string literals with this method" ); |
672 | PrevTokLocation = Tok.getLocation(); |
673 | PP.Lex(Result&: Tok); |
674 | return PrevTokLocation; |
675 | } |
676 | |
677 | /// Consume the current code-completion token. |
678 | /// |
679 | /// This routine can be called to consume the code-completion token and |
680 | /// continue processing in special cases where \c cutOffParsing() isn't |
681 | /// desired, such as token caching or completion with lookahead. |
682 | SourceLocation ConsumeCodeCompletionToken() { |
683 | assert(Tok.is(tok::code_completion)); |
684 | PrevTokLocation = Tok.getLocation(); |
685 | PP.Lex(Result&: Tok); |
686 | return PrevTokLocation; |
687 | } |
688 | |
689 | /// When we are consuming a code-completion token without having matched |
690 | /// specific position in the grammar, provide code-completion results based |
691 | /// on context. |
692 | /// |
693 | /// \returns the source location of the code-completion token. |
694 | SourceLocation handleUnexpectedCodeCompletionToken(); |
695 | |
696 | /// Abruptly cut off parsing; mainly used when we have reached the |
697 | /// code-completion point. |
698 | void cutOffParsing() { |
699 | if (PP.isCodeCompletionEnabled()) |
700 | PP.setCodeCompletionReached(); |
701 | // Cut off parsing by acting as if we reached the end-of-file. |
702 | Tok.setKind(tok::eof); |
703 | } |
704 | |
705 | /// Determine if we're at the end of the file or at a transition |
706 | /// between modules. |
707 | bool isEofOrEom() { |
708 | tok::TokenKind Kind = Tok.getKind(); |
709 | return Kind == tok::eof || Kind == tok::annot_module_begin || |
710 | Kind == tok::annot_module_end || Kind == tok::annot_module_include || |
711 | Kind == tok::annot_repl_input_end; |
712 | } |
713 | |
714 | /// Checks if the \p Level is valid for use in a fold expression. |
715 | bool isFoldOperator(prec::Level Level) const; |
716 | |
717 | /// Checks if the \p Kind is a valid operator for fold expressions. |
718 | bool isFoldOperator(tok::TokenKind Kind) const; |
719 | |
720 | /// Initialize all pragma handlers. |
721 | void initializePragmaHandlers(); |
722 | |
723 | /// Destroy and reset all pragma handlers. |
724 | void resetPragmaHandlers(); |
725 | |
726 | /// Handle the annotation token produced for #pragma unused(...) |
727 | void HandlePragmaUnused(); |
728 | |
729 | /// Handle the annotation token produced for |
730 | /// #pragma GCC visibility... |
731 | void HandlePragmaVisibility(); |
732 | |
733 | /// Handle the annotation token produced for |
734 | /// #pragma pack... |
735 | void HandlePragmaPack(); |
736 | |
737 | /// Handle the annotation token produced for |
738 | /// #pragma ms_struct... |
739 | void HandlePragmaMSStruct(); |
740 | |
741 | void HandlePragmaMSPointersToMembers(); |
742 | |
743 | void HandlePragmaMSVtorDisp(); |
744 | |
745 | void HandlePragmaMSPragma(); |
746 | bool HandlePragmaMSSection(StringRef PragmaName, |
747 | SourceLocation PragmaLocation); |
748 | bool HandlePragmaMSSegment(StringRef PragmaName, |
749 | SourceLocation PragmaLocation); |
750 | bool HandlePragmaMSInitSeg(StringRef PragmaName, |
751 | SourceLocation PragmaLocation); |
752 | bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName, |
753 | SourceLocation PragmaLocation); |
754 | bool HandlePragmaMSFunction(StringRef PragmaName, |
755 | SourceLocation PragmaLocation); |
756 | bool HandlePragmaMSAllocText(StringRef PragmaName, |
757 | SourceLocation PragmaLocation); |
758 | bool HandlePragmaMSOptimize(StringRef PragmaName, |
759 | SourceLocation PragmaLocation); |
760 | |
761 | /// Handle the annotation token produced for |
762 | /// #pragma align... |
763 | void HandlePragmaAlign(); |
764 | |
765 | /// Handle the annotation token produced for |
766 | /// #pragma clang __debug dump... |
767 | void HandlePragmaDump(); |
768 | |
769 | /// Handle the annotation token produced for |
770 | /// #pragma weak id... |
771 | void HandlePragmaWeak(); |
772 | |
773 | /// Handle the annotation token produced for |
774 | /// #pragma weak id = id... |
775 | void HandlePragmaWeakAlias(); |
776 | |
777 | /// Handle the annotation token produced for |
778 | /// #pragma redefine_extname... |
779 | void HandlePragmaRedefineExtname(); |
780 | |
781 | /// Handle the annotation token produced for |
782 | /// #pragma STDC FP_CONTRACT... |
783 | void HandlePragmaFPContract(); |
784 | |
785 | /// Handle the annotation token produced for |
786 | /// #pragma STDC FENV_ACCESS... |
787 | void HandlePragmaFEnvAccess(); |
788 | |
789 | /// Handle the annotation token produced for |
790 | /// #pragma STDC FENV_ROUND... |
791 | void HandlePragmaFEnvRound(); |
792 | |
793 | /// Handle the annotation token produced for |
794 | /// #pragma STDC CX_LIMITED_RANGE... |
795 | void HandlePragmaCXLimitedRange(); |
796 | |
797 | /// Handle the annotation token produced for |
798 | /// #pragma float_control |
799 | void HandlePragmaFloatControl(); |
800 | |
801 | /// \brief Handle the annotation token produced for |
802 | /// #pragma clang fp ... |
803 | void HandlePragmaFP(); |
804 | |
805 | /// Handle the annotation token produced for |
806 | /// #pragma OPENCL EXTENSION... |
807 | void HandlePragmaOpenCLExtension(); |
808 | |
809 | /// Handle the annotation token produced for |
810 | /// #pragma clang __debug captured |
811 | StmtResult HandlePragmaCaptured(); |
812 | |
813 | /// Handle the annotation token produced for |
814 | /// #pragma clang loop and #pragma unroll. |
815 | bool HandlePragmaLoopHint(LoopHint &Hint); |
816 | |
817 | bool ParsePragmaAttributeSubjectMatchRuleSet( |
818 | attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, |
819 | SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); |
820 | |
821 | void HandlePragmaAttribute(); |
822 | |
823 | /// GetLookAheadToken - This peeks ahead N tokens and returns that token |
824 | /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) |
825 | /// returns the token after Tok, etc. |
826 | /// |
827 | /// Note that this differs from the Preprocessor's LookAhead method, because |
828 | /// the Parser always has one token lexed that the preprocessor doesn't. |
829 | /// |
830 | const Token &GetLookAheadToken(unsigned N) { |
831 | if (N == 0 || Tok.is(K: tok::eof)) return Tok; |
832 | return PP.LookAhead(N: N-1); |
833 | } |
834 | |
835 | public: |
836 | /// NextToken - This peeks ahead one token and returns it without |
837 | /// consuming it. |
838 | const Token &NextToken() { |
839 | return PP.LookAhead(N: 0); |
840 | } |
841 | |
842 | /// getTypeAnnotation - Read a parsed type out of an annotation token. |
843 | static TypeResult getTypeAnnotation(const Token &Tok) { |
844 | if (!Tok.getAnnotationValue()) |
845 | return TypeError(); |
846 | return ParsedType::getFromOpaquePtr(P: Tok.getAnnotationValue()); |
847 | } |
848 | |
849 | private: |
850 | static void setTypeAnnotation(Token &Tok, TypeResult T) { |
851 | assert((T.isInvalid() || T.get()) && |
852 | "produced a valid-but-null type annotation?" ); |
853 | Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); |
854 | } |
855 | |
856 | static NamedDecl *getNonTypeAnnotation(const Token &Tok) { |
857 | return static_cast<NamedDecl*>(Tok.getAnnotationValue()); |
858 | } |
859 | |
860 | static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { |
861 | Tok.setAnnotationValue(ND); |
862 | } |
863 | |
864 | static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { |
865 | return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); |
866 | } |
867 | |
868 | static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { |
869 | Tok.setAnnotationValue(ND); |
870 | } |
871 | |
872 | /// Read an already-translated primary expression out of an annotation |
873 | /// token. |
874 | static ExprResult getExprAnnotation(const Token &Tok) { |
875 | return ExprResult::getFromOpaquePointer(P: Tok.getAnnotationValue()); |
876 | } |
877 | |
878 | /// Set the primary expression corresponding to the given annotation |
879 | /// token. |
880 | static void setExprAnnotation(Token &Tok, ExprResult ER) { |
881 | Tok.setAnnotationValue(ER.getAsOpaquePointer()); |
882 | } |
883 | |
884 | public: |
885 | // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to |
886 | // find a type name by attempting typo correction. |
887 | bool |
888 | TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename = |
889 | ImplicitTypenameContext::No); |
890 | bool TryAnnotateTypeOrScopeTokenAfterScopeSpec( |
891 | CXXScopeSpec &SS, bool IsNewScope, |
892 | ImplicitTypenameContext AllowImplicitTypename); |
893 | bool TryAnnotateCXXScopeToken(bool EnteringContext = false); |
894 | |
895 | bool MightBeCXXScopeToken() { |
896 | return getLangOpts().CPlusPlus && |
897 | (Tok.is(K: tok::identifier) || Tok.is(K: tok::coloncolon) || |
898 | (Tok.is(K: tok::annot_template_id) && |
899 | NextToken().is(K: tok::coloncolon)) || |
900 | Tok.is(K: tok::kw_decltype) || Tok.is(K: tok::kw___super)); |
901 | } |
902 | bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { |
903 | return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); |
904 | } |
905 | |
906 | private: |
907 | enum AnnotatedNameKind { |
908 | /// Annotation has failed and emitted an error. |
909 | ANK_Error, |
910 | /// The identifier is a tentatively-declared name. |
911 | ANK_TentativeDecl, |
912 | /// The identifier is a template name. FIXME: Add an annotation for that. |
913 | ANK_TemplateName, |
914 | /// The identifier can't be resolved. |
915 | ANK_Unresolved, |
916 | /// Annotation was successful. |
917 | ANK_Success |
918 | }; |
919 | |
920 | AnnotatedNameKind |
921 | TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr, |
922 | ImplicitTypenameContext AllowImplicitTypename = |
923 | ImplicitTypenameContext::No); |
924 | |
925 | /// Push a tok::annot_cxxscope token onto the token stream. |
926 | void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); |
927 | |
928 | /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, |
929 | /// replacing them with the non-context-sensitive keywords. This returns |
930 | /// true if the token was replaced. |
931 | bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, |
932 | const char *&PrevSpec, unsigned &DiagID, |
933 | bool &isInvalid) { |
934 | if (!getLangOpts().AltiVec && !getLangOpts().ZVector) |
935 | return false; |
936 | |
937 | if (Tok.getIdentifierInfo() != Ident_vector && |
938 | Tok.getIdentifierInfo() != Ident_bool && |
939 | Tok.getIdentifierInfo() != Ident_Bool && |
940 | (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) |
941 | return false; |
942 | |
943 | return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); |
944 | } |
945 | |
946 | /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector |
947 | /// identifier token, replacing it with the non-context-sensitive __vector. |
948 | /// This returns true if the token was replaced. |
949 | bool TryAltiVecVectorToken() { |
950 | if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || |
951 | Tok.getIdentifierInfo() != Ident_vector) return false; |
952 | return TryAltiVecVectorTokenOutOfLine(); |
953 | } |
954 | |
955 | bool TryAltiVecVectorTokenOutOfLine(); |
956 | bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, |
957 | const char *&PrevSpec, unsigned &DiagID, |
958 | bool &isInvalid); |
959 | |
960 | /// Returns true if the current token is the identifier 'instancetype'. |
961 | /// |
962 | /// Should only be used in Objective-C language modes. |
963 | bool isObjCInstancetype() { |
964 | assert(getLangOpts().ObjC); |
965 | if (Tok.isAnnotation()) |
966 | return false; |
967 | if (!Ident_instancetype) |
968 | Ident_instancetype = PP.getIdentifierInfo(Name: "instancetype" ); |
969 | return Tok.getIdentifierInfo() == Ident_instancetype; |
970 | } |
971 | |
972 | /// TryKeywordIdentFallback - For compatibility with system headers using |
973 | /// keywords as identifiers, attempt to convert the current token to an |
974 | /// identifier and optionally disable the keyword for the remainder of the |
975 | /// translation unit. This returns false if the token was not replaced, |
976 | /// otherwise emits a diagnostic and returns true. |
977 | bool TryKeywordIdentFallback(bool DisableKeyword); |
978 | |
979 | /// Get the TemplateIdAnnotation from the token. |
980 | TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); |
981 | |
982 | /// TentativeParsingAction - An object that is used as a kind of "tentative |
983 | /// parsing transaction". It gets instantiated to mark the token position and |
984 | /// after the token consumption is done, Commit() or Revert() is called to |
985 | /// either "commit the consumed tokens" or revert to the previously marked |
986 | /// token position. Example: |
987 | /// |
988 | /// TentativeParsingAction TPA(*this); |
989 | /// ConsumeToken(); |
990 | /// .... |
991 | /// TPA.Revert(); |
992 | /// |
993 | class TentativeParsingAction { |
994 | Parser &P; |
995 | PreferredTypeBuilder PrevPreferredType; |
996 | Token PrevTok; |
997 | size_t PrevTentativelyDeclaredIdentifierCount; |
998 | unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; |
999 | bool isActive; |
1000 | |
1001 | public: |
1002 | explicit TentativeParsingAction(Parser &p) |
1003 | : P(p), PrevPreferredType(P.PreferredType) { |
1004 | PrevTok = P.Tok; |
1005 | PrevTentativelyDeclaredIdentifierCount = |
1006 | P.TentativelyDeclaredIdentifiers.size(); |
1007 | PrevParenCount = P.ParenCount; |
1008 | PrevBracketCount = P.BracketCount; |
1009 | PrevBraceCount = P.BraceCount; |
1010 | P.PP.EnableBacktrackAtThisPos(); |
1011 | isActive = true; |
1012 | } |
1013 | void Commit() { |
1014 | assert(isActive && "Parsing action was finished!" ); |
1015 | P.TentativelyDeclaredIdentifiers.resize( |
1016 | N: PrevTentativelyDeclaredIdentifierCount); |
1017 | P.PP.CommitBacktrackedTokens(); |
1018 | isActive = false; |
1019 | } |
1020 | void Revert() { |
1021 | assert(isActive && "Parsing action was finished!" ); |
1022 | P.PP.Backtrack(); |
1023 | P.PreferredType = PrevPreferredType; |
1024 | P.Tok = PrevTok; |
1025 | P.TentativelyDeclaredIdentifiers.resize( |
1026 | N: PrevTentativelyDeclaredIdentifierCount); |
1027 | P.ParenCount = PrevParenCount; |
1028 | P.BracketCount = PrevBracketCount; |
1029 | P.BraceCount = PrevBraceCount; |
1030 | isActive = false; |
1031 | } |
1032 | ~TentativeParsingAction() { |
1033 | assert(!isActive && "Forgot to call Commit or Revert!" ); |
1034 | } |
1035 | }; |
1036 | /// A TentativeParsingAction that automatically reverts in its destructor. |
1037 | /// Useful for disambiguation parses that will always be reverted. |
1038 | class RevertingTentativeParsingAction |
1039 | : private Parser::TentativeParsingAction { |
1040 | public: |
1041 | RevertingTentativeParsingAction(Parser &P) |
1042 | : Parser::TentativeParsingAction(P) {} |
1043 | ~RevertingTentativeParsingAction() { Revert(); } |
1044 | }; |
1045 | |
1046 | class UnannotatedTentativeParsingAction; |
1047 | |
1048 | /// ObjCDeclContextSwitch - An object used to switch context from |
1049 | /// an objective-c decl context to its enclosing decl context and |
1050 | /// back. |
1051 | class ObjCDeclContextSwitch { |
1052 | Parser &P; |
1053 | ObjCContainerDecl *DC; |
1054 | SaveAndRestore<bool> WithinObjCContainer; |
1055 | public: |
1056 | explicit ObjCDeclContextSwitch(Parser &p) |
1057 | : P(p), DC(p.getObjCDeclContext()), |
1058 | WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { |
1059 | if (DC) |
1060 | P.Actions.ActOnObjCTemporaryExitContainerContext(ObjCCtx: DC); |
1061 | } |
1062 | ~ObjCDeclContextSwitch() { |
1063 | if (DC) |
1064 | P.Actions.ActOnObjCReenterContainerContext(ObjCCtx: DC); |
1065 | } |
1066 | }; |
1067 | |
1068 | /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the |
1069 | /// input. If so, it is consumed and false is returned. |
1070 | /// |
1071 | /// If a trivial punctuator misspelling is encountered, a FixIt error |
1072 | /// diagnostic is issued and false is returned after recovery. |
1073 | /// |
1074 | /// If the input is malformed, this emits the specified diagnostic and true is |
1075 | /// returned. |
1076 | bool ExpectAndConsume(tok::TokenKind ExpectedTok, |
1077 | unsigned Diag = diag::err_expected, |
1078 | StringRef DiagMsg = "" ); |
1079 | |
1080 | /// The parser expects a semicolon and, if present, will consume it. |
1081 | /// |
1082 | /// If the next token is not a semicolon, this emits the specified diagnostic, |
1083 | /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior |
1084 | /// to the semicolon, consumes that extra token. |
1085 | bool ExpectAndConsumeSemi(unsigned DiagID , StringRef TokenUsed = "" ); |
1086 | |
1087 | /// The kind of extra semi diagnostic to emit. |
1088 | enum { |
1089 | OutsideFunction = 0, |
1090 | InsideStruct = 1, |
1091 | InstanceVariableList = 2, |
1092 | AfterMemberFunctionDefinition = 3 |
1093 | }; |
1094 | |
1095 | /// Consume any extra semi-colons until the end of the line. |
1096 | void (ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); |
1097 | |
1098 | /// Return false if the next token is an identifier. An 'expected identifier' |
1099 | /// error is emitted otherwise. |
1100 | /// |
1101 | /// The parser tries to recover from the error by checking if the next token |
1102 | /// is a C++ keyword when parsing Objective-C++. Return false if the recovery |
1103 | /// was successful. |
1104 | bool expectIdentifier(); |
1105 | |
1106 | /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens. |
1107 | enum class CompoundToken { |
1108 | /// A '(' '{' beginning a statement-expression. |
1109 | StmtExprBegin, |
1110 | /// A '}' ')' ending a statement-expression. |
1111 | StmtExprEnd, |
1112 | /// A '[' '[' beginning a C++11 or C23 attribute. |
1113 | AttrBegin, |
1114 | /// A ']' ']' ending a C++11 or C23 attribute. |
1115 | AttrEnd, |
1116 | /// A '::' '*' forming a C++ pointer-to-member declaration. |
1117 | MemberPtr, |
1118 | }; |
1119 | |
1120 | /// Check that a compound operator was written in a "sensible" way, and warn |
1121 | /// if not. |
1122 | void checkCompoundToken(SourceLocation FirstTokLoc, |
1123 | tok::TokenKind FirstTokKind, CompoundToken Op); |
1124 | |
1125 | public: |
1126 | //===--------------------------------------------------------------------===// |
1127 | // Scope manipulation |
1128 | |
1129 | /// ParseScope - Introduces a new scope for parsing. The kind of |
1130 | /// scope is determined by ScopeFlags. Objects of this type should |
1131 | /// be created on the stack to coincide with the position where the |
1132 | /// parser enters the new scope, and this object's constructor will |
1133 | /// create that new scope. Similarly, once the object is destroyed |
1134 | /// the parser will exit the scope. |
1135 | class ParseScope { |
1136 | Parser *Self; |
1137 | ParseScope(const ParseScope &) = delete; |
1138 | void operator=(const ParseScope &) = delete; |
1139 | |
1140 | public: |
1141 | // ParseScope - Construct a new object to manage a scope in the |
1142 | // parser Self where the new Scope is created with the flags |
1143 | // ScopeFlags, but only when we aren't about to enter a compound statement. |
1144 | ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, |
1145 | bool BeforeCompoundStmt = false) |
1146 | : Self(Self) { |
1147 | if (EnteredScope && !BeforeCompoundStmt) |
1148 | Self->EnterScope(ScopeFlags); |
1149 | else { |
1150 | if (BeforeCompoundStmt) |
1151 | Self->incrementMSManglingNumber(); |
1152 | |
1153 | this->Self = nullptr; |
1154 | } |
1155 | } |
1156 | |
1157 | // Exit - Exit the scope associated with this object now, rather |
1158 | // than waiting until the object is destroyed. |
1159 | void Exit() { |
1160 | if (Self) { |
1161 | Self->ExitScope(); |
1162 | Self = nullptr; |
1163 | } |
1164 | } |
1165 | |
1166 | ~ParseScope() { |
1167 | Exit(); |
1168 | } |
1169 | }; |
1170 | |
1171 | /// Introduces zero or more scopes for parsing. The scopes will all be exited |
1172 | /// when the object is destroyed. |
1173 | class MultiParseScope { |
1174 | Parser &Self; |
1175 | unsigned NumScopes = 0; |
1176 | |
1177 | MultiParseScope(const MultiParseScope&) = delete; |
1178 | |
1179 | public: |
1180 | MultiParseScope(Parser &Self) : Self(Self) {} |
1181 | void Enter(unsigned ScopeFlags) { |
1182 | Self.EnterScope(ScopeFlags); |
1183 | ++NumScopes; |
1184 | } |
1185 | void Exit() { |
1186 | while (NumScopes) { |
1187 | Self.ExitScope(); |
1188 | --NumScopes; |
1189 | } |
1190 | } |
1191 | ~MultiParseScope() { |
1192 | Exit(); |
1193 | } |
1194 | }; |
1195 | |
1196 | /// EnterScope - Start a new scope. |
1197 | void EnterScope(unsigned ScopeFlags); |
1198 | |
1199 | /// ExitScope - Pop a scope off the scope stack. |
1200 | void ExitScope(); |
1201 | |
1202 | /// Re-enter the template scopes for a declaration that might be a template. |
1203 | unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D); |
1204 | |
1205 | private: |
1206 | /// RAII object used to modify the scope flags for the current scope. |
1207 | class ParseScopeFlags { |
1208 | Scope *CurScope; |
1209 | unsigned OldFlags = 0; |
1210 | ParseScopeFlags(const ParseScopeFlags &) = delete; |
1211 | void operator=(const ParseScopeFlags &) = delete; |
1212 | |
1213 | public: |
1214 | ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); |
1215 | ~ParseScopeFlags(); |
1216 | }; |
1217 | |
1218 | //===--------------------------------------------------------------------===// |
1219 | // Diagnostic Emission and Error recovery. |
1220 | |
1221 | public: |
1222 | DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); |
1223 | DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); |
1224 | DiagnosticBuilder Diag(unsigned DiagID) { |
1225 | return Diag(Tok, DiagID); |
1226 | } |
1227 | |
1228 | private: |
1229 | void SuggestParentheses(SourceLocation Loc, unsigned DK, |
1230 | SourceRange ParenRange); |
1231 | void CheckNestedObjCContexts(SourceLocation AtLoc); |
1232 | |
1233 | public: |
1234 | |
1235 | /// Control flags for SkipUntil functions. |
1236 | enum SkipUntilFlags { |
1237 | StopAtSemi = 1 << 0, ///< Stop skipping at semicolon |
1238 | /// Stop skipping at specified token, but don't skip the token itself |
1239 | StopBeforeMatch = 1 << 1, |
1240 | StopAtCodeCompletion = 1 << 2 ///< Stop at code completion |
1241 | }; |
1242 | |
1243 | friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, |
1244 | SkipUntilFlags R) { |
1245 | return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | |
1246 | static_cast<unsigned>(R)); |
1247 | } |
1248 | |
1249 | /// SkipUntil - Read tokens until we get to the specified token, then consume |
1250 | /// it (unless StopBeforeMatch is specified). Because we cannot guarantee |
1251 | /// that the token will ever occur, this skips to the next token, or to some |
1252 | /// likely good stopping point. If Flags has StopAtSemi flag, skipping will |
1253 | /// stop at a ';' character. Balances (), [], and {} delimiter tokens while |
1254 | /// skipping. |
1255 | /// |
1256 | /// If SkipUntil finds the specified token, it returns true, otherwise it |
1257 | /// returns false. |
1258 | bool SkipUntil(tok::TokenKind T, |
1259 | SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { |
1260 | return SkipUntil(Toks: llvm::ArrayRef(T), Flags); |
1261 | } |
1262 | bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, |
1263 | SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { |
1264 | tok::TokenKind TokArray[] = {T1, T2}; |
1265 | return SkipUntil(Toks: TokArray, Flags); |
1266 | } |
1267 | bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, |
1268 | SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { |
1269 | tok::TokenKind TokArray[] = {T1, T2, T3}; |
1270 | return SkipUntil(Toks: TokArray, Flags); |
1271 | } |
1272 | bool SkipUntil(ArrayRef<tok::TokenKind> Toks, |
1273 | SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); |
1274 | |
1275 | /// SkipMalformedDecl - Read tokens until we get to some likely good stopping |
1276 | /// point for skipping past a simple-declaration. |
1277 | void SkipMalformedDecl(); |
1278 | |
1279 | /// The location of the first statement inside an else that might |
1280 | /// have a missleading indentation. If there is no |
1281 | /// MisleadingIndentationChecker on an else active, this location is invalid. |
1282 | SourceLocation MisleadingIndentationElseLoc; |
1283 | |
1284 | private: |
1285 | //===--------------------------------------------------------------------===// |
1286 | // Lexing and parsing of C++ inline methods. |
1287 | |
1288 | struct ParsingClass; |
1289 | |
1290 | /// [class.mem]p1: "... the class is regarded as complete within |
1291 | /// - function bodies |
1292 | /// - default arguments |
1293 | /// - exception-specifications (TODO: C++0x) |
1294 | /// - and brace-or-equal-initializers for non-static data members |
1295 | /// (including such things in nested classes)." |
1296 | /// LateParsedDeclarations build the tree of those elements so they can |
1297 | /// be parsed after parsing the top-level class. |
1298 | class LateParsedDeclaration { |
1299 | public: |
1300 | virtual ~LateParsedDeclaration(); |
1301 | |
1302 | virtual void ParseLexedMethodDeclarations(); |
1303 | virtual void ParseLexedMemberInitializers(); |
1304 | virtual void ParseLexedMethodDefs(); |
1305 | virtual void ParseLexedAttributes(); |
1306 | virtual void ParseLexedPragmas(); |
1307 | }; |
1308 | |
1309 | /// Inner node of the LateParsedDeclaration tree that parses |
1310 | /// all its members recursively. |
1311 | class LateParsedClass : public LateParsedDeclaration { |
1312 | public: |
1313 | LateParsedClass(Parser *P, ParsingClass *C); |
1314 | ~LateParsedClass() override; |
1315 | |
1316 | void ParseLexedMethodDeclarations() override; |
1317 | void ParseLexedMemberInitializers() override; |
1318 | void ParseLexedMethodDefs() override; |
1319 | void ParseLexedAttributes() override; |
1320 | void ParseLexedPragmas() override; |
1321 | |
1322 | private: |
1323 | Parser *Self; |
1324 | ParsingClass *Class; |
1325 | }; |
1326 | |
1327 | /// Contains the lexed tokens of an attribute with arguments that |
1328 | /// may reference member variables and so need to be parsed at the |
1329 | /// end of the class declaration after parsing all other member |
1330 | /// member declarations. |
1331 | /// FIXME: Perhaps we should change the name of LateParsedDeclaration to |
1332 | /// LateParsedTokens. |
1333 | struct LateParsedAttribute : public LateParsedDeclaration { |
1334 | Parser *Self; |
1335 | CachedTokens Toks; |
1336 | IdentifierInfo &AttrName; |
1337 | IdentifierInfo *MacroII = nullptr; |
1338 | SourceLocation AttrNameLoc; |
1339 | SmallVector<Decl*, 2> Decls; |
1340 | |
1341 | explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, |
1342 | SourceLocation Loc) |
1343 | : Self(P), AttrName(Name), AttrNameLoc(Loc) {} |
1344 | |
1345 | void ParseLexedAttributes() override; |
1346 | |
1347 | void addDecl(Decl *D) { Decls.push_back(Elt: D); } |
1348 | }; |
1349 | |
1350 | /// Contains the lexed tokens of a pragma with arguments that |
1351 | /// may reference member variables and so need to be parsed at the |
1352 | /// end of the class declaration after parsing all other member |
1353 | /// member declarations. |
1354 | class LateParsedPragma : public LateParsedDeclaration { |
1355 | Parser *Self = nullptr; |
1356 | AccessSpecifier AS = AS_none; |
1357 | CachedTokens Toks; |
1358 | |
1359 | public: |
1360 | explicit LateParsedPragma(Parser *P, AccessSpecifier AS) |
1361 | : Self(P), AS(AS) {} |
1362 | |
1363 | void takeToks(CachedTokens &Cached) { Toks.swap(RHS&: Cached); } |
1364 | const CachedTokens &toks() const { return Toks; } |
1365 | AccessSpecifier getAccessSpecifier() const { return AS; } |
1366 | |
1367 | void ParseLexedPragmas() override; |
1368 | }; |
1369 | |
1370 | // A list of late-parsed attributes. Used by ParseGNUAttributes. |
1371 | class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { |
1372 | public: |
1373 | LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } |
1374 | |
1375 | bool parseSoon() { return ParseSoon; } |
1376 | |
1377 | private: |
1378 | bool ParseSoon; // Are we planning to parse these shortly after creation? |
1379 | }; |
1380 | |
1381 | /// Contains the lexed tokens of a member function definition |
1382 | /// which needs to be parsed at the end of the class declaration |
1383 | /// after parsing all other member declarations. |
1384 | struct LexedMethod : public LateParsedDeclaration { |
1385 | Parser *Self; |
1386 | Decl *D; |
1387 | CachedTokens Toks; |
1388 | |
1389 | explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {} |
1390 | |
1391 | void ParseLexedMethodDefs() override; |
1392 | }; |
1393 | |
1394 | /// LateParsedDefaultArgument - Keeps track of a parameter that may |
1395 | /// have a default argument that cannot be parsed yet because it |
1396 | /// occurs within a member function declaration inside the class |
1397 | /// (C++ [class.mem]p2). |
1398 | struct LateParsedDefaultArgument { |
1399 | explicit LateParsedDefaultArgument(Decl *P, |
1400 | std::unique_ptr<CachedTokens> Toks = nullptr) |
1401 | : Param(P), Toks(std::move(Toks)) { } |
1402 | |
1403 | /// Param - The parameter declaration for this parameter. |
1404 | Decl *Param; |
1405 | |
1406 | /// Toks - The sequence of tokens that comprises the default |
1407 | /// argument expression, not including the '=' or the terminating |
1408 | /// ')' or ','. This will be NULL for parameters that have no |
1409 | /// default argument. |
1410 | std::unique_ptr<CachedTokens> Toks; |
1411 | }; |
1412 | |
1413 | /// LateParsedMethodDeclaration - A method declaration inside a class that |
1414 | /// contains at least one entity whose parsing needs to be delayed |
1415 | /// until the class itself is completely-defined, such as a default |
1416 | /// argument (C++ [class.mem]p2). |
1417 | struct LateParsedMethodDeclaration : public LateParsedDeclaration { |
1418 | explicit LateParsedMethodDeclaration(Parser *P, Decl *M) |
1419 | : Self(P), Method(M), ExceptionSpecTokens(nullptr) {} |
1420 | |
1421 | void ParseLexedMethodDeclarations() override; |
1422 | |
1423 | Parser *Self; |
1424 | |
1425 | /// Method - The method declaration. |
1426 | Decl *Method; |
1427 | |
1428 | /// DefaultArgs - Contains the parameters of the function and |
1429 | /// their default arguments. At least one of the parameters will |
1430 | /// have a default argument, but all of the parameters of the |
1431 | /// method will be stored so that they can be reintroduced into |
1432 | /// scope at the appropriate times. |
1433 | SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; |
1434 | |
1435 | /// The set of tokens that make up an exception-specification that |
1436 | /// has not yet been parsed. |
1437 | CachedTokens *ExceptionSpecTokens; |
1438 | }; |
1439 | |
1440 | /// LateParsedMemberInitializer - An initializer for a non-static class data |
1441 | /// member whose parsing must to be delayed until the class is completely |
1442 | /// defined (C++11 [class.mem]p2). |
1443 | struct LateParsedMemberInitializer : public LateParsedDeclaration { |
1444 | LateParsedMemberInitializer(Parser *P, Decl *FD) |
1445 | : Self(P), Field(FD) { } |
1446 | |
1447 | void ParseLexedMemberInitializers() override; |
1448 | |
1449 | Parser *Self; |
1450 | |
1451 | /// Field - The field declaration. |
1452 | Decl *Field; |
1453 | |
1454 | /// CachedTokens - The sequence of tokens that comprises the initializer, |
1455 | /// including any leading '='. |
1456 | CachedTokens Toks; |
1457 | }; |
1458 | |
1459 | /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) |
1460 | /// C++ class, its method declarations that contain parts that won't be |
1461 | /// parsed until after the definition is completed (C++ [class.mem]p2), |
1462 | /// the method declarations and possibly attached inline definitions |
1463 | /// will be stored here with the tokens that will be parsed to create those |
1464 | /// entities. |
1465 | typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; |
1466 | |
1467 | /// Representation of a class that has been parsed, including |
1468 | /// any member function declarations or definitions that need to be |
1469 | /// parsed after the corresponding top-level class is complete. |
1470 | struct ParsingClass { |
1471 | ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) |
1472 | : TopLevelClass(TopLevelClass), IsInterface(IsInterface), |
1473 | TagOrTemplate(TagOrTemplate) {} |
1474 | |
1475 | /// Whether this is a "top-level" class, meaning that it is |
1476 | /// not nested within another class. |
1477 | bool TopLevelClass : 1; |
1478 | |
1479 | /// Whether this class is an __interface. |
1480 | bool IsInterface : 1; |
1481 | |
1482 | /// The class or class template whose definition we are parsing. |
1483 | Decl *TagOrTemplate; |
1484 | |
1485 | /// LateParsedDeclarations - Method declarations, inline definitions and |
1486 | /// nested classes that contain pieces whose parsing will be delayed until |
1487 | /// the top-level class is fully defined. |
1488 | LateParsedDeclarationsContainer LateParsedDeclarations; |
1489 | }; |
1490 | |
1491 | /// The stack of classes that is currently being |
1492 | /// parsed. Nested and local classes will be pushed onto this stack |
1493 | /// when they are parsed, and removed afterward. |
1494 | std::stack<ParsingClass *> ClassStack; |
1495 | |
1496 | ParsingClass &getCurrentClass() { |
1497 | assert(!ClassStack.empty() && "No lexed method stacks!" ); |
1498 | return *ClassStack.top(); |
1499 | } |
1500 | |
1501 | /// RAII object used to manage the parsing of a class definition. |
1502 | class ParsingClassDefinition { |
1503 | Parser &P; |
1504 | bool Popped; |
1505 | Sema::ParsingClassState State; |
1506 | |
1507 | public: |
1508 | ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, |
1509 | bool IsInterface) |
1510 | : P(P), Popped(false), |
1511 | State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { |
1512 | } |
1513 | |
1514 | /// Pop this class of the stack. |
1515 | void Pop() { |
1516 | assert(!Popped && "Nested class has already been popped" ); |
1517 | Popped = true; |
1518 | P.PopParsingClass(State); |
1519 | } |
1520 | |
1521 | ~ParsingClassDefinition() { |
1522 | if (!Popped) |
1523 | P.PopParsingClass(State); |
1524 | } |
1525 | }; |
1526 | |
1527 | /// Contains information about any template-specific |
1528 | /// information that has been parsed prior to parsing declaration |
1529 | /// specifiers. |
1530 | struct ParsedTemplateInfo { |
1531 | ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr) {} |
1532 | |
1533 | ParsedTemplateInfo(TemplateParameterLists *TemplateParams, |
1534 | bool isSpecialization, |
1535 | bool lastParameterListWasEmpty = false) |
1536 | : Kind(isSpecialization? ExplicitSpecialization : Template), |
1537 | TemplateParams(TemplateParams), |
1538 | LastParameterListWasEmpty(lastParameterListWasEmpty) { } |
1539 | |
1540 | explicit ParsedTemplateInfo(SourceLocation ExternLoc, |
1541 | SourceLocation TemplateLoc) |
1542 | : Kind(ExplicitInstantiation), TemplateParams(nullptr), |
1543 | ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), |
1544 | LastParameterListWasEmpty(false){ } |
1545 | |
1546 | /// The kind of template we are parsing. |
1547 | enum { |
1548 | /// We are not parsing a template at all. |
1549 | NonTemplate = 0, |
1550 | /// We are parsing a template declaration. |
1551 | Template, |
1552 | /// We are parsing an explicit specialization. |
1553 | ExplicitSpecialization, |
1554 | /// We are parsing an explicit instantiation. |
1555 | ExplicitInstantiation |
1556 | } Kind; |
1557 | |
1558 | /// The template parameter lists, for template declarations |
1559 | /// and explicit specializations. |
1560 | TemplateParameterLists *TemplateParams; |
1561 | |
1562 | /// The location of the 'extern' keyword, if any, for an explicit |
1563 | /// instantiation |
1564 | SourceLocation ExternLoc; |
1565 | |
1566 | /// The location of the 'template' keyword, for an explicit |
1567 | /// instantiation. |
1568 | SourceLocation TemplateLoc; |
1569 | |
1570 | /// Whether the last template parameter list was empty. |
1571 | bool LastParameterListWasEmpty; |
1572 | |
1573 | SourceRange getSourceRange() const LLVM_READONLY; |
1574 | }; |
1575 | |
1576 | // In ParseCXXInlineMethods.cpp. |
1577 | struct ReenterTemplateScopeRAII; |
1578 | struct ReenterClassScopeRAII; |
1579 | |
1580 | void LexTemplateFunctionForLateParsing(CachedTokens &Toks); |
1581 | void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); |
1582 | |
1583 | static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); |
1584 | |
1585 | Sema::ParsingClassState |
1586 | PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); |
1587 | void DeallocateParsedClasses(ParsingClass *Class); |
1588 | void PopParsingClass(Sema::ParsingClassState); |
1589 | |
1590 | enum CachedInitKind { |
1591 | CIK_DefaultArgument, |
1592 | CIK_DefaultInitializer |
1593 | }; |
1594 | |
1595 | NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, |
1596 | const ParsedAttributesView &AccessAttrs, |
1597 | ParsingDeclarator &D, |
1598 | const ParsedTemplateInfo &TemplateInfo, |
1599 | const VirtSpecifiers &VS, |
1600 | SourceLocation PureSpecLoc); |
1601 | void ParseCXXNonStaticMemberInitializer(Decl *VarD); |
1602 | void ParseLexedAttributes(ParsingClass &Class); |
1603 | void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, |
1604 | bool EnterScope, bool OnDefinition); |
1605 | void ParseLexedAttribute(LateParsedAttribute &LA, |
1606 | bool EnterScope, bool OnDefinition); |
1607 | void ParseLexedMethodDeclarations(ParsingClass &Class); |
1608 | void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); |
1609 | void ParseLexedMethodDefs(ParsingClass &Class); |
1610 | void ParseLexedMethodDef(LexedMethod &LM); |
1611 | void ParseLexedMemberInitializers(ParsingClass &Class); |
1612 | void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); |
1613 | void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); |
1614 | void ParseLexedPragmas(ParsingClass &Class); |
1615 | void ParseLexedPragma(LateParsedPragma &LP); |
1616 | bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); |
1617 | bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); |
1618 | bool ConsumeAndStoreConditional(CachedTokens &Toks); |
1619 | bool ConsumeAndStoreUntil(tok::TokenKind T1, |
1620 | CachedTokens &Toks, |
1621 | bool StopAtSemi = true, |
1622 | bool ConsumeFinalToken = true) { |
1623 | return ConsumeAndStoreUntil(T1, T2: T1, Toks, StopAtSemi, ConsumeFinalToken); |
1624 | } |
1625 | bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, |
1626 | CachedTokens &Toks, |
1627 | bool StopAtSemi = true, |
1628 | bool ConsumeFinalToken = true); |
1629 | |
1630 | //===--------------------------------------------------------------------===// |
1631 | // C99 6.9: External Definitions. |
1632 | DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs, |
1633 | ParsedAttributes &DeclSpecAttrs, |
1634 | ParsingDeclSpec *DS = nullptr); |
1635 | bool isDeclarationAfterDeclarator(); |
1636 | bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); |
1637 | DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( |
1638 | ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs, |
1639 | ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); |
1640 | DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs, |
1641 | ParsedAttributes &DeclSpecAttrs, |
1642 | ParsingDeclSpec &DS, |
1643 | AccessSpecifier AS); |
1644 | |
1645 | void SkipFunctionBody(); |
1646 | Decl *ParseFunctionDefinition(ParsingDeclarator &D, |
1647 | const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), |
1648 | LateParsedAttrList *LateParsedAttrs = nullptr); |
1649 | void ParseKNRParamDeclarations(Declarator &D); |
1650 | // EndLoc is filled with the location of the last token of the simple-asm. |
1651 | ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); |
1652 | ExprResult ParseAsmStringLiteral(bool ForAsmLabel); |
1653 | |
1654 | // Objective-C External Declarations |
1655 | void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); |
1656 | DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs, |
1657 | ParsedAttributes &DeclSpecAttrs); |
1658 | DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); |
1659 | Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, |
1660 | ParsedAttributes &prefixAttrs); |
1661 | class ObjCTypeParamListScope; |
1662 | ObjCTypeParamList *parseObjCTypeParamList(); |
1663 | ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( |
1664 | ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, |
1665 | SmallVectorImpl<IdentifierLocPair> &protocolIdents, |
1666 | SourceLocation &rAngleLoc, bool mayBeProtocolList = true); |
1667 | |
1668 | void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl, |
1669 | SourceLocation atLoc, |
1670 | BalancedDelimiterTracker &T, |
1671 | SmallVectorImpl<Decl *> &AllIvarDecls, |
1672 | bool RBraceMissing); |
1673 | void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl, |
1674 | tok::ObjCKeywordKind visibility, |
1675 | SourceLocation atLoc); |
1676 | bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, |
1677 | SmallVectorImpl<SourceLocation> &PLocs, |
1678 | bool WarnOnDeclarations, |
1679 | bool ForObjCContainer, |
1680 | SourceLocation &LAngleLoc, |
1681 | SourceLocation &EndProtoLoc, |
1682 | bool consumeLastToken); |
1683 | |
1684 | /// Parse the first angle-bracket-delimited clause for an |
1685 | /// Objective-C object or object pointer type, which may be either |
1686 | /// type arguments or protocol qualifiers. |
1687 | void parseObjCTypeArgsOrProtocolQualifiers( |
1688 | ParsedType baseType, |
1689 | SourceLocation &typeArgsLAngleLoc, |
1690 | SmallVectorImpl<ParsedType> &typeArgs, |
1691 | SourceLocation &typeArgsRAngleLoc, |
1692 | SourceLocation &protocolLAngleLoc, |
1693 | SmallVectorImpl<Decl *> &protocols, |
1694 | SmallVectorImpl<SourceLocation> &protocolLocs, |
1695 | SourceLocation &protocolRAngleLoc, |
1696 | bool consumeLastToken, |
1697 | bool warnOnIncompleteProtocols); |
1698 | |
1699 | /// Parse either Objective-C type arguments or protocol qualifiers; if the |
1700 | /// former, also parse protocol qualifiers afterward. |
1701 | void parseObjCTypeArgsAndProtocolQualifiers( |
1702 | ParsedType baseType, |
1703 | SourceLocation &typeArgsLAngleLoc, |
1704 | SmallVectorImpl<ParsedType> &typeArgs, |
1705 | SourceLocation &typeArgsRAngleLoc, |
1706 | SourceLocation &protocolLAngleLoc, |
1707 | SmallVectorImpl<Decl *> &protocols, |
1708 | SmallVectorImpl<SourceLocation> &protocolLocs, |
1709 | SourceLocation &protocolRAngleLoc, |
1710 | bool consumeLastToken); |
1711 | |
1712 | /// Parse a protocol qualifier type such as '<NSCopying>', which is |
1713 | /// an anachronistic way of writing 'id<NSCopying>'. |
1714 | TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); |
1715 | |
1716 | /// Parse Objective-C type arguments and protocol qualifiers, extending the |
1717 | /// current type with the parsed result. |
1718 | TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, |
1719 | ParsedType type, |
1720 | bool consumeLastToken, |
1721 | SourceLocation &endLoc); |
1722 | |
1723 | void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, |
1724 | Decl *CDecl); |
1725 | DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, |
1726 | ParsedAttributes &prefixAttrs); |
1727 | |
1728 | struct ObjCImplParsingDataRAII { |
1729 | Parser &P; |
1730 | Decl *Dcl; |
1731 | bool HasCFunction; |
1732 | typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; |
1733 | LateParsedObjCMethodContainer LateParsedObjCMethods; |
1734 | |
1735 | ObjCImplParsingDataRAII(Parser &parser, Decl *D) |
1736 | : P(parser), Dcl(D), HasCFunction(false) { |
1737 | P.CurParsedObjCImpl = this; |
1738 | Finished = false; |
1739 | } |
1740 | ~ObjCImplParsingDataRAII(); |
1741 | |
1742 | void finish(SourceRange AtEnd); |
1743 | bool isFinished() const { return Finished; } |
1744 | |
1745 | private: |
1746 | bool Finished; |
1747 | }; |
1748 | ObjCImplParsingDataRAII *CurParsedObjCImpl; |
1749 | void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); |
1750 | |
1751 | DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, |
1752 | ParsedAttributes &Attrs); |
1753 | DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); |
1754 | Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); |
1755 | Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); |
1756 | Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); |
1757 | |
1758 | IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); |
1759 | // Definitions for Objective-c context sensitive keywords recognition. |
1760 | enum ObjCTypeQual { |
1761 | objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, |
1762 | objc_nonnull, objc_nullable, objc_null_unspecified, |
1763 | objc_NumQuals |
1764 | }; |
1765 | IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; |
1766 | |
1767 | bool isTokIdentifier_in() const; |
1768 | |
1769 | ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, |
1770 | ParsedAttributes *ParamAttrs); |
1771 | Decl *ParseObjCMethodPrototype( |
1772 | tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, |
1773 | bool MethodDefinition = true); |
1774 | Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, |
1775 | tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, |
1776 | bool MethodDefinition=true); |
1777 | void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); |
1778 | |
1779 | Decl *ParseObjCMethodDefinition(); |
1780 | |
1781 | public: |
1782 | //===--------------------------------------------------------------------===// |
1783 | // C99 6.5: Expressions. |
1784 | |
1785 | /// TypeCastState - State whether an expression is or may be a type cast. |
1786 | enum TypeCastState { |
1787 | NotTypeCast = 0, |
1788 | MaybeTypeCast, |
1789 | IsTypeCast |
1790 | }; |
1791 | |
1792 | ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); |
1793 | ExprResult ParseConstantExpressionInExprEvalContext( |
1794 | TypeCastState isTypeCast = NotTypeCast); |
1795 | ExprResult ParseConstantExpression(); |
1796 | ExprResult ParseArrayBoundExpression(); |
1797 | ExprResult ParseCaseExpression(SourceLocation CaseLoc); |
1798 | ExprResult ParseConstraintExpression(); |
1799 | ExprResult |
1800 | ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); |
1801 | ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); |
1802 | // Expr that doesn't include commas. |
1803 | ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); |
1804 | |
1805 | ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, |
1806 | unsigned &NumLineToksConsumed, |
1807 | bool IsUnevaluated); |
1808 | |
1809 | ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); |
1810 | ExprResult ParseUnevaluatedStringLiteralExpression(); |
1811 | |
1812 | private: |
1813 | ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral, |
1814 | bool Unevaluated); |
1815 | |
1816 | ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); |
1817 | |
1818 | ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); |
1819 | |
1820 | ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, |
1821 | prec::Level MinPrec); |
1822 | /// Control what ParseCastExpression will parse. |
1823 | enum CastParseKind { |
1824 | AnyCastExpr = 0, |
1825 | UnaryExprOnly, |
1826 | PrimaryExprOnly |
1827 | }; |
1828 | ExprResult ParseCastExpression(CastParseKind ParseKind, |
1829 | bool isAddressOfOperand, |
1830 | bool &NotCastExpr, |
1831 | TypeCastState isTypeCast, |
1832 | bool isVectorLiteral = false, |
1833 | bool *NotPrimaryExpression = nullptr); |
1834 | ExprResult ParseCastExpression(CastParseKind ParseKind, |
1835 | bool isAddressOfOperand = false, |
1836 | TypeCastState isTypeCast = NotTypeCast, |
1837 | bool isVectorLiteral = false, |
1838 | bool *NotPrimaryExpression = nullptr); |
1839 | |
1840 | /// Returns true if the next token cannot start an expression. |
1841 | bool isNotExpressionStart(); |
1842 | |
1843 | /// Returns true if the next token would start a postfix-expression |
1844 | /// suffix. |
1845 | bool isPostfixExpressionSuffixStart() { |
1846 | tok::TokenKind K = Tok.getKind(); |
1847 | return (K == tok::l_square || K == tok::l_paren || |
1848 | K == tok::period || K == tok::arrow || |
1849 | K == tok::plusplus || K == tok::minusminus); |
1850 | } |
1851 | |
1852 | bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); |
1853 | void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); |
1854 | bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, |
1855 | const Token &OpToken); |
1856 | bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { |
1857 | if (auto *Info = AngleBrackets.getCurrent(P&: *this)) |
1858 | return checkPotentialAngleBracketDelimiter(*Info, OpToken); |
1859 | return false; |
1860 | } |
1861 | |
1862 | ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); |
1863 | ExprResult ParseUnaryExprOrTypeTraitExpression(); |
1864 | ExprResult ParseBuiltinPrimaryExpression(); |
1865 | ExprResult ParseSYCLUniqueStableNameExpression(); |
1866 | |
1867 | ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, |
1868 | bool &isCastExpr, |
1869 | ParsedType &CastTy, |
1870 | SourceRange &CastRange); |
1871 | |
1872 | /// ParseExpressionList - Used for C/C++ (argument-)expression-list. |
1873 | bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, |
1874 | llvm::function_ref<void()> ExpressionStarts = |
1875 | llvm::function_ref<void()>(), |
1876 | bool FailImmediatelyOnInvalidExpr = false, |
1877 | bool EarlyTypoCorrection = false); |
1878 | |
1879 | /// ParseSimpleExpressionList - A simple comma-separated list of expressions, |
1880 | /// used for misc language extensions. |
1881 | bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs); |
1882 | |
1883 | /// ParenParseOption - Control what ParseParenExpression will parse. |
1884 | enum ParenParseOption { |
1885 | SimpleExpr, // Only parse '(' expression ')' |
1886 | FoldExpr, // Also allow fold-expression <anything> |
1887 | CompoundStmt, // Also allow '(' compound-statement ')' |
1888 | CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' |
1889 | CastExpr // Also allow '(' type-name ')' <anything> |
1890 | }; |
1891 | ExprResult ParseParenExpression(ParenParseOption &ExprType, |
1892 | bool stopIfCastExpr, |
1893 | bool isTypeCast, |
1894 | ParsedType &CastTy, |
1895 | SourceLocation &RParenLoc); |
1896 | |
1897 | ExprResult ParseCXXAmbiguousParenExpression( |
1898 | ParenParseOption &ExprType, ParsedType &CastTy, |
1899 | BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); |
1900 | ExprResult ParseCompoundLiteralExpression(ParsedType Ty, |
1901 | SourceLocation LParenLoc, |
1902 | SourceLocation RParenLoc); |
1903 | |
1904 | ExprResult ParseGenericSelectionExpression(); |
1905 | |
1906 | ExprResult ParseObjCBoolLiteral(); |
1907 | |
1908 | ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); |
1909 | |
1910 | //===--------------------------------------------------------------------===// |
1911 | // C++ Expressions |
1912 | ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, |
1913 | Token &Replacement); |
1914 | |
1915 | ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression); |
1916 | ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression); |
1917 | |
1918 | ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); |
1919 | |
1920 | bool areTokensAdjacent(const Token &A, const Token &B); |
1921 | |
1922 | void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, |
1923 | bool EnteringContext, IdentifierInfo &II, |
1924 | CXXScopeSpec &SS); |
1925 | |
1926 | bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, |
1927 | ParsedType ObjectType, |
1928 | bool ObjectHasErrors, |
1929 | bool EnteringContext, |
1930 | bool *MayBePseudoDestructor = nullptr, |
1931 | bool IsTypename = false, |
1932 | IdentifierInfo **LastII = nullptr, |
1933 | bool OnlyNamespace = false, |
1934 | bool InUsingDeclaration = false); |
1935 | |
1936 | //===--------------------------------------------------------------------===// |
1937 | // C++11 5.1.2: Lambda expressions |
1938 | |
1939 | /// Result of tentatively parsing a lambda-introducer. |
1940 | enum class LambdaIntroducerTentativeParse { |
1941 | /// This appears to be a lambda-introducer, which has been fully parsed. |
1942 | Success, |
1943 | /// This is a lambda-introducer, but has not been fully parsed, and this |
1944 | /// function needs to be called again to parse it. |
1945 | Incomplete, |
1946 | /// This is definitely an Objective-C message send expression, rather than |
1947 | /// a lambda-introducer, attribute-specifier, or array designator. |
1948 | MessageSend, |
1949 | /// This is not a lambda-introducer. |
1950 | Invalid, |
1951 | }; |
1952 | |
1953 | // [...] () -> type {...} |
1954 | ExprResult ParseLambdaExpression(); |
1955 | ExprResult TryParseLambdaExpression(); |
1956 | bool |
1957 | ParseLambdaIntroducer(LambdaIntroducer &Intro, |
1958 | LambdaIntroducerTentativeParse *Tentative = nullptr); |
1959 | ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); |
1960 | |
1961 | //===--------------------------------------------------------------------===// |
1962 | // C++ 5.2p1: C++ Casts |
1963 | ExprResult ParseCXXCasts(); |
1964 | |
1965 | /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. |
1966 | ExprResult ParseBuiltinBitCast(); |
1967 | |
1968 | //===--------------------------------------------------------------------===// |
1969 | // C++ 5.2p1: C++ Type Identification |
1970 | ExprResult ParseCXXTypeid(); |
1971 | |
1972 | //===--------------------------------------------------------------------===// |
1973 | // C++ : Microsoft __uuidof Expression |
1974 | ExprResult ParseCXXUuidof(); |
1975 | |
1976 | //===--------------------------------------------------------------------===// |
1977 | // C++ 5.2.4: C++ Pseudo-Destructor Expressions |
1978 | ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, |
1979 | tok::TokenKind OpKind, |
1980 | CXXScopeSpec &SS, |
1981 | ParsedType ObjectType); |
1982 | |
1983 | //===--------------------------------------------------------------------===// |
1984 | // C++ 9.3.2: C++ 'this' pointer |
1985 | ExprResult ParseCXXThis(); |
1986 | |
1987 | //===--------------------------------------------------------------------===// |
1988 | // C++ 15: C++ Throw Expression |
1989 | ExprResult ParseThrowExpression(); |
1990 | |
1991 | ExceptionSpecificationType tryParseExceptionSpecification( |
1992 | bool Delayed, |
1993 | SourceRange &SpecificationRange, |
1994 | SmallVectorImpl<ParsedType> &DynamicExceptions, |
1995 | SmallVectorImpl<SourceRange> &DynamicExceptionRanges, |
1996 | ExprResult &NoexceptExpr, |
1997 | CachedTokens *&ExceptionSpecTokens); |
1998 | |
1999 | // EndLoc is filled with the location of the last token of the specification. |
2000 | ExceptionSpecificationType ParseDynamicExceptionSpecification( |
2001 | SourceRange &SpecificationRange, |
2002 | SmallVectorImpl<ParsedType> &Exceptions, |
2003 | SmallVectorImpl<SourceRange> &Ranges); |
2004 | |
2005 | //===--------------------------------------------------------------------===// |
2006 | // C++0x 8: Function declaration trailing-return-type |
2007 | TypeResult ParseTrailingReturnType(SourceRange &Range, |
2008 | bool MayBeFollowedByDirectInit); |
2009 | |
2010 | //===--------------------------------------------------------------------===// |
2011 | // C++ 2.13.5: C++ Boolean Literals |
2012 | ExprResult ParseCXXBoolLiteral(); |
2013 | |
2014 | //===--------------------------------------------------------------------===// |
2015 | // C++ 5.2.3: Explicit type conversion (functional notation) |
2016 | ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); |
2017 | |
2018 | /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. |
2019 | /// This should only be called when the current token is known to be part of |
2020 | /// simple-type-specifier. |
2021 | void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); |
2022 | |
2023 | bool ParseCXXTypeSpecifierSeq( |
2024 | DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName); |
2025 | |
2026 | //===--------------------------------------------------------------------===// |
2027 | // C++ 5.3.4 and 5.3.5: C++ new and delete |
2028 | bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, |
2029 | Declarator &D); |
2030 | void ParseDirectNewDeclarator(Declarator &D); |
2031 | ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); |
2032 | ExprResult ParseCXXDeleteExpression(bool UseGlobal, |
2033 | SourceLocation Start); |
2034 | |
2035 | //===--------------------------------------------------------------------===// |
2036 | // C++ if/switch/while/for condition expression. |
2037 | struct ForRangeInfo; |
2038 | Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, |
2039 | SourceLocation Loc, |
2040 | Sema::ConditionKind CK, |
2041 | bool MissingOK, |
2042 | ForRangeInfo *FRI = nullptr, |
2043 | bool EnterForConditionScope = false); |
2044 | DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context, |
2045 | ParsedAttributes &Attrs); |
2046 | |
2047 | //===--------------------------------------------------------------------===// |
2048 | // C++ Coroutines |
2049 | |
2050 | ExprResult ParseCoyieldExpression(); |
2051 | |
2052 | //===--------------------------------------------------------------------===// |
2053 | // C++ Concepts |
2054 | |
2055 | ExprResult ParseRequiresExpression(); |
2056 | void ParseTrailingRequiresClause(Declarator &D); |
2057 | |
2058 | //===--------------------------------------------------------------------===// |
2059 | // C99 6.7.8: Initialization. |
2060 | |
2061 | /// ParseInitializer |
2062 | /// initializer: [C99 6.7.8] |
2063 | /// assignment-expression |
2064 | /// '{' ... |
2065 | ExprResult ParseInitializer() { |
2066 | if (Tok.isNot(K: tok::l_brace)) |
2067 | return ParseAssignmentExpression(); |
2068 | return ParseBraceInitializer(); |
2069 | } |
2070 | bool MayBeDesignationStart(); |
2071 | ExprResult ParseBraceInitializer(); |
2072 | struct DesignatorCompletionInfo { |
2073 | SmallVectorImpl<Expr *> &InitExprs; |
2074 | QualType PreferredBaseType; |
2075 | }; |
2076 | ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo); |
2077 | |
2078 | //===--------------------------------------------------------------------===// |
2079 | // clang Expressions |
2080 | |
2081 | ExprResult ParseBlockLiteralExpression(); // ^{...} |
2082 | |
2083 | //===--------------------------------------------------------------------===// |
2084 | // Objective-C Expressions |
2085 | ExprResult ParseObjCAtExpression(SourceLocation AtLocation); |
2086 | ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); |
2087 | ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); |
2088 | ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); |
2089 | ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); |
2090 | ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); |
2091 | ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); |
2092 | ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); |
2093 | ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); |
2094 | ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); |
2095 | ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); |
2096 | bool isSimpleObjCMessageExpression(); |
2097 | ExprResult ParseObjCMessageExpression(); |
2098 | ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, |
2099 | SourceLocation SuperLoc, |
2100 | ParsedType ReceiverType, |
2101 | Expr *ReceiverExpr); |
2102 | ExprResult ParseAssignmentExprWithObjCMessageExprStart( |
2103 | SourceLocation LBracloc, SourceLocation SuperLoc, |
2104 | ParsedType ReceiverType, Expr *ReceiverExpr); |
2105 | bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); |
2106 | |
2107 | //===--------------------------------------------------------------------===// |
2108 | // C99 6.8: Statements and Blocks. |
2109 | |
2110 | /// A SmallVector of expressions. |
2111 | typedef SmallVector<Expr*, 12> ExprVector; |
2112 | |
2113 | StmtResult |
2114 | ParseStatement(SourceLocation *TrailingElseLoc = nullptr, |
2115 | ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); |
2116 | StmtResult ParseStatementOrDeclaration( |
2117 | StmtVector &Stmts, ParsedStmtContext StmtCtx, |
2118 | SourceLocation *TrailingElseLoc = nullptr); |
2119 | StmtResult ParseStatementOrDeclarationAfterAttributes( |
2120 | StmtVector &Stmts, ParsedStmtContext StmtCtx, |
2121 | SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs, |
2122 | ParsedAttributes &DeclSpecAttrs); |
2123 | StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); |
2124 | StmtResult ParseLabeledStatement(ParsedAttributes &Attrs, |
2125 | ParsedStmtContext StmtCtx); |
2126 | StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, |
2127 | bool MissingCase = false, |
2128 | ExprResult Expr = ExprResult()); |
2129 | StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); |
2130 | StmtResult ParseCompoundStatement(bool isStmtExpr = false); |
2131 | StmtResult ParseCompoundStatement(bool isStmtExpr, |
2132 | unsigned ScopeFlags); |
2133 | void ParseCompoundStatementLeadingPragmas(); |
2134 | void DiagnoseLabelAtEndOfCompoundStatement(); |
2135 | bool (StmtVector &Stmts); |
2136 | StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); |
2137 | bool ParseParenExprOrCondition(StmtResult *InitStmt, |
2138 | Sema::ConditionResult &CondResult, |
2139 | SourceLocation Loc, Sema::ConditionKind CK, |
2140 | SourceLocation &LParenLoc, |
2141 | SourceLocation &RParenLoc); |
2142 | StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); |
2143 | StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); |
2144 | StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); |
2145 | StmtResult ParseDoStatement(); |
2146 | StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); |
2147 | StmtResult ParseGotoStatement(); |
2148 | StmtResult ParseContinueStatement(); |
2149 | StmtResult ParseBreakStatement(); |
2150 | StmtResult ParseReturnStatement(); |
2151 | StmtResult ParseAsmStatement(bool &msAsm); |
2152 | StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); |
2153 | StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, |
2154 | SourceLocation *TrailingElseLoc, |
2155 | ParsedAttributes &Attrs); |
2156 | |
2157 | /// Describes the behavior that should be taken for an __if_exists |
2158 | /// block. |
2159 | enum IfExistsBehavior { |
2160 | /// Parse the block; this code is always used. |
2161 | IEB_Parse, |
2162 | /// Skip the block entirely; this code is never used. |
2163 | IEB_Skip, |
2164 | /// Parse the block as a dependent block, which may be used in |
2165 | /// some template instantiations but not others. |
2166 | IEB_Dependent |
2167 | }; |
2168 | |
2169 | /// Describes the condition of a Microsoft __if_exists or |
2170 | /// __if_not_exists block. |
2171 | struct IfExistsCondition { |
2172 | /// The location of the initial keyword. |
2173 | SourceLocation KeywordLoc; |
2174 | /// Whether this is an __if_exists block (rather than an |
2175 | /// __if_not_exists block). |
2176 | bool IsIfExists; |
2177 | |
2178 | /// Nested-name-specifier preceding the name. |
2179 | CXXScopeSpec SS; |
2180 | |
2181 | /// The name we're looking for. |
2182 | UnqualifiedId Name; |
2183 | |
2184 | /// The behavior of this __if_exists or __if_not_exists block |
2185 | /// should. |
2186 | IfExistsBehavior Behavior; |
2187 | }; |
2188 | |
2189 | bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); |
2190 | void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); |
2191 | void ParseMicrosoftIfExistsExternalDeclaration(); |
2192 | void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, |
2193 | ParsedAttributes &AccessAttrs, |
2194 | AccessSpecifier &CurAS); |
2195 | bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, |
2196 | bool &InitExprsOk); |
2197 | bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, |
2198 | SmallVectorImpl<Expr *> &Constraints, |
2199 | SmallVectorImpl<Expr *> &Exprs); |
2200 | |
2201 | //===--------------------------------------------------------------------===// |
2202 | // C++ 6: Statements and Blocks |
2203 | |
2204 | StmtResult ParseCXXTryBlock(); |
2205 | StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); |
2206 | StmtResult ParseCXXCatchBlock(bool FnCatch = false); |
2207 | |
2208 | //===--------------------------------------------------------------------===// |
2209 | // MS: SEH Statements and Blocks |
2210 | |
2211 | StmtResult ParseSEHTryBlock(); |
2212 | StmtResult ParseSEHExceptBlock(SourceLocation Loc); |
2213 | StmtResult ParseSEHFinallyBlock(SourceLocation Loc); |
2214 | StmtResult ParseSEHLeaveStatement(); |
2215 | |
2216 | //===--------------------------------------------------------------------===// |
2217 | // Objective-C Statements |
2218 | |
2219 | StmtResult ParseObjCAtStatement(SourceLocation atLoc, |
2220 | ParsedStmtContext StmtCtx); |
2221 | StmtResult ParseObjCTryStmt(SourceLocation atLoc); |
2222 | StmtResult ParseObjCThrowStmt(SourceLocation atLoc); |
2223 | StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); |
2224 | StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); |
2225 | |
2226 | |
2227 | //===--------------------------------------------------------------------===// |
2228 | // C99 6.7: Declarations. |
2229 | |
2230 | /// A context for parsing declaration specifiers. TODO: flesh this |
2231 | /// out, there are other significant restrictions on specifiers than |
2232 | /// would be best implemented in the parser. |
2233 | enum class DeclSpecContext { |
2234 | DSC_normal, // normal context |
2235 | DSC_class, // class context, enables 'friend' |
2236 | DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list |
2237 | DSC_trailing, // C++11 trailing-type-specifier in a trailing return type |
2238 | DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration |
2239 | DSC_conv_operator, // C++ type-specifier-seq in an conversion operator |
2240 | DSC_top_level, // top-level/namespace declaration context |
2241 | DSC_template_param, // template parameter context |
2242 | DSC_template_arg, // template argument context |
2243 | DSC_template_type_arg, // template type argument context |
2244 | DSC_objc_method_result, // ObjC method result context, enables |
2245 | // 'instancetype' |
2246 | DSC_condition, // condition declaration context |
2247 | DSC_association, // A _Generic selection expression's type association |
2248 | DSC_new, // C++ new expression |
2249 | }; |
2250 | |
2251 | /// Is this a context in which we are parsing just a type-specifier (or |
2252 | /// trailing-type-specifier)? |
2253 | static bool isTypeSpecifier(DeclSpecContext DSC) { |
2254 | switch (DSC) { |
2255 | case DeclSpecContext::DSC_normal: |
2256 | case DeclSpecContext::DSC_template_param: |
2257 | case DeclSpecContext::DSC_template_arg: |
2258 | case DeclSpecContext::DSC_class: |
2259 | case DeclSpecContext::DSC_top_level: |
2260 | case DeclSpecContext::DSC_objc_method_result: |
2261 | case DeclSpecContext::DSC_condition: |
2262 | return false; |
2263 | |
2264 | case DeclSpecContext::DSC_template_type_arg: |
2265 | case DeclSpecContext::DSC_type_specifier: |
2266 | case DeclSpecContext::DSC_conv_operator: |
2267 | case DeclSpecContext::DSC_trailing: |
2268 | case DeclSpecContext::DSC_alias_declaration: |
2269 | case DeclSpecContext::DSC_association: |
2270 | case DeclSpecContext::DSC_new: |
2271 | return true; |
2272 | } |
2273 | llvm_unreachable("Missing DeclSpecContext case" ); |
2274 | } |
2275 | |
2276 | /// Whether a defining-type-specifier is permitted in a given context. |
2277 | enum class AllowDefiningTypeSpec { |
2278 | /// The grammar doesn't allow a defining-type-specifier here, and we must |
2279 | /// not parse one (eg, because a '{' could mean something else). |
2280 | No, |
2281 | /// The grammar doesn't allow a defining-type-specifier here, but we permit |
2282 | /// one for error recovery purposes. Sema will reject. |
2283 | NoButErrorRecovery, |
2284 | /// The grammar allows a defining-type-specifier here, even though it's |
2285 | /// always invalid. Sema will reject. |
2286 | YesButInvalid, |
2287 | /// The grammar allows a defining-type-specifier here, and one can be valid. |
2288 | Yes |
2289 | }; |
2290 | |
2291 | /// Is this a context in which we are parsing defining-type-specifiers (and |
2292 | /// so permit class and enum definitions in addition to non-defining class and |
2293 | /// enum elaborated-type-specifiers)? |
2294 | static AllowDefiningTypeSpec |
2295 | isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) { |
2296 | switch (DSC) { |
2297 | case DeclSpecContext::DSC_normal: |
2298 | case DeclSpecContext::DSC_class: |
2299 | case DeclSpecContext::DSC_top_level: |
2300 | case DeclSpecContext::DSC_alias_declaration: |
2301 | case DeclSpecContext::DSC_objc_method_result: |
2302 | return AllowDefiningTypeSpec::Yes; |
2303 | |
2304 | case DeclSpecContext::DSC_condition: |
2305 | case DeclSpecContext::DSC_template_param: |
2306 | return AllowDefiningTypeSpec::YesButInvalid; |
2307 | |
2308 | case DeclSpecContext::DSC_template_type_arg: |
2309 | case DeclSpecContext::DSC_type_specifier: |
2310 | return AllowDefiningTypeSpec::NoButErrorRecovery; |
2311 | |
2312 | case DeclSpecContext::DSC_association: |
2313 | return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery |
2314 | : AllowDefiningTypeSpec::Yes; |
2315 | |
2316 | case DeclSpecContext::DSC_trailing: |
2317 | case DeclSpecContext::DSC_conv_operator: |
2318 | case DeclSpecContext::DSC_template_arg: |
2319 | case DeclSpecContext::DSC_new: |
2320 | return AllowDefiningTypeSpec::No; |
2321 | } |
2322 | llvm_unreachable("Missing DeclSpecContext case" ); |
2323 | } |
2324 | |
2325 | /// Is this a context in which an opaque-enum-declaration can appear? |
2326 | static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { |
2327 | switch (DSC) { |
2328 | case DeclSpecContext::DSC_normal: |
2329 | case DeclSpecContext::DSC_class: |
2330 | case DeclSpecContext::DSC_top_level: |
2331 | return true; |
2332 | |
2333 | case DeclSpecContext::DSC_alias_declaration: |
2334 | case DeclSpecContext::DSC_objc_method_result: |
2335 | case DeclSpecContext::DSC_condition: |
2336 | case DeclSpecContext::DSC_template_param: |
2337 | case DeclSpecContext::DSC_template_type_arg: |
2338 | case DeclSpecContext::DSC_type_specifier: |
2339 | case DeclSpecContext::DSC_trailing: |
2340 | case DeclSpecContext::DSC_association: |
2341 | case DeclSpecContext::DSC_conv_operator: |
2342 | case DeclSpecContext::DSC_template_arg: |
2343 | case DeclSpecContext::DSC_new: |
2344 | |
2345 | return false; |
2346 | } |
2347 | llvm_unreachable("Missing DeclSpecContext case" ); |
2348 | } |
2349 | |
2350 | /// Is this a context in which we can perform class template argument |
2351 | /// deduction? |
2352 | static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { |
2353 | switch (DSC) { |
2354 | case DeclSpecContext::DSC_normal: |
2355 | case DeclSpecContext::DSC_template_param: |
2356 | case DeclSpecContext::DSC_template_arg: |
2357 | case DeclSpecContext::DSC_class: |
2358 | case DeclSpecContext::DSC_top_level: |
2359 | case DeclSpecContext::DSC_condition: |
2360 | case DeclSpecContext::DSC_type_specifier: |
2361 | case DeclSpecContext::DSC_association: |
2362 | case DeclSpecContext::DSC_conv_operator: |
2363 | case DeclSpecContext::DSC_new: |
2364 | return true; |
2365 | |
2366 | case DeclSpecContext::DSC_objc_method_result: |
2367 | case DeclSpecContext::DSC_template_type_arg: |
2368 | case DeclSpecContext::DSC_trailing: |
2369 | case DeclSpecContext::DSC_alias_declaration: |
2370 | return false; |
2371 | } |
2372 | llvm_unreachable("Missing DeclSpecContext case" ); |
2373 | } |
2374 | |
2375 | // Is this a context in which an implicit 'typename' is allowed? |
2376 | static ImplicitTypenameContext |
2377 | getImplicitTypenameContext(DeclSpecContext DSC) { |
2378 | switch (DSC) { |
2379 | case DeclSpecContext::DSC_class: |
2380 | case DeclSpecContext::DSC_top_level: |
2381 | case DeclSpecContext::DSC_type_specifier: |
2382 | case DeclSpecContext::DSC_template_type_arg: |
2383 | case DeclSpecContext::DSC_trailing: |
2384 | case DeclSpecContext::DSC_alias_declaration: |
2385 | case DeclSpecContext::DSC_template_param: |
2386 | case DeclSpecContext::DSC_new: |
2387 | return ImplicitTypenameContext::Yes; |
2388 | |
2389 | case DeclSpecContext::DSC_normal: |
2390 | case DeclSpecContext::DSC_objc_method_result: |
2391 | case DeclSpecContext::DSC_condition: |
2392 | case DeclSpecContext::DSC_template_arg: |
2393 | case DeclSpecContext::DSC_conv_operator: |
2394 | case DeclSpecContext::DSC_association: |
2395 | return ImplicitTypenameContext::No; |
2396 | } |
2397 | llvm_unreachable("Missing DeclSpecContext case" ); |
2398 | } |
2399 | |
2400 | /// Information on a C++0x for-range-initializer found while parsing a |
2401 | /// declaration which turns out to be a for-range-declaration. |
2402 | struct ForRangeInit { |
2403 | SourceLocation ColonLoc; |
2404 | ExprResult RangeExpr; |
2405 | SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps; |
2406 | bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } |
2407 | }; |
2408 | struct ForRangeInfo : ForRangeInit { |
2409 | StmtResult LoopVar; |
2410 | }; |
2411 | |
2412 | DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, |
2413 | SourceLocation &DeclEnd, |
2414 | ParsedAttributes &DeclAttrs, |
2415 | ParsedAttributes &DeclSpecAttrs, |
2416 | SourceLocation *DeclSpecStart = nullptr); |
2417 | DeclGroupPtrTy |
2418 | ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, |
2419 | ParsedAttributes &DeclAttrs, |
2420 | ParsedAttributes &DeclSpecAttrs, bool RequireSemi, |
2421 | ForRangeInit *FRI = nullptr, |
2422 | SourceLocation *DeclSpecStart = nullptr); |
2423 | bool MightBeDeclarator(DeclaratorContext Context); |
2424 | DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, |
2425 | ParsedAttributes &Attrs, |
2426 | ParsedTemplateInfo &TemplateInfo, |
2427 | SourceLocation *DeclEnd = nullptr, |
2428 | ForRangeInit *FRI = nullptr); |
2429 | Decl *ParseDeclarationAfterDeclarator(Declarator &D, |
2430 | const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); |
2431 | bool ParseAsmAttributesAfterDeclarator(Declarator &D); |
2432 | Decl *ParseDeclarationAfterDeclaratorAndAttributes( |
2433 | Declarator &D, |
2434 | const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), |
2435 | ForRangeInit *FRI = nullptr); |
2436 | Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); |
2437 | Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); |
2438 | |
2439 | /// When in code-completion, skip parsing of the function/method body |
2440 | /// unless the body contains the code-completion point. |
2441 | /// |
2442 | /// \returns true if the function body was skipped. |
2443 | bool trySkippingFunctionBody(); |
2444 | |
2445 | bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, |
2446 | const ParsedTemplateInfo &TemplateInfo, |
2447 | AccessSpecifier AS, DeclSpecContext DSC, |
2448 | ParsedAttributes &Attrs); |
2449 | DeclSpecContext |
2450 | getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); |
2451 | void ParseDeclarationSpecifiers( |
2452 | DeclSpec &DS, |
2453 | const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), |
2454 | AccessSpecifier AS = AS_none, |
2455 | DeclSpecContext DSC = DeclSpecContext::DSC_normal, |
2456 | LateParsedAttrList *LateAttrs = nullptr) { |
2457 | return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs, |
2458 | AllowImplicitTypename: getImplicitTypenameContext(DSC)); |
2459 | } |
2460 | void ParseDeclarationSpecifiers( |
2461 | DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, |
2462 | DeclSpecContext DSC, LateParsedAttrList *LateAttrs, |
2463 | ImplicitTypenameContext AllowImplicitTypename); |
2464 | |
2465 | SourceLocation ParsePackIndexingType(DeclSpec &DS); |
2466 | void AnnotateExistingIndexedTypeNamePack(ParsedType T, |
2467 | SourceLocation StartLoc, |
2468 | SourceLocation EndLoc); |
2469 | |
2470 | bool DiagnoseMissingSemiAfterTagDefinition( |
2471 | DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, |
2472 | LateParsedAttrList *LateAttrs = nullptr); |
2473 | |
2474 | void ParseSpecifierQualifierList( |
2475 | DeclSpec &DS, AccessSpecifier AS = AS_none, |
2476 | DeclSpecContext DSC = DeclSpecContext::DSC_normal) { |
2477 | ParseSpecifierQualifierList(DS, AllowImplicitTypename: getImplicitTypenameContext(DSC), AS, DSC); |
2478 | } |
2479 | |
2480 | void ParseSpecifierQualifierList( |
2481 | DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename, |
2482 | AccessSpecifier AS = AS_none, |
2483 | DeclSpecContext DSC = DeclSpecContext::DSC_normal); |
2484 | |
2485 | void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, |
2486 | DeclaratorContext Context); |
2487 | |
2488 | void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, |
2489 | const ParsedTemplateInfo &TemplateInfo, |
2490 | AccessSpecifier AS, DeclSpecContext DSC); |
2491 | void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); |
2492 | void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, |
2493 | RecordDecl *TagDecl); |
2494 | |
2495 | void ParseStructDeclaration( |
2496 | ParsingDeclSpec &DS, |
2497 | llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); |
2498 | |
2499 | DeclGroupPtrTy ParseTopLevelStmtDecl(); |
2500 | |
2501 | bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename, |
2502 | bool DisambiguatingWithExpression = false); |
2503 | bool isTypeSpecifierQualifier(); |
2504 | |
2505 | /// isKnownToBeTypeSpecifier - Return true if we know that the specified token |
2506 | /// is definitely a type-specifier. Return false if it isn't part of a type |
2507 | /// specifier or if we're not sure. |
2508 | bool isKnownToBeTypeSpecifier(const Token &Tok) const; |
2509 | |
2510 | /// Return true if we know that we are definitely looking at a |
2511 | /// decl-specifier, and isn't part of an expression such as a function-style |
2512 | /// cast. Return false if it's no a decl-specifier, or we're not sure. |
2513 | bool isKnownToBeDeclarationSpecifier() { |
2514 | if (getLangOpts().CPlusPlus) |
2515 | return isCXXDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No) == |
2516 | TPResult::True; |
2517 | return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No, DisambiguatingWithExpression: true); |
2518 | } |
2519 | |
2520 | /// isDeclarationStatement - Disambiguates between a declaration or an |
2521 | /// expression statement, when parsing function bodies. |
2522 | /// |
2523 | /// \param DisambiguatingWithExpression - True to indicate that the purpose of |
2524 | /// this check is to disambiguate between an expression and a declaration. |
2525 | /// Returns true for declaration, false for expression. |
2526 | bool isDeclarationStatement(bool DisambiguatingWithExpression = false) { |
2527 | if (getLangOpts().CPlusPlus) |
2528 | return isCXXDeclarationStatement(DisambiguatingWithExpression); |
2529 | return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No, DisambiguatingWithExpression: true); |
2530 | } |
2531 | |
2532 | /// isForInitDeclaration - Disambiguates between a declaration or an |
2533 | /// expression in the context of the C 'clause-1' or the C++ |
2534 | // 'for-init-statement' part of a 'for' statement. |
2535 | /// Returns true for declaration, false for expression. |
2536 | bool isForInitDeclaration() { |
2537 | if (getLangOpts().OpenMP) |
2538 | Actions.startOpenMPLoop(); |
2539 | if (getLangOpts().CPlusPlus) |
2540 | return Tok.is(K: tok::kw_using) || |
2541 | isCXXSimpleDeclaration(/*AllowForRangeDecl=*/AllowForRangeDecl: true); |
2542 | return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No, DisambiguatingWithExpression: true); |
2543 | } |
2544 | |
2545 | /// Determine whether this is a C++1z for-range-identifier. |
2546 | bool isForRangeIdentifier(); |
2547 | |
2548 | /// Determine whether we are currently at the start of an Objective-C |
2549 | /// class message that appears to be missing the open bracket '['. |
2550 | bool isStartOfObjCClassMessageMissingOpenBracket(); |
2551 | |
2552 | /// Starting with a scope specifier, identifier, or |
2553 | /// template-id that refers to the current class, determine whether |
2554 | /// this is a constructor declarator. |
2555 | bool isConstructorDeclarator( |
2556 | bool Unqualified, bool DeductionGuide = false, |
2557 | DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No, |
2558 | const ParsedTemplateInfo *TemplateInfo = nullptr); |
2559 | |
2560 | /// Specifies the context in which type-id/expression |
2561 | /// disambiguation will occur. |
2562 | enum TentativeCXXTypeIdContext { |
2563 | TypeIdInParens, |
2564 | TypeIdUnambiguous, |
2565 | TypeIdAsTemplateArgument, |
2566 | TypeIdInTrailingReturnType, |
2567 | TypeIdAsGenericSelectionArgument, |
2568 | }; |
2569 | |
2570 | /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know |
2571 | /// whether the parens contain an expression or a type-id. |
2572 | /// Returns true for a type-id and false for an expression. |
2573 | bool isTypeIdInParens(bool &isAmbiguous) { |
2574 | if (getLangOpts().CPlusPlus) |
2575 | return isCXXTypeId(Context: TypeIdInParens, isAmbiguous); |
2576 | isAmbiguous = false; |
2577 | return isTypeSpecifierQualifier(); |
2578 | } |
2579 | bool isTypeIdInParens() { |
2580 | bool isAmbiguous; |
2581 | return isTypeIdInParens(isAmbiguous); |
2582 | } |
2583 | |
2584 | /// Checks whether the current tokens form a type-id or an expression for the |
2585 | /// purposes of use as the initial operand to a generic selection expression. |
2586 | /// This requires special handling in C++ because it accepts either a type or |
2587 | /// an expression, and we need to disambiguate which is which. However, we |
2588 | /// cannot use the same logic as we've used for sizeof expressions, because |
2589 | /// that logic relies on the operator only accepting a single argument, |
2590 | /// whereas _Generic accepts a list of arguments. |
2591 | bool isTypeIdForGenericSelection() { |
2592 | if (getLangOpts().CPlusPlus) { |
2593 | bool isAmbiguous; |
2594 | return isCXXTypeId(Context: TypeIdAsGenericSelectionArgument, isAmbiguous); |
2595 | } |
2596 | return isTypeSpecifierQualifier(); |
2597 | } |
2598 | |
2599 | /// Checks if the current tokens form type-id or expression. |
2600 | /// It is similar to isTypeIdInParens but does not suppose that type-id |
2601 | /// is in parenthesis. |
2602 | bool isTypeIdUnambiguously() { |
2603 | if (getLangOpts().CPlusPlus) { |
2604 | bool isAmbiguous; |
2605 | return isCXXTypeId(Context: TypeIdUnambiguous, isAmbiguous); |
2606 | } |
2607 | return isTypeSpecifierQualifier(); |
2608 | } |
2609 | |
2610 | /// isCXXDeclarationStatement - C++-specialized function that disambiguates |
2611 | /// between a declaration or an expression statement, when parsing function |
2612 | /// bodies. Returns true for declaration, false for expression. |
2613 | bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false); |
2614 | |
2615 | /// isCXXSimpleDeclaration - C++-specialized function that disambiguates |
2616 | /// between a simple-declaration or an expression-statement. |
2617 | /// If during the disambiguation process a parsing error is encountered, |
2618 | /// the function returns true to let the declaration parsing code handle it. |
2619 | /// Returns false if the statement is disambiguated as expression. |
2620 | bool isCXXSimpleDeclaration(bool AllowForRangeDecl); |
2621 | |
2622 | /// isCXXFunctionDeclarator - Disambiguates between a function declarator or |
2623 | /// a constructor-style initializer, when parsing declaration statements. |
2624 | /// Returns true for function declarator and false for constructor-style |
2625 | /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration |
2626 | /// might be a constructor-style initializer. |
2627 | /// If during the disambiguation process a parsing error is encountered, |
2628 | /// the function returns true to let the declaration parsing code handle it. |
2629 | bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr, |
2630 | ImplicitTypenameContext AllowImplicitTypename = |
2631 | ImplicitTypenameContext::No); |
2632 | |
2633 | struct ConditionDeclarationOrInitStatementState; |
2634 | enum class ConditionOrInitStatement { |
2635 | Expression, ///< Disambiguated as an expression (either kind). |
2636 | ConditionDecl, ///< Disambiguated as the declaration form of condition. |
2637 | InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. |
2638 | ForRangeDecl, ///< Disambiguated as a for-range declaration. |
2639 | Error ///< Can't be any of the above! |
2640 | }; |
2641 | /// Disambiguates between the different kinds of things that can happen |
2642 | /// after 'if (' or 'switch ('. This could be one of two different kinds of |
2643 | /// declaration (depending on whether there is a ';' later) or an expression. |
2644 | ConditionOrInitStatement |
2645 | isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, |
2646 | bool CanBeForRangeDecl); |
2647 | |
2648 | bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); |
2649 | bool isCXXTypeId(TentativeCXXTypeIdContext Context) { |
2650 | bool isAmbiguous; |
2651 | return isCXXTypeId(Context, isAmbiguous); |
2652 | } |
2653 | |
2654 | /// TPResult - Used as the result value for functions whose purpose is to |
2655 | /// disambiguate C++ constructs by "tentatively parsing" them. |
2656 | enum class TPResult { |
2657 | True, False, Ambiguous, Error |
2658 | }; |
2659 | |
2660 | /// Determine whether we could have an enum-base. |
2661 | /// |
2662 | /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise |
2663 | /// only consider this to be an enum-base if the next token is a '{'. |
2664 | /// |
2665 | /// \return \c false if this cannot possibly be an enum base; \c true |
2666 | /// otherwise. |
2667 | bool isEnumBase(bool AllowSemi); |
2668 | |
2669 | /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a |
2670 | /// declaration specifier, TPResult::False if it is not, |
2671 | /// TPResult::Ambiguous if it could be either a decl-specifier or a |
2672 | /// function-style cast, and TPResult::Error if a parsing error was |
2673 | /// encountered. If it could be a braced C++11 function-style cast, returns |
2674 | /// BracedCastResult. |
2675 | /// Doesn't consume tokens. |
2676 | TPResult |
2677 | isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename, |
2678 | TPResult BracedCastResult = TPResult::False, |
2679 | bool *InvalidAsDeclSpec = nullptr); |
2680 | |
2681 | /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or |
2682 | /// \c TPResult::Ambiguous, determine whether the decl-specifier would be |
2683 | /// a type-specifier other than a cv-qualifier. |
2684 | bool isCXXDeclarationSpecifierAType(); |
2685 | |
2686 | /// Determine whether the current token sequence might be |
2687 | /// '<' template-argument-list '>' |
2688 | /// rather than a less-than expression. |
2689 | TPResult isTemplateArgumentList(unsigned TokensToSkip); |
2690 | |
2691 | /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 |
2692 | /// 'explicit(bool)' declaration, in earlier language modes where that is an |
2693 | /// extension. |
2694 | TPResult isExplicitBool(); |
2695 | |
2696 | /// Determine whether an identifier has been tentatively declared as a |
2697 | /// non-type. Such tentative declarations should not be found to name a type |
2698 | /// during a tentative parse, but also should not be annotated as a non-type. |
2699 | bool isTentativelyDeclared(IdentifierInfo *II); |
2700 | |
2701 | // "Tentative parsing" functions, used for disambiguation. If a parsing error |
2702 | // is encountered they will return TPResult::Error. |
2703 | // Returning TPResult::True/False indicates that the ambiguity was |
2704 | // resolved and tentative parsing may stop. TPResult::Ambiguous indicates |
2705 | // that more tentative parsing is necessary for disambiguation. |
2706 | // They all consume tokens, so backtracking should be used after calling them. |
2707 | |
2708 | TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); |
2709 | TPResult TryParseTypeofSpecifier(); |
2710 | TPResult TryParseProtocolQualifiers(); |
2711 | TPResult TryParsePtrOperatorSeq(); |
2712 | TPResult TryParseOperatorId(); |
2713 | TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false); |
2714 | TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, |
2715 | bool mayHaveDirectInit = false, |
2716 | bool mayHaveTrailingReturnType = false); |
2717 | TPResult TryParseParameterDeclarationClause( |
2718 | bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false, |
2719 | ImplicitTypenameContext AllowImplicitTypename = |
2720 | ImplicitTypenameContext::No); |
2721 | TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false); |
2722 | bool NameAfterArrowIsNonType(); |
2723 | TPResult TryParseBracketDeclarator(); |
2724 | TPResult TryConsumeDeclarationSpecifier(); |
2725 | |
2726 | /// Try to skip a possibly empty sequence of 'attribute-specifier's without |
2727 | /// full validation of the syntactic structure of attributes. |
2728 | bool TrySkipAttributes(); |
2729 | |
2730 | /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of |
2731 | /// _BitInt as an extension when appropriate. |
2732 | void DiagnoseBitIntUse(const Token &Tok); |
2733 | |
2734 | public: |
2735 | TypeResult |
2736 | ParseTypeName(SourceRange *Range = nullptr, |
2737 | DeclaratorContext Context = DeclaratorContext::TypeName, |
2738 | AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, |
2739 | ParsedAttributes *Attrs = nullptr); |
2740 | |
2741 | private: |
2742 | void ParseBlockId(SourceLocation CaretLoc); |
2743 | |
2744 | /// Return true if the next token should be treated as a [[]] attribute, |
2745 | /// or as a keyword that behaves like one. The former is only true if |
2746 | /// [[]] attributes are enabled, whereas the latter is true whenever |
2747 | /// such a keyword appears. The arguments are as for |
2748 | /// isCXX11AttributeSpecifier. |
2749 | bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false, |
2750 | bool OuterMightBeMessageSend = false) { |
2751 | return (Tok.isRegularKeywordAttribute() || |
2752 | isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend)); |
2753 | } |
2754 | |
2755 | // Check for the start of an attribute-specifier-seq in a context where an |
2756 | // attribute is not allowed. |
2757 | bool CheckProhibitedCXX11Attribute() { |
2758 | assert(Tok.is(tok::l_square)); |
2759 | if (NextToken().isNot(K: tok::l_square)) |
2760 | return false; |
2761 | return DiagnoseProhibitedCXX11Attribute(); |
2762 | } |
2763 | |
2764 | bool DiagnoseProhibitedCXX11Attribute(); |
2765 | void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs, |
2766 | SourceLocation CorrectLocation) { |
2767 | if (!Tok.isRegularKeywordAttribute() && |
2768 | (Tok.isNot(K: tok::l_square) || NextToken().isNot(K: tok::l_square)) && |
2769 | Tok.isNot(K: tok::kw_alignas)) |
2770 | return; |
2771 | DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); |
2772 | } |
2773 | void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs, |
2774 | SourceLocation CorrectLocation); |
2775 | |
2776 | void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS, |
2777 | Sema::TagUseKind TUK); |
2778 | |
2779 | // FixItLoc = possible correct location for the attributes |
2780 | void ProhibitAttributes(ParsedAttributes &Attrs, |
2781 | SourceLocation FixItLoc = SourceLocation()) { |
2782 | if (Attrs.Range.isInvalid()) |
2783 | return; |
2784 | DiagnoseProhibitedAttributes(Attrs, FixItLoc); |
2785 | Attrs.clear(); |
2786 | } |
2787 | |
2788 | void ProhibitAttributes(ParsedAttributesView &Attrs, |
2789 | SourceLocation FixItLoc = SourceLocation()) { |
2790 | if (Attrs.Range.isInvalid()) |
2791 | return; |
2792 | DiagnoseProhibitedAttributes(Attrs, FixItLoc); |
2793 | Attrs.clearListOnly(); |
2794 | } |
2795 | void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs, |
2796 | SourceLocation FixItLoc); |
2797 | |
2798 | // Forbid C++11 and C23 attributes that appear on certain syntactic locations |
2799 | // which standard permits but we don't supported yet, for example, attributes |
2800 | // appertain to decl specifiers. |
2801 | // For the most cases we don't want to warn on unknown type attributes, but |
2802 | // left them to later diagnoses. However, for a few cases like module |
2803 | // declarations and module import declarations, we should do it. |
2804 | void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID, |
2805 | unsigned KeywordDiagId, |
2806 | bool DiagnoseEmptyAttrs = false, |
2807 | bool WarnOnUnknownAttrs = false); |
2808 | |
2809 | /// Skip C++11 and C23 attributes and return the end location of the |
2810 | /// last one. |
2811 | /// \returns SourceLocation() if there are no attributes. |
2812 | SourceLocation SkipCXX11Attributes(); |
2813 | |
2814 | /// Diagnose and skip C++11 and C23 attributes that appear in syntactic |
2815 | /// locations where attributes are not allowed. |
2816 | void DiagnoseAndSkipCXX11Attributes(); |
2817 | |
2818 | /// Emit warnings for C++11 and C23 attributes that are in a position that |
2819 | /// clang accepts as an extension. |
2820 | void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs); |
2821 | |
2822 | ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName); |
2823 | |
2824 | bool |
2825 | ParseAttributeArgumentList(const clang::IdentifierInfo &AttrName, |
2826 | SmallVectorImpl<Expr *> &Exprs, |
2827 | ParsedAttributeArgumentsProperties ArgsProperties); |
2828 | |
2829 | /// Parses syntax-generic attribute arguments for attributes which are |
2830 | /// known to the implementation, and adds them to the given ParsedAttributes |
2831 | /// list with the given attribute syntax. Returns the number of arguments |
2832 | /// parsed for the attribute. |
2833 | unsigned |
2834 | ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, |
2835 | ParsedAttributes &Attrs, SourceLocation *EndLoc, |
2836 | IdentifierInfo *ScopeName, SourceLocation ScopeLoc, |
2837 | ParsedAttr::Form Form); |
2838 | |
2839 | enum ParseAttrKindMask { |
2840 | PAKM_GNU = 1 << 0, |
2841 | PAKM_Declspec = 1 << 1, |
2842 | PAKM_CXX11 = 1 << 2, |
2843 | }; |
2844 | |
2845 | /// \brief Parse attributes based on what syntaxes are desired, allowing for |
2846 | /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec: |
2847 | /// __attribute__((...)) __declspec(...) __attribute__((...))) |
2848 | /// Note that Microsoft attributes (spelled with single square brackets) are |
2849 | /// not supported by this because of parsing ambiguities with other |
2850 | /// constructs. |
2851 | /// |
2852 | /// There are some attribute parse orderings that should not be allowed in |
2853 | /// arbitrary order. e.g., |
2854 | /// |
2855 | /// [[]] __attribute__(()) int i; // OK |
2856 | /// __attribute__(()) [[]] int i; // Not OK |
2857 | /// |
2858 | /// Such situations should use the specific attribute parsing functionality. |
2859 | void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, |
2860 | LateParsedAttrList *LateAttrs = nullptr); |
2861 | /// \brief Possibly parse attributes based on what syntaxes are desired, |
2862 | /// allowing for the order to vary. |
2863 | bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, |
2864 | LateParsedAttrList *LateAttrs = nullptr) { |
2865 | if (Tok.isOneOf(K1: tok::kw___attribute, K2: tok::kw___declspec) || |
2866 | isAllowedCXX11AttributeSpecifier()) { |
2867 | ParseAttributes(WhichAttrKinds, Attrs, LateAttrs); |
2868 | return true; |
2869 | } |
2870 | return false; |
2871 | } |
2872 | |
2873 | void MaybeParseGNUAttributes(Declarator &D, |
2874 | LateParsedAttrList *LateAttrs = nullptr) { |
2875 | if (Tok.is(K: tok::kw___attribute)) { |
2876 | ParsedAttributes Attrs(AttrFactory); |
2877 | ParseGNUAttributes(Attrs, LateAttrs, D: &D); |
2878 | D.takeAttributes(attrs&: Attrs); |
2879 | } |
2880 | } |
2881 | |
2882 | bool MaybeParseGNUAttributes(ParsedAttributes &Attrs, |
2883 | LateParsedAttrList *LateAttrs = nullptr) { |
2884 | if (Tok.is(K: tok::kw___attribute)) { |
2885 | ParseGNUAttributes(Attrs, LateAttrs); |
2886 | return true; |
2887 | } |
2888 | return false; |
2889 | } |
2890 | |
2891 | void ParseGNUAttributes(ParsedAttributes &Attrs, |
2892 | LateParsedAttrList *LateAttrs = nullptr, |
2893 | Declarator *D = nullptr); |
2894 | void ParseGNUAttributeArgs(IdentifierInfo *AttrName, |
2895 | SourceLocation AttrNameLoc, |
2896 | ParsedAttributes &Attrs, SourceLocation *EndLoc, |
2897 | IdentifierInfo *ScopeName, SourceLocation ScopeLoc, |
2898 | ParsedAttr::Form Form, Declarator *D); |
2899 | IdentifierLoc *ParseIdentifierLoc(); |
2900 | |
2901 | unsigned |
2902 | ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, |
2903 | ParsedAttributes &Attrs, SourceLocation *EndLoc, |
2904 | IdentifierInfo *ScopeName, SourceLocation ScopeLoc, |
2905 | ParsedAttr::Form Form); |
2906 | |
2907 | void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) { |
2908 | // If parsing the attributes found an OpenMP directive, emit those tokens |
2909 | // to the parse stream now. |
2910 | if (!OpenMPTokens.empty()) { |
2911 | PP.EnterToken(Tok, /*IsReinject*/ IsReinject: true); |
2912 | PP.EnterTokenStream(Toks: OpenMPTokens, /*DisableMacroExpansion*/ DisableMacroExpansion: true, |
2913 | /*IsReinject*/ IsReinject: true); |
2914 | ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ ConsumeCodeCompletionTok: true); |
2915 | } |
2916 | } |
2917 | void MaybeParseCXX11Attributes(Declarator &D) { |
2918 | if (isAllowedCXX11AttributeSpecifier()) { |
2919 | ParsedAttributes Attrs(AttrFactory); |
2920 | ParseCXX11Attributes(attrs&: Attrs); |
2921 | D.takeAttributes(attrs&: Attrs); |
2922 | } |
2923 | } |
2924 | |
2925 | bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs, |
2926 | bool OuterMightBeMessageSend = false) { |
2927 | if (isAllowedCXX11AttributeSpecifier(Disambiguate: false, OuterMightBeMessageSend)) { |
2928 | ParseCXX11Attributes(attrs&: Attrs); |
2929 | return true; |
2930 | } |
2931 | return false; |
2932 | } |
2933 | |
2934 | void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName, |
2935 | CachedTokens &OpenMPTokens); |
2936 | |
2937 | void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs, |
2938 | CachedTokens &OpenMPTokens, |
2939 | SourceLocation *EndLoc = nullptr); |
2940 | void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs, |
2941 | SourceLocation *EndLoc = nullptr) { |
2942 | CachedTokens OpenMPTokens; |
2943 | ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc); |
2944 | ReplayOpenMPAttributeTokens(OpenMPTokens); |
2945 | } |
2946 | void ParseCXX11Attributes(ParsedAttributes &attrs); |
2947 | /// Parses a C++11 (or C23)-style attribute argument list. Returns true |
2948 | /// if this results in adding an attribute to the ParsedAttributes list. |
2949 | bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, |
2950 | SourceLocation AttrNameLoc, |
2951 | ParsedAttributes &Attrs, SourceLocation *EndLoc, |
2952 | IdentifierInfo *ScopeName, |
2953 | SourceLocation ScopeLoc, |
2954 | CachedTokens &OpenMPTokens); |
2955 | |
2956 | IdentifierInfo *TryParseCXX11AttributeIdentifier( |
2957 | SourceLocation &Loc, |
2958 | Sema::AttributeCompletion Completion = Sema::AttributeCompletion::None, |
2959 | const IdentifierInfo *EnclosingScope = nullptr); |
2960 | |
2961 | void MaybeParseHLSLSemantics(Declarator &D, |
2962 | SourceLocation *EndLoc = nullptr) { |
2963 | assert(getLangOpts().HLSL && "MaybeParseHLSLSemantics is for HLSL only" ); |
2964 | if (Tok.is(K: tok::colon)) { |
2965 | ParsedAttributes Attrs(AttrFactory); |
2966 | ParseHLSLSemantics(Attrs, EndLoc); |
2967 | D.takeAttributes(attrs&: Attrs); |
2968 | } |
2969 | } |
2970 | |
2971 | void MaybeParseHLSLSemantics(ParsedAttributes &Attrs, |
2972 | SourceLocation *EndLoc = nullptr) { |
2973 | assert(getLangOpts().HLSL && "MaybeParseHLSLSemantics is for HLSL only" ); |
2974 | if (getLangOpts().HLSL && Tok.is(K: tok::colon)) |
2975 | ParseHLSLSemantics(Attrs, EndLoc); |
2976 | } |
2977 | |
2978 | void ParseHLSLSemantics(ParsedAttributes &Attrs, |
2979 | SourceLocation *EndLoc = nullptr); |
2980 | Decl *ParseHLSLBuffer(SourceLocation &DeclEnd); |
2981 | |
2982 | void MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) { |
2983 | if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) && |
2984 | Tok.is(K: tok::l_square)) { |
2985 | ParsedAttributes AttrsWithRange(AttrFactory); |
2986 | ParseMicrosoftAttributes(Attrs&: AttrsWithRange); |
2987 | Attrs.takeAllFrom(Other&: AttrsWithRange); |
2988 | } |
2989 | } |
2990 | void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); |
2991 | void ParseMicrosoftAttributes(ParsedAttributes &Attrs); |
2992 | bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) { |
2993 | if (getLangOpts().DeclSpecKeyword && Tok.is(K: tok::kw___declspec)) { |
2994 | ParseMicrosoftDeclSpecs(Attrs); |
2995 | return true; |
2996 | } |
2997 | return false; |
2998 | } |
2999 | void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs); |
3000 | bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, |
3001 | SourceLocation AttrNameLoc, |
3002 | ParsedAttributes &Attrs); |
3003 | void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); |
3004 | void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs); |
3005 | void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); |
3006 | SourceLocation SkipExtendedMicrosoftTypeAttributes(); |
3007 | void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); |
3008 | void ParseBorlandTypeAttributes(ParsedAttributes &attrs); |
3009 | void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); |
3010 | void ParseOpenCLQualifiers(ParsedAttributes &Attrs); |
3011 | void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); |
3012 | void ParseCUDAFunctionAttributes(ParsedAttributes &attrs); |
3013 | bool isHLSLQualifier(const Token &Tok) const; |
3014 | void ParseHLSLQualifiers(ParsedAttributes &Attrs); |
3015 | |
3016 | VersionTuple ParseVersionTuple(SourceRange &Range); |
3017 | void ParseAvailabilityAttribute(IdentifierInfo &Availability, |
3018 | SourceLocation AvailabilityLoc, |
3019 | ParsedAttributes &attrs, |
3020 | SourceLocation *endLoc, |
3021 | IdentifierInfo *ScopeName, |
3022 | SourceLocation ScopeLoc, |
3023 | ParsedAttr::Form Form); |
3024 | |
3025 | std::optional<AvailabilitySpec> ParseAvailabilitySpec(); |
3026 | ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); |
3027 | |
3028 | void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, |
3029 | SourceLocation Loc, |
3030 | ParsedAttributes &Attrs, |
3031 | SourceLocation *EndLoc, |
3032 | IdentifierInfo *ScopeName, |
3033 | SourceLocation ScopeLoc, |
3034 | ParsedAttr::Form Form); |
3035 | |
3036 | void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, |
3037 | SourceLocation ObjCBridgeRelatedLoc, |
3038 | ParsedAttributes &Attrs, |
3039 | SourceLocation *EndLoc, |
3040 | IdentifierInfo *ScopeName, |
3041 | SourceLocation ScopeLoc, |
3042 | ParsedAttr::Form Form); |
3043 | |
3044 | void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName, |
3045 | SourceLocation AttrNameLoc, |
3046 | ParsedAttributes &Attrs, |
3047 | SourceLocation *EndLoc, |
3048 | IdentifierInfo *ScopeName, |
3049 | SourceLocation ScopeLoc, |
3050 | ParsedAttr::Form Form); |
3051 | |
3052 | void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, |
3053 | SourceLocation AttrNameLoc, |
3054 | ParsedAttributes &Attrs, |
3055 | SourceLocation *EndLoc, |
3056 | IdentifierInfo *ScopeName, |
3057 | SourceLocation ScopeLoc, |
3058 | ParsedAttr::Form Form); |
3059 | |
3060 | void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, |
3061 | SourceLocation AttrNameLoc, |
3062 | ParsedAttributes &Attrs, |
3063 | IdentifierInfo *ScopeName, |
3064 | SourceLocation ScopeLoc, |
3065 | ParsedAttr::Form Form); |
3066 | |
3067 | void ParseTypeofSpecifier(DeclSpec &DS); |
3068 | SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); |
3069 | void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, |
3070 | SourceLocation StartLoc, |
3071 | SourceLocation EndLoc); |
3072 | void ParseAtomicSpecifier(DeclSpec &DS); |
3073 | |
3074 | ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start, |
3075 | SourceLocation &EllipsisLoc, bool &IsType, |
3076 | ParsedType &Ty); |
3077 | void ParseAlignmentSpecifier(ParsedAttributes &Attrs, |
3078 | SourceLocation *endLoc = nullptr); |
3079 | ExprResult ParseExtIntegerArgument(); |
3080 | |
3081 | VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; |
3082 | VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { |
3083 | return isCXX11VirtSpecifier(Tok); |
3084 | } |
3085 | void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, |
3086 | SourceLocation FriendLoc); |
3087 | |
3088 | bool isCXX11FinalKeyword() const; |
3089 | bool isClassCompatibleKeyword() const; |
3090 | |
3091 | /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to |
3092 | /// enter a new C++ declarator scope and exit it when the function is |
3093 | /// finished. |
3094 | class DeclaratorScopeObj { |
3095 | Parser &P; |
3096 | CXXScopeSpec &SS; |
3097 | bool EnteredScope; |
3098 | bool CreatedScope; |
3099 | public: |
3100 | DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) |
3101 | : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} |
3102 | |
3103 | void EnterDeclaratorScope() { |
3104 | assert(!EnteredScope && "Already entered the scope!" ); |
3105 | assert(SS.isSet() && "C++ scope was not set!" ); |
3106 | |
3107 | CreatedScope = true; |
3108 | P.EnterScope(ScopeFlags: 0); // Not a decl scope. |
3109 | |
3110 | if (!P.Actions.ActOnCXXEnterDeclaratorScope(S: P.getCurScope(), SS)) |
3111 | EnteredScope = true; |
3112 | } |
3113 | |
3114 | ~DeclaratorScopeObj() { |
3115 | if (EnteredScope) { |
3116 | assert(SS.isSet() && "C++ scope was cleared ?" ); |
3117 | P.Actions.ActOnCXXExitDeclaratorScope(S: P.getCurScope(), SS); |
3118 | } |
3119 | if (CreatedScope) |
3120 | P.ExitScope(); |
3121 | } |
3122 | }; |
3123 | |
3124 | /// ParseDeclarator - Parse and verify a newly-initialized declarator. |
3125 | void ParseDeclarator(Declarator &D); |
3126 | /// A function that parses a variant of direct-declarator. |
3127 | typedef void (Parser::*DirectDeclParseFunction)(Declarator&); |
3128 | void ParseDeclaratorInternal(Declarator &D, |
3129 | DirectDeclParseFunction DirectDeclParser); |
3130 | |
3131 | enum AttrRequirements { |
3132 | AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. |
3133 | AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. |
3134 | AR_GNUAttributesParsed = 1 << 1, |
3135 | AR_CXX11AttributesParsed = 1 << 2, |
3136 | AR_DeclspecAttributesParsed = 1 << 3, |
3137 | AR_AllAttributesParsed = AR_GNUAttributesParsed | |
3138 | AR_CXX11AttributesParsed | |
3139 | AR_DeclspecAttributesParsed, |
3140 | AR_VendorAttributesParsed = AR_GNUAttributesParsed | |
3141 | AR_DeclspecAttributesParsed |
3142 | }; |
3143 | |
3144 | void ParseTypeQualifierListOpt( |
3145 | DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, |
3146 | bool AtomicAllowed = true, bool IdentifierRequired = false, |
3147 | std::optional<llvm::function_ref<void()>> CodeCompletionHandler = |
3148 | std::nullopt); |
3149 | void ParseDirectDeclarator(Declarator &D); |
3150 | void ParseDecompositionDeclarator(Declarator &D); |
3151 | void ParseParenDeclarator(Declarator &D); |
3152 | void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs, |
3153 | BalancedDelimiterTracker &Tracker, |
3154 | bool IsAmbiguous, bool RequiresArg = false); |
3155 | void InitCXXThisScopeForDeclaratorIfRelevant( |
3156 | const Declarator &D, const DeclSpec &DS, |
3157 | std::optional<Sema::CXXThisScopeRAII> &ThisScope); |
3158 | bool ParseRefQualifier(bool &RefQualifierIsLValueRef, |
3159 | SourceLocation &RefQualifierLoc); |
3160 | bool isFunctionDeclaratorIdentifierList(); |
3161 | void ParseFunctionDeclaratorIdentifierList( |
3162 | Declarator &D, |
3163 | SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); |
3164 | void ParseParameterDeclarationClause( |
3165 | Declarator &D, ParsedAttributes &attrs, |
3166 | SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, |
3167 | SourceLocation &EllipsisLoc) { |
3168 | return ParseParameterDeclarationClause( |
3169 | DeclaratorContext: D.getContext(), attrs, ParamInfo, EllipsisLoc, |
3170 | IsACXXFunctionDeclaration: D.getCXXScopeSpec().isSet() && |
3171 | D.isFunctionDeclaratorAFunctionDeclaration()); |
3172 | } |
3173 | void ParseParameterDeclarationClause( |
3174 | DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, |
3175 | SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, |
3176 | SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false); |
3177 | |
3178 | void ParseBracketDeclarator(Declarator &D); |
3179 | void ParseMisplacedBracketDeclarator(Declarator &D); |
3180 | bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS); |
3181 | DeclSpec::TST TypeTransformTokToDeclSpec(); |
3182 | |
3183 | //===--------------------------------------------------------------------===// |
3184 | // C++ 7: Declarations [dcl.dcl] |
3185 | |
3186 | /// The kind of attribute specifier we have found. |
3187 | enum CXX11AttributeKind { |
3188 | /// This is not an attribute specifier. |
3189 | CAK_NotAttributeSpecifier, |
3190 | /// This should be treated as an attribute-specifier. |
3191 | CAK_AttributeSpecifier, |
3192 | /// The next tokens are '[[', but this is not an attribute-specifier. This |
3193 | /// is ill-formed by C++11 [dcl.attr.grammar]p6. |
3194 | CAK_InvalidAttributeSpecifier |
3195 | }; |
3196 | CXX11AttributeKind |
3197 | isCXX11AttributeSpecifier(bool Disambiguate = false, |
3198 | bool OuterMightBeMessageSend = false); |
3199 | |
3200 | void DiagnoseUnexpectedNamespace(NamedDecl *Context); |
3201 | |
3202 | DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, |
3203 | SourceLocation &DeclEnd, |
3204 | SourceLocation InlineLoc = SourceLocation()); |
3205 | |
3206 | struct InnerNamespaceInfo { |
3207 | SourceLocation NamespaceLoc; |
3208 | SourceLocation InlineLoc; |
3209 | SourceLocation IdentLoc; |
3210 | IdentifierInfo *Ident; |
3211 | }; |
3212 | using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; |
3213 | |
3214 | void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, |
3215 | unsigned int index, SourceLocation &InlineLoc, |
3216 | ParsedAttributes &attrs, |
3217 | BalancedDelimiterTracker &Tracker); |
3218 | Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); |
3219 | Decl *ParseExportDeclaration(); |
3220 | DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( |
3221 | DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, |
3222 | SourceLocation &DeclEnd, ParsedAttributes &Attrs); |
3223 | Decl *ParseUsingDirective(DeclaratorContext Context, |
3224 | SourceLocation UsingLoc, |
3225 | SourceLocation &DeclEnd, |
3226 | ParsedAttributes &attrs); |
3227 | |
3228 | struct UsingDeclarator { |
3229 | SourceLocation TypenameLoc; |
3230 | CXXScopeSpec SS; |
3231 | UnqualifiedId Name; |
3232 | SourceLocation EllipsisLoc; |
3233 | |
3234 | void clear() { |
3235 | TypenameLoc = EllipsisLoc = SourceLocation(); |
3236 | SS.clear(); |
3237 | Name.clear(); |
3238 | } |
3239 | }; |
3240 | |
3241 | bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); |
3242 | DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, |
3243 | const ParsedTemplateInfo &TemplateInfo, |
3244 | SourceLocation UsingLoc, |
3245 | SourceLocation &DeclEnd, |
3246 | ParsedAttributes &Attrs, |
3247 | AccessSpecifier AS = AS_none); |
3248 | Decl *ParseAliasDeclarationAfterDeclarator( |
3249 | const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, |
3250 | UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, |
3251 | ParsedAttributes &Attrs, Decl **OwnedType = nullptr); |
3252 | |
3253 | Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); |
3254 | Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, |
3255 | SourceLocation AliasLoc, IdentifierInfo *Alias, |
3256 | SourceLocation &DeclEnd); |
3257 | |
3258 | //===--------------------------------------------------------------------===// |
3259 | // C++ 9: classes [class] and C structs/unions. |
3260 | bool isValidAfterTypeSpecifier(bool CouldBeBitfield); |
3261 | void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, |
3262 | DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, |
3263 | AccessSpecifier AS, bool EnteringContext, |
3264 | DeclSpecContext DSC, ParsedAttributes &Attributes); |
3265 | void SkipCXXMemberSpecification(SourceLocation StartLoc, |
3266 | SourceLocation AttrFixitLoc, |
3267 | unsigned TagType, |
3268 | Decl *TagDecl); |
3269 | void ParseCXXMemberSpecification(SourceLocation StartLoc, |
3270 | SourceLocation AttrFixitLoc, |
3271 | ParsedAttributes &Attrs, unsigned TagType, |
3272 | Decl *TagDecl); |
3273 | ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, |
3274 | SourceLocation &EqualLoc); |
3275 | bool |
3276 | ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, |
3277 | VirtSpecifiers &VS, |
3278 | ExprResult &BitfieldSize, |
3279 | LateParsedAttrList &LateAttrs); |
3280 | void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, |
3281 | VirtSpecifiers &VS); |
3282 | DeclGroupPtrTy ParseCXXClassMemberDeclaration( |
3283 | AccessSpecifier AS, ParsedAttributes &Attr, |
3284 | const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), |
3285 | ParsingDeclRAIIObject *DiagsFromTParams = nullptr); |
3286 | DeclGroupPtrTy |
3287 | ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS, |
3288 | ParsedAttributes &AccessAttrs, |
3289 | DeclSpec::TST TagType, Decl *Tag); |
3290 | void ParseConstructorInitializer(Decl *ConstructorDecl); |
3291 | MemInitResult ParseMemInitializer(Decl *ConstructorDecl); |
3292 | void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, |
3293 | Decl *ThisDecl); |
3294 | |
3295 | //===--------------------------------------------------------------------===// |
3296 | // C++ 10: Derived classes [class.derived] |
3297 | TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, |
3298 | SourceLocation &EndLocation); |
3299 | void ParseBaseClause(Decl *ClassDecl); |
3300 | BaseResult ParseBaseSpecifier(Decl *ClassDecl); |
3301 | AccessSpecifier getAccessSpecifierIfPresent() const; |
3302 | |
3303 | bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, |
3304 | ParsedType ObjectType, |
3305 | bool ObjectHadErrors, |
3306 | SourceLocation TemplateKWLoc, |
3307 | IdentifierInfo *Name, |
3308 | SourceLocation NameLoc, |
3309 | bool EnteringContext, |
3310 | UnqualifiedId &Id, |
3311 | bool AssumeTemplateId); |
3312 | bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, |
3313 | ParsedType ObjectType, |
3314 | UnqualifiedId &Result); |
3315 | |
3316 | //===--------------------------------------------------------------------===// |
3317 | // OpenMP: Directives and clauses. |
3318 | /// Parse clauses for '#pragma omp declare simd'. |
3319 | DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, |
3320 | CachedTokens &Toks, |
3321 | SourceLocation Loc); |
3322 | |
3323 | /// Parse a property kind into \p TIProperty for the selector set \p Set and |
3324 | /// selector \p Selector. |
3325 | void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, |
3326 | llvm::omp::TraitSet Set, |
3327 | llvm::omp::TraitSelector Selector, |
3328 | llvm::StringMap<SourceLocation> &Seen); |
3329 | |
3330 | /// Parse a selector kind into \p TISelector for the selector set \p Set. |
3331 | void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, |
3332 | llvm::omp::TraitSet Set, |
3333 | llvm::StringMap<SourceLocation> &Seen); |
3334 | |
3335 | /// Parse a selector set kind into \p TISet. |
3336 | void parseOMPTraitSetKind(OMPTraitSet &TISet, |
3337 | llvm::StringMap<SourceLocation> &Seen); |
3338 | |
3339 | /// Parses an OpenMP context property. |
3340 | void parseOMPContextProperty(OMPTraitSelector &TISelector, |
3341 | llvm::omp::TraitSet Set, |
3342 | llvm::StringMap<SourceLocation> &Seen); |
3343 | |
3344 | /// Parses an OpenMP context selector. |
3345 | void parseOMPContextSelector(OMPTraitSelector &TISelector, |
3346 | llvm::omp::TraitSet Set, |
3347 | llvm::StringMap<SourceLocation> &SeenSelectors); |
3348 | |
3349 | /// Parses an OpenMP context selector set. |
3350 | void parseOMPContextSelectorSet(OMPTraitSet &TISet, |
3351 | llvm::StringMap<SourceLocation> &SeenSets); |
3352 | |
3353 | /// Parses OpenMP context selectors. |
3354 | bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); |
3355 | |
3356 | /// Parse an 'append_args' clause for '#pragma omp declare variant'. |
3357 | bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos); |
3358 | |
3359 | /// Parse a `match` clause for an '#pragma omp declare variant'. Return true |
3360 | /// if there was an error. |
3361 | bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI, |
3362 | OMPTraitInfo *ParentTI); |
3363 | |
3364 | /// Parse clauses for '#pragma omp declare variant'. |
3365 | void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, |
3366 | SourceLocation Loc); |
3367 | |
3368 | /// Parse 'omp [begin] assume[s]' directive. |
3369 | void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind, |
3370 | SourceLocation Loc); |
3371 | |
3372 | /// Parse 'omp end assumes' directive. |
3373 | void ParseOpenMPEndAssumesDirective(SourceLocation Loc); |
3374 | |
3375 | /// Parses clauses for directive. |
3376 | /// |
3377 | /// \param DKind Kind of current directive. |
3378 | /// \param clauses for current directive. |
3379 | /// \param start location for clauses of current directive |
3380 | void ParseOpenMPClauses(OpenMPDirectiveKind DKind, |
3381 | SmallVectorImpl<clang::OMPClause *> &Clauses, |
3382 | SourceLocation Loc); |
3383 | |
3384 | /// Parse clauses for '#pragma omp [begin] declare target'. |
3385 | void ParseOMPDeclareTargetClauses(Sema::DeclareTargetContextInfo &DTCI); |
3386 | |
3387 | /// Parse '#pragma omp end declare target'. |
3388 | void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind, |
3389 | OpenMPDirectiveKind EndDKind, |
3390 | SourceLocation Loc); |
3391 | |
3392 | /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if |
3393 | /// it is not the current token. |
3394 | void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); |
3395 | |
3396 | /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error |
3397 | /// that the "end" matching the "begin" directive of kind \p BeginKind was not |
3398 | /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd |
3399 | /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. |
3400 | void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, |
3401 | OpenMPDirectiveKind ExpectedKind, |
3402 | OpenMPDirectiveKind FoundKind, |
3403 | SourceLocation MatchingLoc, |
3404 | SourceLocation FoundLoc, |
3405 | bool SkipUntilOpenMPEnd); |
3406 | |
3407 | /// Parses declarative OpenMP directives. |
3408 | DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( |
3409 | AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false, |
3410 | DeclSpec::TST TagType = DeclSpec::TST_unspecified, |
3411 | Decl *TagDecl = nullptr); |
3412 | /// Parse 'omp declare reduction' construct. |
3413 | DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); |
3414 | /// Parses initializer for provided omp_priv declaration inside the reduction |
3415 | /// initializer. |
3416 | void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); |
3417 | |
3418 | /// Parses 'omp declare mapper' directive. |
3419 | DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); |
3420 | /// Parses variable declaration in 'omp declare mapper' directive. |
3421 | TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, |
3422 | DeclarationName &Name, |
3423 | AccessSpecifier AS = AS_none); |
3424 | |
3425 | /// Tries to parse cast part of OpenMP array shaping operation: |
3426 | /// '[' expression ']' { '[' expression ']' } ')'. |
3427 | bool tryParseOpenMPArrayShapingCastPart(); |
3428 | |
3429 | /// Parses simple list of variables. |
3430 | /// |
3431 | /// \param Kind Kind of the directive. |
3432 | /// \param Callback Callback function to be called for the list elements. |
3433 | /// \param AllowScopeSpecifier true, if the variables can have fully |
3434 | /// qualified names. |
3435 | /// |
3436 | bool ParseOpenMPSimpleVarList( |
3437 | OpenMPDirectiveKind Kind, |
3438 | const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & |
3439 | Callback, |
3440 | bool AllowScopeSpecifier); |
3441 | /// Parses declarative or executable directive. |
3442 | /// |
3443 | /// \param StmtCtx The context in which we're parsing the directive. |
3444 | /// \param ReadDirectiveWithinMetadirective true if directive is within a |
3445 | /// metadirective and therefore ends on the closing paren. |
3446 | StmtResult ParseOpenMPDeclarativeOrExecutableDirective( |
3447 | ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false); |
3448 | /// Parses clause of kind \a CKind for directive of a kind \a Kind. |
3449 | /// |
3450 | /// \param DKind Kind of current directive. |
3451 | /// \param CKind Kind of current clause. |
3452 | /// \param FirstClause true, if this is the first clause of a kind \a CKind |
3453 | /// in current directive. |
3454 | /// |
3455 | OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, |
3456 | OpenMPClauseKind CKind, bool FirstClause); |
3457 | /// Parses clause with a single expression of a kind \a Kind. |
3458 | /// |
3459 | /// \param Kind Kind of current clause. |
3460 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3461 | /// nullptr. |
3462 | /// |
3463 | OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, |
3464 | bool ParseOnly); |
3465 | /// Parses simple clause of a kind \a Kind. |
3466 | /// |
3467 | /// \param Kind Kind of current clause. |
3468 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3469 | /// nullptr. |
3470 | /// |
3471 | OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); |
3472 | /// Parses indirect clause |
3473 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3474 | // false; |
3475 | bool ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI, |
3476 | bool ParseOnly); |
3477 | /// Parses clause with a single expression and an additional argument |
3478 | /// of a kind \a Kind. |
3479 | /// |
3480 | /// \param DKind Directive kind. |
3481 | /// \param Kind Kind of current clause. |
3482 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3483 | /// nullptr. |
3484 | /// |
3485 | OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, |
3486 | OpenMPClauseKind Kind, |
3487 | bool ParseOnly); |
3488 | |
3489 | /// Parses the 'sizes' clause of a '#pragma omp tile' directive. |
3490 | OMPClause *ParseOpenMPSizesClause(); |
3491 | |
3492 | /// Parses clause without any additional arguments. |
3493 | /// |
3494 | /// \param Kind Kind of current clause. |
3495 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3496 | /// nullptr. |
3497 | /// |
3498 | OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); |
3499 | /// Parses clause with the list of variables of a kind \a Kind. |
3500 | /// |
3501 | /// \param Kind Kind of current clause. |
3502 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3503 | /// nullptr. |
3504 | /// |
3505 | OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, |
3506 | OpenMPClauseKind Kind, bool ParseOnly); |
3507 | |
3508 | /// Parses and creates OpenMP 5.0 iterators expression: |
3509 | /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = |
3510 | /// <range-specification> }+ ')' |
3511 | ExprResult ParseOpenMPIteratorsExpr(); |
3512 | |
3513 | /// Parses allocators and traits in the context of the uses_allocator clause. |
3514 | /// Expected format: |
3515 | /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' |
3516 | OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); |
3517 | |
3518 | /// Parses the 'interop' parts of the 'append_args' and 'init' clauses. |
3519 | bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind); |
3520 | |
3521 | /// Parses clause with an interop variable of kind \a Kind. |
3522 | /// |
3523 | /// \param Kind Kind of current clause. |
3524 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3525 | /// nullptr. |
3526 | // |
3527 | OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly); |
3528 | |
3529 | /// Parses a ompx_attribute clause |
3530 | /// |
3531 | /// \param ParseOnly true to skip the clause's semantic actions and return |
3532 | /// nullptr. |
3533 | // |
3534 | OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly); |
3535 | |
3536 | public: |
3537 | /// Parses simple expression in parens for single-expression clauses of OpenMP |
3538 | /// constructs. |
3539 | /// \param RLoc Returned location of right paren. |
3540 | ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, |
3541 | bool IsAddressOfOperand = false); |
3542 | |
3543 | /// Parses a reserved locator like 'omp_all_memory'. |
3544 | bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind, |
3545 | Sema::OpenMPVarListDataTy &Data, |
3546 | const LangOptions &LangOpts); |
3547 | /// Parses clauses with list. |
3548 | bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, |
3549 | SmallVectorImpl<Expr *> &Vars, |
3550 | Sema::OpenMPVarListDataTy &Data); |
3551 | bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, |
3552 | bool ObjectHadErrors, bool EnteringContext, |
3553 | bool AllowDestructorName, bool AllowConstructorName, |
3554 | bool AllowDeductionGuide, |
3555 | SourceLocation *TemplateKWLoc, UnqualifiedId &Result); |
3556 | |
3557 | /// Parses the mapper modifier in map, to, and from clauses. |
3558 | bool parseMapperModifier(Sema::OpenMPVarListDataTy &Data); |
3559 | /// Parses map-type-modifiers in map clause. |
3560 | /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) |
3561 | /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
3562 | bool parseMapTypeModifiers(Sema::OpenMPVarListDataTy &Data); |
3563 | |
3564 | //===--------------------------------------------------------------------===// |
3565 | // OpenACC Parsing. |
3566 | |
3567 | /// Placeholder for now, should just ignore the directives after emitting a |
3568 | /// diagnostic. Eventually will be split into a few functions to parse |
3569 | /// different situations. |
3570 | public: |
3571 | DeclGroupPtrTy ParseOpenACCDirectiveDecl(); |
3572 | StmtResult ParseOpenACCDirectiveStmt(); |
3573 | |
3574 | private: |
3575 | void ParseOpenACCDirective(); |
3576 | /// Helper that parses an ID Expression based on the language options. |
3577 | ExprResult ParseOpenACCIDExpression(); |
3578 | /// Parses the variable list for the `cache` construct. |
3579 | void ParseOpenACCCacheVarList(); |
3580 | /// Parses a single variable in a variable list for OpenACC. |
3581 | bool ParseOpenACCVar(); |
3582 | /// Parses the variable list for the variety of clauses that take a var-list, |
3583 | /// including the optional Special Token listed for some,based on clause type. |
3584 | bool ParseOpenACCClauseVarList(OpenACCClauseKind Kind); |
3585 | /// Parses any parameters for an OpenACC Clause, including required/optional |
3586 | /// parens. |
3587 | bool ParseOpenACCClauseParams(OpenACCDirectiveKind DirKind, |
3588 | OpenACCClauseKind Kind); |
3589 | /// Parses a single clause in a clause-list for OpenACC. |
3590 | bool ParseOpenACCClause(OpenACCDirectiveKind DirKind); |
3591 | /// Parses the clause-list for an OpenACC directive. |
3592 | void ParseOpenACCClauseList(OpenACCDirectiveKind DirKind); |
3593 | bool ParseOpenACCWaitArgument(); |
3594 | /// Parses the clause of the 'bind' argument, which can be a string literal or |
3595 | /// an ID expression. |
3596 | ExprResult ParseOpenACCBindClauseArgument(); |
3597 | /// Parses the clause kind of 'int-expr', which can be any integral |
3598 | /// expression. |
3599 | ExprResult ParseOpenACCIntExpr(); |
3600 | /// Parses the 'device-type-list', which is a list of identifiers. |
3601 | bool ParseOpenACCDeviceTypeList(); |
3602 | /// Parses the 'async-argument', which is an integral value with two |
3603 | /// 'special' values that are likely negative (but come from Macros). |
3604 | ExprResult ParseOpenACCAsyncArgument(); |
3605 | /// Parses the 'size-expr', which is an integral value, or an asterisk. |
3606 | bool ParseOpenACCSizeExpr(); |
3607 | /// Parses a comma delimited list of 'size-expr's. |
3608 | bool ParseOpenACCSizeExprList(); |
3609 | /// Parses a 'gang-arg-list', used for the 'gang' clause. |
3610 | bool ParseOpenACCGangArgList(); |
3611 | /// Parses a 'gang-arg', used for the 'gang' clause. |
3612 | bool ParseOpenACCGangArg(); |
3613 | |
3614 | private: |
3615 | //===--------------------------------------------------------------------===// |
3616 | // C++ 14: Templates [temp] |
3617 | |
3618 | // C++ 14.1: Template Parameters [temp.param] |
3619 | DeclGroupPtrTy |
3620 | ParseDeclarationStartingWithTemplate(DeclaratorContext Context, |
3621 | SourceLocation &DeclEnd, |
3622 | ParsedAttributes &AccessAttrs); |
3623 | DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization( |
3624 | DeclaratorContext Context, SourceLocation &DeclEnd, |
3625 | ParsedAttributes &AccessAttrs, AccessSpecifier AS); |
3626 | DeclGroupPtrTy ParseDeclarationAfterTemplate( |
3627 | DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo, |
3628 | ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, |
3629 | ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); |
3630 | bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth, |
3631 | SmallVectorImpl<NamedDecl *> &TemplateParams, |
3632 | SourceLocation &LAngleLoc, |
3633 | SourceLocation &RAngleLoc); |
3634 | bool ParseTemplateParameterList(unsigned Depth, |
3635 | SmallVectorImpl<NamedDecl*> &TemplateParams); |
3636 | TPResult isStartOfTemplateTypeParameter(); |
3637 | NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); |
3638 | NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); |
3639 | NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); |
3640 | NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); |
3641 | bool isTypeConstraintAnnotation(); |
3642 | bool TryAnnotateTypeConstraint(); |
3643 | void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, |
3644 | SourceLocation CorrectLoc, |
3645 | bool AlreadyHasEllipsis, |
3646 | bool IdentifierHasName); |
3647 | void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, |
3648 | Declarator &D); |
3649 | // C++ 14.3: Template arguments [temp.arg] |
3650 | typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; |
3651 | |
3652 | bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, |
3653 | SourceLocation &RAngleLoc, |
3654 | bool ConsumeLastToken, |
3655 | bool ObjCGenericList); |
3656 | bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, |
3657 | SourceLocation &LAngleLoc, |
3658 | TemplateArgList &TemplateArgs, |
3659 | SourceLocation &RAngleLoc, |
3660 | TemplateTy NameHint = nullptr); |
3661 | |
3662 | bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, |
3663 | CXXScopeSpec &SS, |
3664 | SourceLocation TemplateKWLoc, |
3665 | UnqualifiedId &TemplateName, |
3666 | bool AllowTypeAnnotation = true, |
3667 | bool TypeConstraint = false); |
3668 | void |
3669 | AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, |
3670 | ImplicitTypenameContext AllowImplicitTypename, |
3671 | bool IsClassName = false); |
3672 | bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs, |
3673 | TemplateTy Template, SourceLocation OpenLoc); |
3674 | ParsedTemplateArgument ParseTemplateTemplateArgument(); |
3675 | ParsedTemplateArgument ParseTemplateArgument(); |
3676 | DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context, |
3677 | SourceLocation ExternLoc, |
3678 | SourceLocation TemplateLoc, |
3679 | SourceLocation &DeclEnd, |
3680 | ParsedAttributes &AccessAttrs, |
3681 | AccessSpecifier AS = AS_none); |
3682 | // C++2a: Template, concept definition [temp] |
3683 | Decl * |
3684 | ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, |
3685 | SourceLocation &DeclEnd); |
3686 | |
3687 | /// Parse the given string as a type. |
3688 | /// |
3689 | /// This is a dangerous utility function currently employed only by API notes. |
3690 | /// It is not a general entry-point for safely parsing types from strings. |
3691 | /// |
3692 | /// \param TypeStr The string to be parsed as a type. |
3693 | /// \param Context The name of the context in which this string is being |
3694 | /// parsed, which will be used in diagnostics. |
3695 | /// \param IncludeLoc The location at which this parse was triggered. |
3696 | TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context, |
3697 | SourceLocation IncludeLoc); |
3698 | |
3699 | //===--------------------------------------------------------------------===// |
3700 | // Modules |
3701 | DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState); |
3702 | Decl *ParseModuleImport(SourceLocation AtLoc, |
3703 | Sema::ModuleImportState &ImportState); |
3704 | bool parseMisplacedModuleImport(); |
3705 | bool tryParseMisplacedModuleImport() { |
3706 | tok::TokenKind Kind = Tok.getKind(); |
3707 | if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || |
3708 | Kind == tok::annot_module_include) |
3709 | return parseMisplacedModuleImport(); |
3710 | return false; |
3711 | } |
3712 | |
3713 | bool ParseModuleName( |
3714 | SourceLocation UseLoc, |
3715 | SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, |
3716 | bool IsImport); |
3717 | |
3718 | //===--------------------------------------------------------------------===// |
3719 | // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] |
3720 | ExprResult ParseTypeTrait(); |
3721 | |
3722 | //===--------------------------------------------------------------------===// |
3723 | // Embarcadero: Arary and Expression Traits |
3724 | ExprResult ParseArrayTypeTrait(); |
3725 | ExprResult ParseExpressionTrait(); |
3726 | |
3727 | //===--------------------------------------------------------------------===// |
3728 | // Preprocessor code-completion pass-through |
3729 | void CodeCompleteDirective(bool InConditional) override; |
3730 | void CodeCompleteInConditionalExclusion() override; |
3731 | void CodeCompleteMacroName(bool IsDefinition) override; |
3732 | void CodeCompletePreprocessorExpression() override; |
3733 | void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, |
3734 | unsigned ArgumentIndex) override; |
3735 | void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; |
3736 | void CodeCompleteNaturalLanguage() override; |
3737 | |
3738 | class GNUAsmQualifiers { |
3739 | unsigned Qualifiers = AQ_unspecified; |
3740 | |
3741 | public: |
3742 | enum AQ { |
3743 | AQ_unspecified = 0, |
3744 | AQ_volatile = 1, |
3745 | AQ_inline = 2, |
3746 | AQ_goto = 4, |
3747 | }; |
3748 | static const char *getQualifierName(AQ Qualifier); |
3749 | bool setAsmQualifier(AQ Qualifier); |
3750 | inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; |
3751 | inline bool isInline() const { return Qualifiers & AQ_inline; }; |
3752 | inline bool isGoto() const { return Qualifiers & AQ_goto; } |
3753 | }; |
3754 | bool isGCCAsmStatement(const Token &TokAfterAsm) const; |
3755 | bool isGNUAsmQualifier(const Token &TokAfterAsm) const; |
3756 | GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; |
3757 | bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); |
3758 | }; |
3759 | |
3760 | } // end namespace clang |
3761 | |
3762 | #endif |
3763 | |