Parser.h 146 KB

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