Parser.h 143 KB

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