TokenAnnotator.cpp 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480
  1. //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// This file implements a token annotator, i.e. creates
  11. /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TokenAnnotator.h"
  15. #include "FormatToken.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/Support/Debug.h"
  19. #define DEBUG_TYPE "format-token-annotator"
  20. namespace clang {
  21. namespace format {
  22. namespace {
  23. /// Returns \c true if the token can be used as an identifier in
  24. /// an Objective-C \c @selector, \c false otherwise.
  25. ///
  26. /// Because getFormattingLangOpts() always lexes source code as
  27. /// Objective-C++, C++ keywords like \c new and \c delete are
  28. /// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
  29. ///
  30. /// For Objective-C and Objective-C++, both identifiers and keywords
  31. /// are valid inside @selector(...) (or a macro which
  32. /// invokes @selector(...)). So, we allow treat any identifier or
  33. /// keyword as a potential Objective-C selector component.
  34. static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
  35. return Tok.Tok.getIdentifierInfo() != nullptr;
  36. }
  37. /// A parser that gathers additional information about tokens.
  38. ///
  39. /// The \c TokenAnnotator tries to match parenthesis and square brakets and
  40. /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
  41. /// into template parameter lists.
  42. class AnnotatingParser {
  43. public:
  44. AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
  45. const AdditionalKeywords &Keywords)
  46. : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
  47. Keywords(Keywords) {
  48. Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
  49. resetTokenMetadata(CurrentToken);
  50. }
  51. private:
  52. bool parseAngle() {
  53. if (!CurrentToken || !CurrentToken->Previous)
  54. return false;
  55. if (NonTemplateLess.count(CurrentToken->Previous))
  56. return false;
  57. const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
  58. if (Previous.Previous) {
  59. if (Previous.Previous->Tok.isLiteral())
  60. return false;
  61. if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
  62. (!Previous.Previous->MatchingParen ||
  63. !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
  64. return false;
  65. }
  66. FormatToken *Left = CurrentToken->Previous;
  67. Left->ParentBracket = Contexts.back().ContextKind;
  68. ScopedContextCreator ContextCreator(*this, tok::less, 12);
  69. // If this angle is in the context of an expression, we need to be more
  70. // hesitant to detect it as opening template parameters.
  71. bool InExprContext = Contexts.back().IsExpression;
  72. Contexts.back().IsExpression = false;
  73. // If there's a template keyword before the opening angle bracket, this is a
  74. // template parameter, not an argument.
  75. Contexts.back().InTemplateArgument =
  76. Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
  77. if (Style.Language == FormatStyle::LK_Java &&
  78. CurrentToken->is(tok::question))
  79. next();
  80. while (CurrentToken) {
  81. if (CurrentToken->is(tok::greater)) {
  82. Left->MatchingParen = CurrentToken;
  83. CurrentToken->MatchingParen = Left;
  84. // In TT_Proto, we must distignuish between:
  85. // map<key, value>
  86. // msg < item: data >
  87. // msg: < item: data >
  88. // In TT_TextProto, map<key, value> does not occur.
  89. if (Style.Language == FormatStyle::LK_TextProto ||
  90. (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
  91. Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
  92. CurrentToken->Type = TT_DictLiteral;
  93. else
  94. CurrentToken->Type = TT_TemplateCloser;
  95. next();
  96. return true;
  97. }
  98. if (CurrentToken->is(tok::question) &&
  99. Style.Language == FormatStyle::LK_Java) {
  100. next();
  101. continue;
  102. }
  103. if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
  104. (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
  105. Style.Language != FormatStyle::LK_Proto &&
  106. Style.Language != FormatStyle::LK_TextProto))
  107. return false;
  108. // If a && or || is found and interpreted as a binary operator, this set
  109. // of angles is likely part of something like "a < b && c > d". If the
  110. // angles are inside an expression, the ||/&& might also be a binary
  111. // operator that was misinterpreted because we are parsing template
  112. // parameters.
  113. // FIXME: This is getting out of hand, write a decent parser.
  114. if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
  115. CurrentToken->Previous->is(TT_BinaryOperator) &&
  116. Contexts[Contexts.size() - 2].IsExpression &&
  117. !Line.startsWith(tok::kw_template))
  118. return false;
  119. updateParameterCount(Left, CurrentToken);
  120. if (Style.Language == FormatStyle::LK_Proto) {
  121. if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
  122. if (CurrentToken->is(tok::colon) ||
  123. (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
  124. Previous->isNot(tok::colon)))
  125. Previous->Type = TT_SelectorName;
  126. }
  127. }
  128. if (!consumeToken())
  129. return false;
  130. }
  131. return false;
  132. }
  133. bool parseParens(bool LookForDecls = false) {
  134. if (!CurrentToken)
  135. return false;
  136. FormatToken *Left = CurrentToken->Previous;
  137. Left->ParentBracket = Contexts.back().ContextKind;
  138. ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
  139. // FIXME: This is a bit of a hack. Do better.
  140. Contexts.back().ColonIsForRangeExpr =
  141. Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
  142. bool StartsObjCMethodExpr = false;
  143. if (FormatToken *MaybeSel = Left->Previous) {
  144. // @selector( starts a selector.
  145. if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
  146. MaybeSel->Previous->is(tok::at)) {
  147. StartsObjCMethodExpr = true;
  148. }
  149. }
  150. if (Left->is(TT_OverloadedOperatorLParen)) {
  151. Contexts.back().IsExpression = false;
  152. } else if (Style.Language == FormatStyle::LK_JavaScript &&
  153. (Line.startsWith(Keywords.kw_type, tok::identifier) ||
  154. Line.startsWith(tok::kw_export, Keywords.kw_type,
  155. tok::identifier))) {
  156. // type X = (...);
  157. // export type X = (...);
  158. Contexts.back().IsExpression = false;
  159. } else if (Left->Previous &&
  160. (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
  161. tok::kw_if, tok::kw_while, tok::l_paren,
  162. tok::comma) ||
  163. Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
  164. Left->Previous->is(TT_BinaryOperator))) {
  165. // static_assert, if and while usually contain expressions.
  166. Contexts.back().IsExpression = true;
  167. } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
  168. (Left->Previous->is(Keywords.kw_function) ||
  169. (Left->Previous->endsSequence(tok::identifier,
  170. Keywords.kw_function)))) {
  171. // function(...) or function f(...)
  172. Contexts.back().IsExpression = false;
  173. } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
  174. Left->Previous->is(TT_JsTypeColon)) {
  175. // let x: (SomeType);
  176. Contexts.back().IsExpression = false;
  177. } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
  178. Left->Previous->MatchingParen &&
  179. Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
  180. // This is a parameter list of a lambda expression.
  181. Contexts.back().IsExpression = false;
  182. } else if (Line.InPPDirective &&
  183. (!Left->Previous || !Left->Previous->is(tok::identifier))) {
  184. Contexts.back().IsExpression = true;
  185. } else if (Contexts[Contexts.size() - 2].CaretFound) {
  186. // This is the parameter list of an ObjC block.
  187. Contexts.back().IsExpression = false;
  188. } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
  189. Left->Type = TT_AttributeParen;
  190. } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
  191. // The first argument to a foreach macro is a declaration.
  192. Contexts.back().IsForEachMacro = true;
  193. Contexts.back().IsExpression = false;
  194. } else if (Left->Previous && Left->Previous->MatchingParen &&
  195. Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
  196. Contexts.back().IsExpression = false;
  197. } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
  198. bool IsForOrCatch =
  199. Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
  200. Contexts.back().IsExpression = !IsForOrCatch;
  201. }
  202. if (StartsObjCMethodExpr) {
  203. Contexts.back().ColonIsObjCMethodExpr = true;
  204. Left->Type = TT_ObjCMethodExpr;
  205. }
  206. // MightBeFunctionType and ProbablyFunctionType are used for
  207. // function pointer and reference types as well as Objective-C
  208. // block types:
  209. //
  210. // void (*FunctionPointer)(void);
  211. // void (&FunctionReference)(void);
  212. // void (^ObjCBlock)(void);
  213. bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
  214. bool ProbablyFunctionType =
  215. CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
  216. bool HasMultipleLines = false;
  217. bool HasMultipleParametersOnALine = false;
  218. bool MightBeObjCForRangeLoop =
  219. Left->Previous && Left->Previous->is(tok::kw_for);
  220. FormatToken *PossibleObjCForInToken = nullptr;
  221. while (CurrentToken) {
  222. // LookForDecls is set when "if (" has been seen. Check for
  223. // 'identifier' '*' 'identifier' followed by not '=' -- this
  224. // '*' has to be a binary operator but determineStarAmpUsage() will
  225. // categorize it as an unary operator, so set the right type here.
  226. if (LookForDecls && CurrentToken->Next) {
  227. FormatToken *Prev = CurrentToken->getPreviousNonComment();
  228. if (Prev) {
  229. FormatToken *PrevPrev = Prev->getPreviousNonComment();
  230. FormatToken *Next = CurrentToken->Next;
  231. if (PrevPrev && PrevPrev->is(tok::identifier) &&
  232. Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
  233. CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
  234. Prev->Type = TT_BinaryOperator;
  235. LookForDecls = false;
  236. }
  237. }
  238. }
  239. if (CurrentToken->Previous->is(TT_PointerOrReference) &&
  240. CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
  241. tok::coloncolon))
  242. ProbablyFunctionType = true;
  243. if (CurrentToken->is(tok::comma))
  244. MightBeFunctionType = false;
  245. if (CurrentToken->Previous->is(TT_BinaryOperator))
  246. Contexts.back().IsExpression = true;
  247. if (CurrentToken->is(tok::r_paren)) {
  248. if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
  249. (CurrentToken->Next->is(tok::l_paren) ||
  250. (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
  251. Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
  252. : TT_FunctionTypeLParen;
  253. Left->MatchingParen = CurrentToken;
  254. CurrentToken->MatchingParen = Left;
  255. if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
  256. Left->Previous && Left->Previous->is(tok::l_paren)) {
  257. // Detect the case where macros are used to generate lambdas or
  258. // function bodies, e.g.:
  259. // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
  260. for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
  261. if (Tok->is(TT_BinaryOperator) &&
  262. Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
  263. Tok->Type = TT_PointerOrReference;
  264. }
  265. }
  266. if (StartsObjCMethodExpr) {
  267. CurrentToken->Type = TT_ObjCMethodExpr;
  268. if (Contexts.back().FirstObjCSelectorName) {
  269. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
  270. Contexts.back().LongestObjCSelectorName;
  271. }
  272. }
  273. if (Left->is(TT_AttributeParen))
  274. CurrentToken->Type = TT_AttributeParen;
  275. if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
  276. CurrentToken->Type = TT_JavaAnnotation;
  277. if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
  278. CurrentToken->Type = TT_LeadingJavaAnnotation;
  279. if (Left->Previous && Left->Previous->is(TT_AttributeSquare))
  280. CurrentToken->Type = TT_AttributeSquare;
  281. if (!HasMultipleLines)
  282. Left->PackingKind = PPK_Inconclusive;
  283. else if (HasMultipleParametersOnALine)
  284. Left->PackingKind = PPK_BinPacked;
  285. else
  286. Left->PackingKind = PPK_OnePerLine;
  287. next();
  288. return true;
  289. }
  290. if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
  291. return false;
  292. if (CurrentToken->is(tok::l_brace))
  293. Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
  294. if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
  295. !CurrentToken->Next->HasUnescapedNewline &&
  296. !CurrentToken->Next->isTrailingComment())
  297. HasMultipleParametersOnALine = true;
  298. if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
  299. CurrentToken->Previous->isSimpleTypeSpecifier()) &&
  300. !CurrentToken->is(tok::l_brace))
  301. Contexts.back().IsExpression = false;
  302. if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
  303. MightBeObjCForRangeLoop = false;
  304. if (PossibleObjCForInToken) {
  305. PossibleObjCForInToken->Type = TT_Unknown;
  306. PossibleObjCForInToken = nullptr;
  307. }
  308. }
  309. if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
  310. PossibleObjCForInToken = CurrentToken;
  311. PossibleObjCForInToken->Type = TT_ObjCForIn;
  312. }
  313. // When we discover a 'new', we set CanBeExpression to 'false' in order to
  314. // parse the type correctly. Reset that after a comma.
  315. if (CurrentToken->is(tok::comma))
  316. Contexts.back().CanBeExpression = true;
  317. FormatToken *Tok = CurrentToken;
  318. if (!consumeToken())
  319. return false;
  320. updateParameterCount(Left, Tok);
  321. if (CurrentToken && CurrentToken->HasUnescapedNewline)
  322. HasMultipleLines = true;
  323. }
  324. return false;
  325. }
  326. bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
  327. if (!Style.isCSharp())
  328. return false;
  329. const FormatToken *AttrTok = Tok.Next;
  330. if (!AttrTok)
  331. return false;
  332. // Just an empty declaration e.g. string [].
  333. if (AttrTok->is(tok::r_square))
  334. return false;
  335. // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
  336. while (AttrTok && AttrTok->isNot(tok::r_square)) {
  337. AttrTok = AttrTok->Next;
  338. }
  339. if (!AttrTok)
  340. return false;
  341. // Move past the end of ']'.
  342. AttrTok = AttrTok->Next;
  343. if (!AttrTok)
  344. return false;
  345. // Limit this to being an access modifier that follows.
  346. if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
  347. tok::kw_class, tok::kw_static, tok::l_square,
  348. Keywords.kw_internal)) {
  349. return true;
  350. }
  351. return false;
  352. }
  353. bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
  354. if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
  355. return false;
  356. const FormatToken *AttrTok = Tok.Next->Next;
  357. if (!AttrTok)
  358. return false;
  359. // C++17 '[[using ns: foo, bar(baz, blech)]]'
  360. // We assume nobody will name an ObjC variable 'using'.
  361. if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
  362. return true;
  363. if (AttrTok->isNot(tok::identifier))
  364. return false;
  365. while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
  366. // ObjC message send. We assume nobody will use : in a C++11 attribute
  367. // specifier parameter, although this is technically valid:
  368. // [[foo(:)]]
  369. if (AttrTok->is(tok::colon) ||
  370. AttrTok->startsSequence(tok::identifier, tok::identifier) ||
  371. AttrTok->startsSequence(tok::r_paren, tok::identifier))
  372. return false;
  373. if (AttrTok->is(tok::ellipsis))
  374. return true;
  375. AttrTok = AttrTok->Next;
  376. }
  377. return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
  378. }
  379. bool parseSquare() {
  380. if (!CurrentToken)
  381. return false;
  382. // A '[' could be an index subscript (after an identifier or after
  383. // ')' or ']'), it could be the start of an Objective-C method
  384. // expression, it could the start of an Objective-C array literal,
  385. // or it could be a C++ attribute specifier [[foo::bar]].
  386. FormatToken *Left = CurrentToken->Previous;
  387. Left->ParentBracket = Contexts.back().ContextKind;
  388. FormatToken *Parent = Left->getPreviousNonComment();
  389. // Cases where '>' is followed by '['.
  390. // In C++, this can happen either in array of templates (foo<int>[10])
  391. // or when array is a nested template type (unique_ptr<type1<type2>[]>).
  392. bool CppArrayTemplates =
  393. Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
  394. (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
  395. Contexts.back().InTemplateArgument);
  396. bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
  397. Contexts.back().InCpp11AttributeSpecifier;
  398. // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
  399. bool IsCSharp11AttributeSpecifier =
  400. isCSharpAttributeSpecifier(*Left) ||
  401. Contexts.back().InCSharpAttributeSpecifier;
  402. bool InsideInlineASM = Line.startsWith(tok::kw_asm);
  403. bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
  404. bool StartsObjCMethodExpr =
  405. !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
  406. Style.isCpp() && !IsCpp11AttributeSpecifier &&
  407. Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
  408. !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
  409. (!Parent ||
  410. Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
  411. tok::kw_return, tok::kw_throw) ||
  412. Parent->isUnaryOperator() ||
  413. // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  414. Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
  415. (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
  416. prec::Unknown));
  417. bool ColonFound = false;
  418. unsigned BindingIncrease = 1;
  419. if (IsCppStructuredBinding) {
  420. Left->Type = TT_StructuredBindingLSquare;
  421. } else if (Left->is(TT_Unknown)) {
  422. if (StartsObjCMethodExpr) {
  423. Left->Type = TT_ObjCMethodExpr;
  424. } else if (IsCpp11AttributeSpecifier) {
  425. Left->Type = TT_AttributeSquare;
  426. } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  427. Contexts.back().ContextKind == tok::l_brace &&
  428. Parent->isOneOf(tok::l_brace, tok::comma)) {
  429. Left->Type = TT_JsComputedPropertyName;
  430. } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
  431. Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
  432. Left->Type = TT_DesignatedInitializerLSquare;
  433. } else if (CurrentToken->is(tok::r_square) && Parent &&
  434. Parent->is(TT_TemplateCloser)) {
  435. Left->Type = TT_ArraySubscriptLSquare;
  436. } else if (Style.Language == FormatStyle::LK_Proto ||
  437. Style.Language == FormatStyle::LK_TextProto) {
  438. // Square braces in LK_Proto can either be message field attributes:
  439. //
  440. // optional Aaa aaa = 1 [
  441. // (aaa) = aaa
  442. // ];
  443. //
  444. // extensions 123 [
  445. // (aaa) = aaa
  446. // ];
  447. //
  448. // or text proto extensions (in options):
  449. //
  450. // option (Aaa.options) = {
  451. // [type.type/type] {
  452. // key: value
  453. // }
  454. // }
  455. //
  456. // or repeated fields (in options):
  457. //
  458. // option (Aaa.options) = {
  459. // keys: [ 1, 2, 3 ]
  460. // }
  461. //
  462. // In the first and the third case we want to spread the contents inside
  463. // the square braces; in the second we want to keep them inline.
  464. Left->Type = TT_ArrayInitializerLSquare;
  465. if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
  466. tok::equal) &&
  467. !Left->endsSequence(tok::l_square, tok::numeric_constant,
  468. tok::identifier) &&
  469. !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
  470. Left->Type = TT_ProtoExtensionLSquare;
  471. BindingIncrease = 10;
  472. }
  473. } else if (!CppArrayTemplates && Parent &&
  474. Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
  475. tok::comma, tok::l_paren, tok::l_square,
  476. tok::question, tok::colon, tok::kw_return,
  477. // Should only be relevant to JavaScript:
  478. tok::kw_default)) {
  479. Left->Type = TT_ArrayInitializerLSquare;
  480. } else if (IsCSharp11AttributeSpecifier) {
  481. Left->Type = TT_AttributeSquare;
  482. } else {
  483. BindingIncrease = 10;
  484. Left->Type = TT_ArraySubscriptLSquare;
  485. }
  486. }
  487. ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
  488. Contexts.back().IsExpression = true;
  489. if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  490. Parent->is(TT_JsTypeColon))
  491. Contexts.back().IsExpression = false;
  492. Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
  493. Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
  494. Contexts.back().InCSharpAttributeSpecifier = IsCSharp11AttributeSpecifier;
  495. while (CurrentToken) {
  496. if (CurrentToken->is(tok::r_square)) {
  497. if (IsCpp11AttributeSpecifier)
  498. CurrentToken->Type = TT_AttributeSquare;
  499. if (IsCSharp11AttributeSpecifier)
  500. CurrentToken->Type = TT_AttributeSquare;
  501. else if (((CurrentToken->Next &&
  502. CurrentToken->Next->is(tok::l_paren)) ||
  503. (CurrentToken->Previous &&
  504. CurrentToken->Previous->Previous == Left)) &&
  505. Left->is(TT_ObjCMethodExpr)) {
  506. // An ObjC method call is rarely followed by an open parenthesis. It
  507. // also can't be composed of just one token, unless it's a macro that
  508. // will be expanded to more tokens.
  509. // FIXME: Do we incorrectly label ":" with this?
  510. StartsObjCMethodExpr = false;
  511. Left->Type = TT_Unknown;
  512. }
  513. if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
  514. CurrentToken->Type = TT_ObjCMethodExpr;
  515. // If we haven't seen a colon yet, make sure the last identifier
  516. // before the r_square is tagged as a selector name component.
  517. if (!ColonFound && CurrentToken->Previous &&
  518. CurrentToken->Previous->is(TT_Unknown) &&
  519. canBeObjCSelectorComponent(*CurrentToken->Previous))
  520. CurrentToken->Previous->Type = TT_SelectorName;
  521. // determineStarAmpUsage() thinks that '*' '[' is allocating an
  522. // array of pointers, but if '[' starts a selector then '*' is a
  523. // binary operator.
  524. if (Parent && Parent->is(TT_PointerOrReference))
  525. Parent->Type = TT_BinaryOperator;
  526. }
  527. // An arrow after an ObjC method expression is not a lambda arrow.
  528. if (CurrentToken->Type == TT_ObjCMethodExpr && CurrentToken->Next &&
  529. CurrentToken->Next->is(TT_LambdaArrow))
  530. CurrentToken->Next->Type = TT_Unknown;
  531. Left->MatchingParen = CurrentToken;
  532. CurrentToken->MatchingParen = Left;
  533. // FirstObjCSelectorName is set when a colon is found. This does
  534. // not work, however, when the method has no parameters.
  535. // Here, we set FirstObjCSelectorName when the end of the method call is
  536. // reached, in case it was not set already.
  537. if (!Contexts.back().FirstObjCSelectorName) {
  538. FormatToken *Previous = CurrentToken->getPreviousNonComment();
  539. if (Previous && Previous->is(TT_SelectorName)) {
  540. Previous->ObjCSelectorNameParts = 1;
  541. Contexts.back().FirstObjCSelectorName = Previous;
  542. }
  543. } else {
  544. Left->ParameterCount =
  545. Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
  546. }
  547. if (Contexts.back().FirstObjCSelectorName) {
  548. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
  549. Contexts.back().LongestObjCSelectorName;
  550. if (Left->BlockParameterCount > 1)
  551. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
  552. }
  553. next();
  554. return true;
  555. }
  556. if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
  557. return false;
  558. if (CurrentToken->is(tok::colon)) {
  559. if (IsCpp11AttributeSpecifier &&
  560. CurrentToken->endsSequence(tok::colon, tok::identifier,
  561. tok::kw_using)) {
  562. // Remember that this is a [[using ns: foo]] C++ attribute, so we
  563. // don't add a space before the colon (unlike other colons).
  564. CurrentToken->Type = TT_AttributeColon;
  565. } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
  566. TT_DesignatedInitializerLSquare)) {
  567. Left->Type = TT_ObjCMethodExpr;
  568. StartsObjCMethodExpr = true;
  569. Contexts.back().ColonIsObjCMethodExpr = true;
  570. if (Parent && Parent->is(tok::r_paren))
  571. // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  572. Parent->Type = TT_CastRParen;
  573. }
  574. ColonFound = true;
  575. }
  576. if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
  577. !ColonFound)
  578. Left->Type = TT_ArrayInitializerLSquare;
  579. FormatToken *Tok = CurrentToken;
  580. if (!consumeToken())
  581. return false;
  582. updateParameterCount(Left, Tok);
  583. }
  584. return false;
  585. }
  586. bool parseBrace() {
  587. if (CurrentToken) {
  588. FormatToken *Left = CurrentToken->Previous;
  589. Left->ParentBracket = Contexts.back().ContextKind;
  590. if (Contexts.back().CaretFound)
  591. Left->Type = TT_ObjCBlockLBrace;
  592. Contexts.back().CaretFound = false;
  593. ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
  594. Contexts.back().ColonIsDictLiteral = true;
  595. if (Left->BlockKind == BK_BracedInit)
  596. Contexts.back().IsExpression = true;
  597. if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
  598. Left->Previous->is(TT_JsTypeColon))
  599. Contexts.back().IsExpression = false;
  600. while (CurrentToken) {
  601. if (CurrentToken->is(tok::r_brace)) {
  602. Left->MatchingParen = CurrentToken;
  603. CurrentToken->MatchingParen = Left;
  604. next();
  605. return true;
  606. }
  607. if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
  608. return false;
  609. updateParameterCount(Left, CurrentToken);
  610. if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
  611. FormatToken *Previous = CurrentToken->getPreviousNonComment();
  612. if (Previous->is(TT_JsTypeOptionalQuestion))
  613. Previous = Previous->getPreviousNonComment();
  614. if ((CurrentToken->is(tok::colon) &&
  615. (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
  616. Style.Language == FormatStyle::LK_Proto ||
  617. Style.Language == FormatStyle::LK_TextProto) {
  618. Left->Type = TT_DictLiteral;
  619. if (Previous->Tok.getIdentifierInfo() ||
  620. Previous->is(tok::string_literal))
  621. Previous->Type = TT_SelectorName;
  622. }
  623. if (CurrentToken->is(tok::colon) ||
  624. Style.Language == FormatStyle::LK_JavaScript)
  625. Left->Type = TT_DictLiteral;
  626. }
  627. if (CurrentToken->is(tok::comma) &&
  628. Style.Language == FormatStyle::LK_JavaScript)
  629. Left->Type = TT_DictLiteral;
  630. if (!consumeToken())
  631. return false;
  632. }
  633. }
  634. return true;
  635. }
  636. void updateParameterCount(FormatToken *Left, FormatToken *Current) {
  637. // For ObjC methods, the number of parameters is calculated differently as
  638. // method declarations have a different structure (the parameters are not
  639. // inside a bracket scope).
  640. if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
  641. ++Left->BlockParameterCount;
  642. if (Current->is(tok::comma)) {
  643. ++Left->ParameterCount;
  644. if (!Left->Role)
  645. Left->Role.reset(new CommaSeparatedList(Style));
  646. Left->Role->CommaFound(Current);
  647. } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
  648. Left->ParameterCount = 1;
  649. }
  650. }
  651. bool parseConditional() {
  652. while (CurrentToken) {
  653. if (CurrentToken->is(tok::colon)) {
  654. CurrentToken->Type = TT_ConditionalExpr;
  655. next();
  656. return true;
  657. }
  658. if (!consumeToken())
  659. return false;
  660. }
  661. return false;
  662. }
  663. bool parseTemplateDeclaration() {
  664. if (CurrentToken && CurrentToken->is(tok::less)) {
  665. CurrentToken->Type = TT_TemplateOpener;
  666. next();
  667. if (!parseAngle())
  668. return false;
  669. if (CurrentToken)
  670. CurrentToken->Previous->ClosesTemplateDeclaration = true;
  671. return true;
  672. }
  673. return false;
  674. }
  675. bool consumeToken() {
  676. FormatToken *Tok = CurrentToken;
  677. next();
  678. switch (Tok->Tok.getKind()) {
  679. case tok::plus:
  680. case tok::minus:
  681. if (!Tok->Previous && Line.MustBeDeclaration)
  682. Tok->Type = TT_ObjCMethodSpecifier;
  683. break;
  684. case tok::colon:
  685. if (!Tok->Previous)
  686. return false;
  687. // Colons from ?: are handled in parseConditional().
  688. if (Style.Language == FormatStyle::LK_JavaScript) {
  689. if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
  690. (Contexts.size() == 1 && // switch/case labels
  691. !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
  692. Contexts.back().ContextKind == tok::l_paren || // function params
  693. Contexts.back().ContextKind == tok::l_square || // array type
  694. (!Contexts.back().IsExpression &&
  695. Contexts.back().ContextKind == tok::l_brace) || // object type
  696. (Contexts.size() == 1 &&
  697. Line.MustBeDeclaration)) { // method/property declaration
  698. Contexts.back().IsExpression = false;
  699. Tok->Type = TT_JsTypeColon;
  700. break;
  701. }
  702. }
  703. if (Contexts.back().ColonIsDictLiteral ||
  704. Style.Language == FormatStyle::LK_Proto ||
  705. Style.Language == FormatStyle::LK_TextProto) {
  706. Tok->Type = TT_DictLiteral;
  707. if (Style.Language == FormatStyle::LK_TextProto) {
  708. if (FormatToken *Previous = Tok->getPreviousNonComment())
  709. Previous->Type = TT_SelectorName;
  710. }
  711. } else if (Contexts.back().ColonIsObjCMethodExpr ||
  712. Line.startsWith(TT_ObjCMethodSpecifier)) {
  713. Tok->Type = TT_ObjCMethodExpr;
  714. const FormatToken *BeforePrevious = Tok->Previous->Previous;
  715. // Ensure we tag all identifiers in method declarations as
  716. // TT_SelectorName.
  717. bool UnknownIdentifierInMethodDeclaration =
  718. Line.startsWith(TT_ObjCMethodSpecifier) &&
  719. Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
  720. if (!BeforePrevious ||
  721. // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  722. !(BeforePrevious->is(TT_CastRParen) ||
  723. (BeforePrevious->is(TT_ObjCMethodExpr) &&
  724. BeforePrevious->is(tok::colon))) ||
  725. BeforePrevious->is(tok::r_square) ||
  726. Contexts.back().LongestObjCSelectorName == 0 ||
  727. UnknownIdentifierInMethodDeclaration) {
  728. Tok->Previous->Type = TT_SelectorName;
  729. if (!Contexts.back().FirstObjCSelectorName)
  730. Contexts.back().FirstObjCSelectorName = Tok->Previous;
  731. else if (Tok->Previous->ColumnWidth >
  732. Contexts.back().LongestObjCSelectorName)
  733. Contexts.back().LongestObjCSelectorName =
  734. Tok->Previous->ColumnWidth;
  735. Tok->Previous->ParameterIndex =
  736. Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
  737. ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
  738. }
  739. } else if (Contexts.back().ColonIsForRangeExpr) {
  740. Tok->Type = TT_RangeBasedForLoopColon;
  741. } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
  742. Tok->Type = TT_BitFieldColon;
  743. } else if (Contexts.size() == 1 &&
  744. !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
  745. if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
  746. tok::kw_noexcept))
  747. Tok->Type = TT_CtorInitializerColon;
  748. else
  749. Tok->Type = TT_InheritanceColon;
  750. } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
  751. (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
  752. (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
  753. Tok->Next->Next->is(tok::colon)))) {
  754. // This handles a special macro in ObjC code where selectors including
  755. // the colon are passed as macro arguments.
  756. Tok->Type = TT_ObjCMethodExpr;
  757. } else if (Contexts.back().ContextKind == tok::l_paren) {
  758. Tok->Type = TT_InlineASMColon;
  759. }
  760. break;
  761. case tok::pipe:
  762. case tok::amp:
  763. // | and & in declarations/type expressions represent union and
  764. // intersection types, respectively.
  765. if (Style.Language == FormatStyle::LK_JavaScript &&
  766. !Contexts.back().IsExpression)
  767. Tok->Type = TT_JsTypeOperator;
  768. break;
  769. case tok::kw_if:
  770. case tok::kw_while:
  771. if (Tok->is(tok::kw_if) && CurrentToken &&
  772. CurrentToken->is(tok::kw_constexpr))
  773. next();
  774. if (CurrentToken && CurrentToken->is(tok::l_paren)) {
  775. next();
  776. if (!parseParens(/*LookForDecls=*/true))
  777. return false;
  778. }
  779. break;
  780. case tok::kw_for:
  781. if (Style.Language == FormatStyle::LK_JavaScript) {
  782. // x.for and {for: ...}
  783. if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
  784. (Tok->Next && Tok->Next->is(tok::colon)))
  785. break;
  786. // JS' for await ( ...
  787. if (CurrentToken && CurrentToken->is(Keywords.kw_await))
  788. next();
  789. }
  790. Contexts.back().ColonIsForRangeExpr = true;
  791. next();
  792. if (!parseParens())
  793. return false;
  794. break;
  795. case tok::l_paren:
  796. // When faced with 'operator()()', the kw_operator handler incorrectly
  797. // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
  798. // the first two parens OverloadedOperators and the second l_paren an
  799. // OverloadedOperatorLParen.
  800. if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
  801. Tok->Previous->MatchingParen &&
  802. Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
  803. Tok->Previous->Type = TT_OverloadedOperator;
  804. Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
  805. Tok->Type = TT_OverloadedOperatorLParen;
  806. }
  807. if (!parseParens())
  808. return false;
  809. if (Line.MustBeDeclaration && Contexts.size() == 1 &&
  810. !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
  811. (!Tok->Previous ||
  812. !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
  813. TT_LeadingJavaAnnotation)))
  814. Line.MightBeFunctionDecl = true;
  815. break;
  816. case tok::l_square:
  817. if (!parseSquare())
  818. return false;
  819. break;
  820. case tok::l_brace:
  821. if (Style.Language == FormatStyle::LK_TextProto) {
  822. FormatToken *Previous = Tok->getPreviousNonComment();
  823. if (Previous && Previous->Type != TT_DictLiteral)
  824. Previous->Type = TT_SelectorName;
  825. }
  826. if (!parseBrace())
  827. return false;
  828. break;
  829. case tok::less:
  830. if (parseAngle()) {
  831. Tok->Type = TT_TemplateOpener;
  832. // In TT_Proto, we must distignuish between:
  833. // map<key, value>
  834. // msg < item: data >
  835. // msg: < item: data >
  836. // In TT_TextProto, map<key, value> does not occur.
  837. if (Style.Language == FormatStyle::LK_TextProto ||
  838. (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
  839. Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
  840. Tok->Type = TT_DictLiteral;
  841. FormatToken *Previous = Tok->getPreviousNonComment();
  842. if (Previous && Previous->Type != TT_DictLiteral)
  843. Previous->Type = TT_SelectorName;
  844. }
  845. } else {
  846. Tok->Type = TT_BinaryOperator;
  847. NonTemplateLess.insert(Tok);
  848. CurrentToken = Tok;
  849. next();
  850. }
  851. break;
  852. case tok::r_paren:
  853. case tok::r_square:
  854. return false;
  855. case tok::r_brace:
  856. // Lines can start with '}'.
  857. if (Tok->Previous)
  858. return false;
  859. break;
  860. case tok::greater:
  861. if (Style.Language != FormatStyle::LK_TextProto)
  862. Tok->Type = TT_BinaryOperator;
  863. break;
  864. case tok::kw_operator:
  865. if (Style.Language == FormatStyle::LK_TextProto ||
  866. Style.Language == FormatStyle::LK_Proto)
  867. break;
  868. while (CurrentToken &&
  869. !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
  870. if (CurrentToken->isOneOf(tok::star, tok::amp))
  871. CurrentToken->Type = TT_PointerOrReference;
  872. consumeToken();
  873. if (CurrentToken &&
  874. CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
  875. tok::comma))
  876. CurrentToken->Previous->Type = TT_OverloadedOperator;
  877. }
  878. if (CurrentToken) {
  879. CurrentToken->Type = TT_OverloadedOperatorLParen;
  880. if (CurrentToken->Previous->is(TT_BinaryOperator))
  881. CurrentToken->Previous->Type = TT_OverloadedOperator;
  882. }
  883. break;
  884. case tok::question:
  885. if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
  886. Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
  887. tok::r_brace)) {
  888. // Question marks before semicolons, colons, etc. indicate optional
  889. // types (fields, parameters), e.g.
  890. // function(x?: string, y?) {...}
  891. // class X { y?; }
  892. Tok->Type = TT_JsTypeOptionalQuestion;
  893. break;
  894. }
  895. // Declarations cannot be conditional expressions, this can only be part
  896. // of a type declaration.
  897. if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
  898. Style.Language == FormatStyle::LK_JavaScript)
  899. break;
  900. parseConditional();
  901. break;
  902. case tok::kw_template:
  903. parseTemplateDeclaration();
  904. break;
  905. case tok::comma:
  906. if (Contexts.back().InCtorInitializer)
  907. Tok->Type = TT_CtorInitializerComma;
  908. else if (Contexts.back().InInheritanceList)
  909. Tok->Type = TT_InheritanceComma;
  910. else if (Contexts.back().FirstStartOfName &&
  911. (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
  912. Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
  913. Line.IsMultiVariableDeclStmt = true;
  914. }
  915. if (Contexts.back().IsForEachMacro)
  916. Contexts.back().IsExpression = true;
  917. break;
  918. case tok::identifier:
  919. if (Tok->isOneOf(Keywords.kw___has_include,
  920. Keywords.kw___has_include_next)) {
  921. parseHasInclude();
  922. }
  923. break;
  924. default:
  925. break;
  926. }
  927. return true;
  928. }
  929. void parseIncludeDirective() {
  930. if (CurrentToken && CurrentToken->is(tok::less)) {
  931. next();
  932. while (CurrentToken) {
  933. // Mark tokens up to the trailing line comments as implicit string
  934. // literals.
  935. if (CurrentToken->isNot(tok::comment) &&
  936. !CurrentToken->TokenText.startswith("//"))
  937. CurrentToken->Type = TT_ImplicitStringLiteral;
  938. next();
  939. }
  940. }
  941. }
  942. void parseWarningOrError() {
  943. next();
  944. // We still want to format the whitespace left of the first token of the
  945. // warning or error.
  946. next();
  947. while (CurrentToken) {
  948. CurrentToken->Type = TT_ImplicitStringLiteral;
  949. next();
  950. }
  951. }
  952. void parsePragma() {
  953. next(); // Consume "pragma".
  954. if (CurrentToken &&
  955. CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
  956. bool IsMark = CurrentToken->is(Keywords.kw_mark);
  957. next(); // Consume "mark".
  958. next(); // Consume first token (so we fix leading whitespace).
  959. while (CurrentToken) {
  960. if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
  961. CurrentToken->Type = TT_ImplicitStringLiteral;
  962. next();
  963. }
  964. }
  965. }
  966. void parseHasInclude() {
  967. if (!CurrentToken || !CurrentToken->is(tok::l_paren))
  968. return;
  969. next(); // '('
  970. parseIncludeDirective();
  971. next(); // ')'
  972. }
  973. LineType parsePreprocessorDirective() {
  974. bool IsFirstToken = CurrentToken->IsFirst;
  975. LineType Type = LT_PreprocessorDirective;
  976. next();
  977. if (!CurrentToken)
  978. return Type;
  979. if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
  980. // JavaScript files can contain shebang lines of the form:
  981. // #!/usr/bin/env node
  982. // Treat these like C++ #include directives.
  983. while (CurrentToken) {
  984. // Tokens cannot be comments here.
  985. CurrentToken->Type = TT_ImplicitStringLiteral;
  986. next();
  987. }
  988. return LT_ImportStatement;
  989. }
  990. if (CurrentToken->Tok.is(tok::numeric_constant)) {
  991. CurrentToken->SpacesRequiredBefore = 1;
  992. return Type;
  993. }
  994. // Hashes in the middle of a line can lead to any strange token
  995. // sequence.
  996. if (!CurrentToken->Tok.getIdentifierInfo())
  997. return Type;
  998. switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
  999. case tok::pp_include:
  1000. case tok::pp_include_next:
  1001. case tok::pp_import:
  1002. next();
  1003. parseIncludeDirective();
  1004. Type = LT_ImportStatement;
  1005. break;
  1006. case tok::pp_error:
  1007. case tok::pp_warning:
  1008. parseWarningOrError();
  1009. break;
  1010. case tok::pp_pragma:
  1011. parsePragma();
  1012. break;
  1013. case tok::pp_if:
  1014. case tok::pp_elif:
  1015. Contexts.back().IsExpression = true;
  1016. parseLine();
  1017. break;
  1018. default:
  1019. break;
  1020. }
  1021. while (CurrentToken) {
  1022. FormatToken *Tok = CurrentToken;
  1023. next();
  1024. if (Tok->is(tok::l_paren))
  1025. parseParens();
  1026. else if (Tok->isOneOf(Keywords.kw___has_include,
  1027. Keywords.kw___has_include_next))
  1028. parseHasInclude();
  1029. }
  1030. return Type;
  1031. }
  1032. public:
  1033. LineType parseLine() {
  1034. NonTemplateLess.clear();
  1035. if (CurrentToken->is(tok::hash))
  1036. return parsePreprocessorDirective();
  1037. // Directly allow to 'import <string-literal>' to support protocol buffer
  1038. // definitions (github.com/google/protobuf) or missing "#" (either way we
  1039. // should not break the line).
  1040. IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
  1041. if ((Style.Language == FormatStyle::LK_Java &&
  1042. CurrentToken->is(Keywords.kw_package)) ||
  1043. (Info && Info->getPPKeywordID() == tok::pp_import &&
  1044. CurrentToken->Next &&
  1045. CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
  1046. tok::kw_static))) {
  1047. next();
  1048. parseIncludeDirective();
  1049. return LT_ImportStatement;
  1050. }
  1051. // If this line starts and ends in '<' and '>', respectively, it is likely
  1052. // part of "#define <a/b.h>".
  1053. if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
  1054. parseIncludeDirective();
  1055. return LT_ImportStatement;
  1056. }
  1057. // In .proto files, top-level options and package statements are very
  1058. // similar to import statements and should not be line-wrapped.
  1059. if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
  1060. CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
  1061. next();
  1062. if (CurrentToken && CurrentToken->is(tok::identifier)) {
  1063. while (CurrentToken)
  1064. next();
  1065. return LT_ImportStatement;
  1066. }
  1067. }
  1068. bool KeywordVirtualFound = false;
  1069. bool ImportStatement = false;
  1070. // import {...} from '...';
  1071. if (Style.Language == FormatStyle::LK_JavaScript &&
  1072. CurrentToken->is(Keywords.kw_import))
  1073. ImportStatement = true;
  1074. while (CurrentToken) {
  1075. if (CurrentToken->is(tok::kw_virtual))
  1076. KeywordVirtualFound = true;
  1077. if (Style.Language == FormatStyle::LK_JavaScript) {
  1078. // export {...} from '...';
  1079. // An export followed by "from 'some string';" is a re-export from
  1080. // another module identified by a URI and is treated as a
  1081. // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
  1082. // Just "export {...};" or "export class ..." should not be treated as
  1083. // an import in this sense.
  1084. if (Line.First->is(tok::kw_export) &&
  1085. CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
  1086. CurrentToken->Next->isStringLiteral())
  1087. ImportStatement = true;
  1088. if (isClosureImportStatement(*CurrentToken))
  1089. ImportStatement = true;
  1090. }
  1091. if (!consumeToken())
  1092. return LT_Invalid;
  1093. }
  1094. if (KeywordVirtualFound)
  1095. return LT_VirtualFunctionDecl;
  1096. if (ImportStatement)
  1097. return LT_ImportStatement;
  1098. if (Line.startsWith(TT_ObjCMethodSpecifier)) {
  1099. if (Contexts.back().FirstObjCSelectorName)
  1100. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
  1101. Contexts.back().LongestObjCSelectorName;
  1102. return LT_ObjCMethodDecl;
  1103. }
  1104. return LT_Other;
  1105. }
  1106. private:
  1107. bool isClosureImportStatement(const FormatToken &Tok) {
  1108. // FIXME: Closure-library specific stuff should not be hard-coded but be
  1109. // configurable.
  1110. return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
  1111. Tok.Next->Next &&
  1112. (Tok.Next->Next->TokenText == "module" ||
  1113. Tok.Next->Next->TokenText == "provide" ||
  1114. Tok.Next->Next->TokenText == "require" ||
  1115. Tok.Next->Next->TokenText == "requireType" ||
  1116. Tok.Next->Next->TokenText == "forwardDeclare") &&
  1117. Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
  1118. }
  1119. void resetTokenMetadata(FormatToken *Token) {
  1120. if (!Token)
  1121. return;
  1122. // Reset token type in case we have already looked at it and then
  1123. // recovered from an error (e.g. failure to find the matching >).
  1124. if (!CurrentToken->isOneOf(
  1125. TT_LambdaLSquare, TT_LambdaLBrace, TT_ForEachMacro,
  1126. TT_FunctionLBrace, TT_ImplicitStringLiteral, TT_InlineASMBrace,
  1127. TT_JsFatArrow, TT_LambdaArrow, TT_OverloadedOperator,
  1128. TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral))
  1129. CurrentToken->Type = TT_Unknown;
  1130. CurrentToken->Role.reset();
  1131. CurrentToken->MatchingParen = nullptr;
  1132. CurrentToken->FakeLParens.clear();
  1133. CurrentToken->FakeRParens = 0;
  1134. }
  1135. void next() {
  1136. if (CurrentToken) {
  1137. CurrentToken->NestingLevel = Contexts.size() - 1;
  1138. CurrentToken->BindingStrength = Contexts.back().BindingStrength;
  1139. modifyContext(*CurrentToken);
  1140. determineTokenType(*CurrentToken);
  1141. CurrentToken = CurrentToken->Next;
  1142. }
  1143. resetTokenMetadata(CurrentToken);
  1144. }
  1145. /// A struct to hold information valid in a specific context, e.g.
  1146. /// a pair of parenthesis.
  1147. struct Context {
  1148. Context(tok::TokenKind ContextKind, unsigned BindingStrength,
  1149. bool IsExpression)
  1150. : ContextKind(ContextKind), BindingStrength(BindingStrength),
  1151. IsExpression(IsExpression) {}
  1152. tok::TokenKind ContextKind;
  1153. unsigned BindingStrength;
  1154. bool IsExpression;
  1155. unsigned LongestObjCSelectorName = 0;
  1156. bool ColonIsForRangeExpr = false;
  1157. bool ColonIsDictLiteral = false;
  1158. bool ColonIsObjCMethodExpr = false;
  1159. FormatToken *FirstObjCSelectorName = nullptr;
  1160. FormatToken *FirstStartOfName = nullptr;
  1161. bool CanBeExpression = true;
  1162. bool InTemplateArgument = false;
  1163. bool InCtorInitializer = false;
  1164. bool InInheritanceList = false;
  1165. bool CaretFound = false;
  1166. bool IsForEachMacro = false;
  1167. bool InCpp11AttributeSpecifier = false;
  1168. bool InCSharpAttributeSpecifier = false;
  1169. };
  1170. /// Puts a new \c Context onto the stack \c Contexts for the lifetime
  1171. /// of each instance.
  1172. struct ScopedContextCreator {
  1173. AnnotatingParser &P;
  1174. ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
  1175. unsigned Increase)
  1176. : P(P) {
  1177. P.Contexts.push_back(Context(ContextKind,
  1178. P.Contexts.back().BindingStrength + Increase,
  1179. P.Contexts.back().IsExpression));
  1180. }
  1181. ~ScopedContextCreator() { P.Contexts.pop_back(); }
  1182. };
  1183. void modifyContext(const FormatToken &Current) {
  1184. if (Current.getPrecedence() == prec::Assignment &&
  1185. !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
  1186. // Type aliases use `type X = ...;` in TypeScript and can be exported
  1187. // using `export type ...`.
  1188. !(Style.Language == FormatStyle::LK_JavaScript &&
  1189. (Line.startsWith(Keywords.kw_type, tok::identifier) ||
  1190. Line.startsWith(tok::kw_export, Keywords.kw_type,
  1191. tok::identifier))) &&
  1192. (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
  1193. Contexts.back().IsExpression = true;
  1194. if (!Line.startsWith(TT_UnaryOperator)) {
  1195. for (FormatToken *Previous = Current.Previous;
  1196. Previous && Previous->Previous &&
  1197. !Previous->Previous->isOneOf(tok::comma, tok::semi);
  1198. Previous = Previous->Previous) {
  1199. if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
  1200. Previous = Previous->MatchingParen;
  1201. if (!Previous)
  1202. break;
  1203. }
  1204. if (Previous->opensScope())
  1205. break;
  1206. if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
  1207. Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
  1208. Previous->Previous && Previous->Previous->isNot(tok::equal))
  1209. Previous->Type = TT_PointerOrReference;
  1210. }
  1211. }
  1212. } else if (Current.is(tok::lessless) &&
  1213. (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
  1214. Contexts.back().IsExpression = true;
  1215. } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
  1216. Contexts.back().IsExpression = true;
  1217. } else if (Current.is(TT_TrailingReturnArrow)) {
  1218. Contexts.back().IsExpression = false;
  1219. } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
  1220. Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
  1221. } else if (Current.Previous &&
  1222. Current.Previous->is(TT_CtorInitializerColon)) {
  1223. Contexts.back().IsExpression = true;
  1224. Contexts.back().InCtorInitializer = true;
  1225. } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
  1226. Contexts.back().InInheritanceList = true;
  1227. } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
  1228. for (FormatToken *Previous = Current.Previous;
  1229. Previous && Previous->isOneOf(tok::star, tok::amp);
  1230. Previous = Previous->Previous)
  1231. Previous->Type = TT_PointerOrReference;
  1232. if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
  1233. Contexts.back().IsExpression = false;
  1234. } else if (Current.is(tok::kw_new)) {
  1235. Contexts.back().CanBeExpression = false;
  1236. } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
  1237. // This should be the condition or increment in a for-loop.
  1238. Contexts.back().IsExpression = true;
  1239. }
  1240. }
  1241. void determineTokenType(FormatToken &Current) {
  1242. if (!Current.is(TT_Unknown))
  1243. // The token type is already known.
  1244. return;
  1245. if (Style.Language == FormatStyle::LK_JavaScript) {
  1246. if (Current.is(tok::exclaim)) {
  1247. if (Current.Previous &&
  1248. (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
  1249. tok::r_paren, tok::r_square,
  1250. tok::r_brace) ||
  1251. Current.Previous->Tok.isLiteral())) {
  1252. Current.Type = TT_JsNonNullAssertion;
  1253. return;
  1254. }
  1255. if (Current.Next &&
  1256. Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
  1257. Current.Type = TT_JsNonNullAssertion;
  1258. return;
  1259. }
  1260. }
  1261. }
  1262. // Line.MightBeFunctionDecl can only be true after the parentheses of a
  1263. // function declaration have been found. In this case, 'Current' is a
  1264. // trailing token of this declaration and thus cannot be a name.
  1265. if (Current.is(Keywords.kw_instanceof)) {
  1266. Current.Type = TT_BinaryOperator;
  1267. } else if (isStartOfName(Current) &&
  1268. (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
  1269. Contexts.back().FirstStartOfName = &Current;
  1270. Current.Type = TT_StartOfName;
  1271. } else if (Current.is(tok::semi)) {
  1272. // Reset FirstStartOfName after finding a semicolon so that a for loop
  1273. // with multiple increment statements is not confused with a for loop
  1274. // having multiple variable declarations.
  1275. Contexts.back().FirstStartOfName = nullptr;
  1276. } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
  1277. AutoFound = true;
  1278. } else if (Current.is(tok::arrow) &&
  1279. Style.Language == FormatStyle::LK_Java) {
  1280. Current.Type = TT_LambdaArrow;
  1281. } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
  1282. Current.NestingLevel == 0) {
  1283. Current.Type = TT_TrailingReturnArrow;
  1284. } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
  1285. Current.Type = determineStarAmpUsage(Current,
  1286. Contexts.back().CanBeExpression &&
  1287. Contexts.back().IsExpression,
  1288. Contexts.back().InTemplateArgument);
  1289. } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
  1290. Current.Type = determinePlusMinusCaretUsage(Current);
  1291. if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
  1292. Contexts.back().CaretFound = true;
  1293. } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
  1294. Current.Type = determineIncrementUsage(Current);
  1295. } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
  1296. Current.Type = TT_UnaryOperator;
  1297. } else if (Current.is(tok::question)) {
  1298. if (Style.Language == FormatStyle::LK_JavaScript &&
  1299. Line.MustBeDeclaration && !Contexts.back().IsExpression) {
  1300. // In JavaScript, `interface X { foo?(): bar; }` is an optional method
  1301. // on the interface, not a ternary expression.
  1302. Current.Type = TT_JsTypeOptionalQuestion;
  1303. } else {
  1304. Current.Type = TT_ConditionalExpr;
  1305. }
  1306. } else if (Current.isBinaryOperator() &&
  1307. (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
  1308. (!Current.is(tok::greater) &&
  1309. Style.Language != FormatStyle::LK_TextProto)) {
  1310. Current.Type = TT_BinaryOperator;
  1311. } else if (Current.is(tok::comment)) {
  1312. if (Current.TokenText.startswith("/*")) {
  1313. if (Current.TokenText.endswith("*/"))
  1314. Current.Type = TT_BlockComment;
  1315. else
  1316. // The lexer has for some reason determined a comment here. But we
  1317. // cannot really handle it, if it isn't properly terminated.
  1318. Current.Tok.setKind(tok::unknown);
  1319. } else {
  1320. Current.Type = TT_LineComment;
  1321. }
  1322. } else if (Current.is(tok::r_paren)) {
  1323. if (rParenEndsCast(Current))
  1324. Current.Type = TT_CastRParen;
  1325. if (Current.MatchingParen && Current.Next &&
  1326. !Current.Next->isBinaryOperator() &&
  1327. !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
  1328. tok::comma, tok::period, tok::arrow,
  1329. tok::coloncolon))
  1330. if (FormatToken *AfterParen = Current.MatchingParen->Next) {
  1331. // Make sure this isn't the return type of an Obj-C block declaration
  1332. if (AfterParen->Tok.isNot(tok::caret)) {
  1333. if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
  1334. if (BeforeParen->is(tok::identifier) &&
  1335. BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
  1336. (!BeforeParen->Previous ||
  1337. BeforeParen->Previous->ClosesTemplateDeclaration))
  1338. Current.Type = TT_FunctionAnnotationRParen;
  1339. }
  1340. }
  1341. } else if (Current.is(tok::at) && Current.Next &&
  1342. Style.Language != FormatStyle::LK_JavaScript &&
  1343. Style.Language != FormatStyle::LK_Java) {
  1344. // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
  1345. // marks declarations and properties that need special formatting.
  1346. switch (Current.Next->Tok.getObjCKeywordID()) {
  1347. case tok::objc_interface:
  1348. case tok::objc_implementation:
  1349. case tok::objc_protocol:
  1350. Current.Type = TT_ObjCDecl;
  1351. break;
  1352. case tok::objc_property:
  1353. Current.Type = TT_ObjCProperty;
  1354. break;
  1355. default:
  1356. break;
  1357. }
  1358. } else if (Current.is(tok::period)) {
  1359. FormatToken *PreviousNoComment = Current.getPreviousNonComment();
  1360. if (PreviousNoComment &&
  1361. PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
  1362. Current.Type = TT_DesignatedInitializerPeriod;
  1363. else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
  1364. Current.Previous->isOneOf(TT_JavaAnnotation,
  1365. TT_LeadingJavaAnnotation)) {
  1366. Current.Type = Current.Previous->Type;
  1367. }
  1368. } else if (canBeObjCSelectorComponent(Current) &&
  1369. // FIXME(bug 36976): ObjC return types shouldn't use
  1370. // TT_CastRParen.
  1371. Current.Previous && Current.Previous->is(TT_CastRParen) &&
  1372. Current.Previous->MatchingParen &&
  1373. Current.Previous->MatchingParen->Previous &&
  1374. Current.Previous->MatchingParen->Previous->is(
  1375. TT_ObjCMethodSpecifier)) {
  1376. // This is the first part of an Objective-C selector name. (If there's no
  1377. // colon after this, this is the only place which annotates the identifier
  1378. // as a selector.)
  1379. Current.Type = TT_SelectorName;
  1380. } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
  1381. Current.Previous &&
  1382. !Current.Previous->isOneOf(tok::equal, tok::at) &&
  1383. Line.MightBeFunctionDecl && Contexts.size() == 1) {
  1384. // Line.MightBeFunctionDecl can only be true after the parentheses of a
  1385. // function declaration have been found.
  1386. Current.Type = TT_TrailingAnnotation;
  1387. } else if ((Style.Language == FormatStyle::LK_Java ||
  1388. Style.Language == FormatStyle::LK_JavaScript) &&
  1389. Current.Previous) {
  1390. if (Current.Previous->is(tok::at) &&
  1391. Current.isNot(Keywords.kw_interface)) {
  1392. const FormatToken &AtToken = *Current.Previous;
  1393. const FormatToken *Previous = AtToken.getPreviousNonComment();
  1394. if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
  1395. Current.Type = TT_LeadingJavaAnnotation;
  1396. else
  1397. Current.Type = TT_JavaAnnotation;
  1398. } else if (Current.Previous->is(tok::period) &&
  1399. Current.Previous->isOneOf(TT_JavaAnnotation,
  1400. TT_LeadingJavaAnnotation)) {
  1401. Current.Type = Current.Previous->Type;
  1402. }
  1403. }
  1404. }
  1405. /// Take a guess at whether \p Tok starts a name of a function or
  1406. /// variable declaration.
  1407. ///
  1408. /// This is a heuristic based on whether \p Tok is an identifier following
  1409. /// something that is likely a type.
  1410. bool isStartOfName(const FormatToken &Tok) {
  1411. if (Tok.isNot(tok::identifier) || !Tok.Previous)
  1412. return false;
  1413. if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
  1414. Keywords.kw_as))
  1415. return false;
  1416. if (Style.Language == FormatStyle::LK_JavaScript &&
  1417. Tok.Previous->is(Keywords.kw_in))
  1418. return false;
  1419. // Skip "const" as it does not have an influence on whether this is a name.
  1420. FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
  1421. while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
  1422. PreviousNotConst = PreviousNotConst->getPreviousNonComment();
  1423. if (!PreviousNotConst)
  1424. return false;
  1425. bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
  1426. PreviousNotConst->Previous &&
  1427. PreviousNotConst->Previous->is(tok::hash);
  1428. if (PreviousNotConst->is(TT_TemplateCloser))
  1429. return PreviousNotConst && PreviousNotConst->MatchingParen &&
  1430. PreviousNotConst->MatchingParen->Previous &&
  1431. PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
  1432. PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
  1433. if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
  1434. PreviousNotConst->MatchingParen->Previous &&
  1435. PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
  1436. return true;
  1437. return (!IsPPKeyword &&
  1438. PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
  1439. PreviousNotConst->is(TT_PointerOrReference) ||
  1440. PreviousNotConst->isSimpleTypeSpecifier();
  1441. }
  1442. /// Determine whether ')' is ending a cast.
  1443. bool rParenEndsCast(const FormatToken &Tok) {
  1444. // C-style casts are only used in C++ and Java.
  1445. if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
  1446. return false;
  1447. // Empty parens aren't casts and there are no casts at the end of the line.
  1448. if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
  1449. return false;
  1450. FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
  1451. if (LeftOfParens) {
  1452. // If there is a closing parenthesis left of the current parentheses,
  1453. // look past it as these might be chained casts.
  1454. if (LeftOfParens->is(tok::r_paren)) {
  1455. if (!LeftOfParens->MatchingParen ||
  1456. !LeftOfParens->MatchingParen->Previous)
  1457. return false;
  1458. LeftOfParens = LeftOfParens->MatchingParen->Previous;
  1459. }
  1460. // If there is an identifier (or with a few exceptions a keyword) right
  1461. // before the parentheses, this is unlikely to be a cast.
  1462. if (LeftOfParens->Tok.getIdentifierInfo() &&
  1463. !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
  1464. tok::kw_delete))
  1465. return false;
  1466. // Certain other tokens right before the parentheses are also signals that
  1467. // this cannot be a cast.
  1468. if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
  1469. TT_TemplateCloser, tok::ellipsis))
  1470. return false;
  1471. }
  1472. if (Tok.Next->is(tok::question))
  1473. return false;
  1474. // As Java has no function types, a "(" after the ")" likely means that this
  1475. // is a cast.
  1476. if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
  1477. return true;
  1478. // If a (non-string) literal follows, this is likely a cast.
  1479. if (Tok.Next->isNot(tok::string_literal) &&
  1480. (Tok.Next->Tok.isLiteral() ||
  1481. Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
  1482. return true;
  1483. // Heuristically try to determine whether the parentheses contain a type.
  1484. bool ParensAreType =
  1485. !Tok.Previous ||
  1486. Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
  1487. Tok.Previous->isSimpleTypeSpecifier();
  1488. bool ParensCouldEndDecl =
  1489. Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
  1490. if (ParensAreType && !ParensCouldEndDecl)
  1491. return true;
  1492. // At this point, we heuristically assume that there are no casts at the
  1493. // start of the line. We assume that we have found most cases where there
  1494. // are by the logic above, e.g. "(void)x;".
  1495. if (!LeftOfParens)
  1496. return false;
  1497. // Certain token types inside the parentheses mean that this can't be a
  1498. // cast.
  1499. for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
  1500. Token = Token->Next)
  1501. if (Token->is(TT_BinaryOperator))
  1502. return false;
  1503. // If the following token is an identifier or 'this', this is a cast. All
  1504. // cases where this can be something else are handled above.
  1505. if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
  1506. return true;
  1507. if (!Tok.Next->Next)
  1508. return false;
  1509. // If the next token after the parenthesis is a unary operator, assume
  1510. // that this is cast, unless there are unexpected tokens inside the
  1511. // parenthesis.
  1512. bool NextIsUnary =
  1513. Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
  1514. if (!NextIsUnary || Tok.Next->is(tok::plus) ||
  1515. !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
  1516. return false;
  1517. // Search for unexpected tokens.
  1518. for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
  1519. Prev = Prev->Previous) {
  1520. if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
  1521. return false;
  1522. }
  1523. return true;
  1524. }
  1525. /// Return the type of the given token assuming it is * or &.
  1526. TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
  1527. bool InTemplateArgument) {
  1528. if (Style.Language == FormatStyle::LK_JavaScript)
  1529. return TT_BinaryOperator;
  1530. const FormatToken *PrevToken = Tok.getPreviousNonComment();
  1531. if (!PrevToken)
  1532. return TT_UnaryOperator;
  1533. const FormatToken *NextToken = Tok.getNextNonComment();
  1534. if (!NextToken ||
  1535. NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
  1536. (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
  1537. return TT_PointerOrReference;
  1538. if (PrevToken->is(tok::coloncolon))
  1539. return TT_PointerOrReference;
  1540. if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
  1541. tok::comma, tok::semi, tok::kw_return, tok::colon,
  1542. tok::equal, tok::kw_delete, tok::kw_sizeof,
  1543. tok::kw_throw) ||
  1544. PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
  1545. TT_UnaryOperator, TT_CastRParen))
  1546. return TT_UnaryOperator;
  1547. if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
  1548. return TT_PointerOrReference;
  1549. if (NextToken->is(tok::kw_operator) && !IsExpression)
  1550. return TT_PointerOrReference;
  1551. if (NextToken->isOneOf(tok::comma, tok::semi))
  1552. return TT_PointerOrReference;
  1553. if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
  1554. FormatToken *TokenBeforeMatchingParen =
  1555. PrevToken->MatchingParen->getPreviousNonComment();
  1556. if (TokenBeforeMatchingParen &&
  1557. TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
  1558. return TT_PointerOrReference;
  1559. }
  1560. if (PrevToken->Tok.isLiteral() ||
  1561. PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
  1562. tok::kw_false, tok::r_brace) ||
  1563. NextToken->Tok.isLiteral() ||
  1564. NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
  1565. NextToken->isUnaryOperator() ||
  1566. // If we know we're in a template argument, there are no named
  1567. // declarations. Thus, having an identifier on the right-hand side
  1568. // indicates a binary operator.
  1569. (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
  1570. return TT_BinaryOperator;
  1571. // "&&(" is quite unlikely to be two successive unary "&".
  1572. if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
  1573. return TT_BinaryOperator;
  1574. // This catches some cases where evaluation order is used as control flow:
  1575. // aaa && aaa->f();
  1576. const FormatToken *NextNextToken = NextToken->getNextNonComment();
  1577. if (NextNextToken && NextNextToken->is(tok::arrow))
  1578. return TT_BinaryOperator;
  1579. // It is very unlikely that we are going to find a pointer or reference type
  1580. // definition on the RHS of an assignment.
  1581. if (IsExpression && !Contexts.back().CaretFound)
  1582. return TT_BinaryOperator;
  1583. return TT_PointerOrReference;
  1584. }
  1585. TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
  1586. const FormatToken *PrevToken = Tok.getPreviousNonComment();
  1587. if (!PrevToken)
  1588. return TT_UnaryOperator;
  1589. if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
  1590. // This must be a sequence of leading unary operators.
  1591. return TT_UnaryOperator;
  1592. // Use heuristics to recognize unary operators.
  1593. if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
  1594. tok::question, tok::colon, tok::kw_return,
  1595. tok::kw_case, tok::at, tok::l_brace))
  1596. return TT_UnaryOperator;
  1597. // There can't be two consecutive binary operators.
  1598. if (PrevToken->is(TT_BinaryOperator))
  1599. return TT_UnaryOperator;
  1600. // Fall back to marking the token as binary operator.
  1601. return TT_BinaryOperator;
  1602. }
  1603. /// Determine whether ++/-- are pre- or post-increments/-decrements.
  1604. TokenType determineIncrementUsage(const FormatToken &Tok) {
  1605. const FormatToken *PrevToken = Tok.getPreviousNonComment();
  1606. if (!PrevToken || PrevToken->is(TT_CastRParen))
  1607. return TT_UnaryOperator;
  1608. if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
  1609. return TT_TrailingUnaryOperator;
  1610. return TT_UnaryOperator;
  1611. }
  1612. SmallVector<Context, 8> Contexts;
  1613. const FormatStyle &Style;
  1614. AnnotatedLine &Line;
  1615. FormatToken *CurrentToken;
  1616. bool AutoFound;
  1617. const AdditionalKeywords &Keywords;
  1618. // Set of "<" tokens that do not open a template parameter list. If parseAngle
  1619. // determines that a specific token can't be a template opener, it will make
  1620. // same decision irrespective of the decisions for tokens leading up to it.
  1621. // Store this information to prevent this from causing exponential runtime.
  1622. llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
  1623. };
  1624. static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
  1625. static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
  1626. /// Parses binary expressions by inserting fake parenthesis based on
  1627. /// operator precedence.
  1628. class ExpressionParser {
  1629. public:
  1630. ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
  1631. AnnotatedLine &Line)
  1632. : Style(Style), Keywords(Keywords), Current(Line.First) {}
  1633. /// Parse expressions with the given operator precedence.
  1634. void parse(int Precedence = 0) {
  1635. // Skip 'return' and ObjC selector colons as they are not part of a binary
  1636. // expression.
  1637. while (Current && (Current->is(tok::kw_return) ||
  1638. (Current->is(tok::colon) &&
  1639. Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
  1640. next();
  1641. if (!Current || Precedence > PrecedenceArrowAndPeriod)
  1642. return;
  1643. // Conditional expressions need to be parsed separately for proper nesting.
  1644. if (Precedence == prec::Conditional) {
  1645. parseConditionalExpr();
  1646. return;
  1647. }
  1648. // Parse unary operators, which all have a higher precedence than binary
  1649. // operators.
  1650. if (Precedence == PrecedenceUnaryOperator) {
  1651. parseUnaryOperator();
  1652. return;
  1653. }
  1654. FormatToken *Start = Current;
  1655. FormatToken *LatestOperator = nullptr;
  1656. unsigned OperatorIndex = 0;
  1657. while (Current) {
  1658. // Consume operators with higher precedence.
  1659. parse(Precedence + 1);
  1660. int CurrentPrecedence = getCurrentPrecedence();
  1661. if (Current && Current->is(TT_SelectorName) &&
  1662. Precedence == CurrentPrecedence) {
  1663. if (LatestOperator)
  1664. addFakeParenthesis(Start, prec::Level(Precedence));
  1665. Start = Current;
  1666. }
  1667. // At the end of the line or when an operator with higher precedence is
  1668. // found, insert fake parenthesis and return.
  1669. if (!Current ||
  1670. (Current->closesScope() &&
  1671. (Current->MatchingParen || Current->is(TT_TemplateString))) ||
  1672. (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
  1673. (CurrentPrecedence == prec::Conditional &&
  1674. Precedence == prec::Assignment && Current->is(tok::colon))) {
  1675. break;
  1676. }
  1677. // Consume scopes: (), [], <> and {}
  1678. if (Current->opensScope()) {
  1679. // In fragment of a JavaScript template string can look like '}..${' and
  1680. // thus close a scope and open a new one at the same time.
  1681. while (Current && (!Current->closesScope() || Current->opensScope())) {
  1682. next();
  1683. parse();
  1684. }
  1685. next();
  1686. } else {
  1687. // Operator found.
  1688. if (CurrentPrecedence == Precedence) {
  1689. if (LatestOperator)
  1690. LatestOperator->NextOperator = Current;
  1691. LatestOperator = Current;
  1692. Current->OperatorIndex = OperatorIndex;
  1693. ++OperatorIndex;
  1694. }
  1695. next(/*SkipPastLeadingComments=*/Precedence > 0);
  1696. }
  1697. }
  1698. if (LatestOperator && (Current || Precedence > 0)) {
  1699. // LatestOperator->LastOperator = true;
  1700. if (Precedence == PrecedenceArrowAndPeriod) {
  1701. // Call expressions don't have a binary operator precedence.
  1702. addFakeParenthesis(Start, prec::Unknown);
  1703. } else {
  1704. addFakeParenthesis(Start, prec::Level(Precedence));
  1705. }
  1706. }
  1707. }
  1708. private:
  1709. /// Gets the precedence (+1) of the given token for binary operators
  1710. /// and other tokens that we treat like binary operators.
  1711. int getCurrentPrecedence() {
  1712. if (Current) {
  1713. const FormatToken *NextNonComment = Current->getNextNonComment();
  1714. if (Current->is(TT_ConditionalExpr))
  1715. return prec::Conditional;
  1716. if (NextNonComment && Current->is(TT_SelectorName) &&
  1717. (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
  1718. ((Style.Language == FormatStyle::LK_Proto ||
  1719. Style.Language == FormatStyle::LK_TextProto) &&
  1720. NextNonComment->is(tok::less))))
  1721. return prec::Assignment;
  1722. if (Current->is(TT_JsComputedPropertyName))
  1723. return prec::Assignment;
  1724. if (Current->is(TT_LambdaArrow))
  1725. return prec::Comma;
  1726. if (Current->is(TT_JsFatArrow))
  1727. return prec::Assignment;
  1728. if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
  1729. (Current->is(tok::comment) && NextNonComment &&
  1730. NextNonComment->is(TT_SelectorName)))
  1731. return 0;
  1732. if (Current->is(TT_RangeBasedForLoopColon))
  1733. return prec::Comma;
  1734. if ((Style.Language == FormatStyle::LK_Java ||
  1735. Style.Language == FormatStyle::LK_JavaScript) &&
  1736. Current->is(Keywords.kw_instanceof))
  1737. return prec::Relational;
  1738. if (Style.Language == FormatStyle::LK_JavaScript &&
  1739. Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
  1740. return prec::Relational;
  1741. if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
  1742. return Current->getPrecedence();
  1743. if (Current->isOneOf(tok::period, tok::arrow))
  1744. return PrecedenceArrowAndPeriod;
  1745. if ((Style.Language == FormatStyle::LK_Java ||
  1746. Style.Language == FormatStyle::LK_JavaScript) &&
  1747. Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
  1748. Keywords.kw_throws))
  1749. return 0;
  1750. }
  1751. return -1;
  1752. }
  1753. void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
  1754. Start->FakeLParens.push_back(Precedence);
  1755. if (Precedence > prec::Unknown)
  1756. Start->StartsBinaryExpression = true;
  1757. if (Current) {
  1758. FormatToken *Previous = Current->Previous;
  1759. while (Previous->is(tok::comment) && Previous->Previous)
  1760. Previous = Previous->Previous;
  1761. ++Previous->FakeRParens;
  1762. if (Precedence > prec::Unknown)
  1763. Previous->EndsBinaryExpression = true;
  1764. }
  1765. }
  1766. /// Parse unary operator expressions and surround them with fake
  1767. /// parentheses if appropriate.
  1768. void parseUnaryOperator() {
  1769. llvm::SmallVector<FormatToken *, 2> Tokens;
  1770. while (Current && Current->is(TT_UnaryOperator)) {
  1771. Tokens.push_back(Current);
  1772. next();
  1773. }
  1774. parse(PrecedenceArrowAndPeriod);
  1775. for (FormatToken *Token : llvm::reverse(Tokens))
  1776. // The actual precedence doesn't matter.
  1777. addFakeParenthesis(Token, prec::Unknown);
  1778. }
  1779. void parseConditionalExpr() {
  1780. while (Current && Current->isTrailingComment()) {
  1781. next();
  1782. }
  1783. FormatToken *Start = Current;
  1784. parse(prec::LogicalOr);
  1785. if (!Current || !Current->is(tok::question))
  1786. return;
  1787. next();
  1788. parse(prec::Assignment);
  1789. if (!Current || Current->isNot(TT_ConditionalExpr))
  1790. return;
  1791. next();
  1792. parse(prec::Assignment);
  1793. addFakeParenthesis(Start, prec::Conditional);
  1794. }
  1795. void next(bool SkipPastLeadingComments = true) {
  1796. if (Current)
  1797. Current = Current->Next;
  1798. while (Current &&
  1799. (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
  1800. Current->isTrailingComment())
  1801. Current = Current->Next;
  1802. }
  1803. const FormatStyle &Style;
  1804. const AdditionalKeywords &Keywords;
  1805. FormatToken *Current;
  1806. };
  1807. } // end anonymous namespace
  1808. void TokenAnnotator::setCommentLineLevels(
  1809. SmallVectorImpl<AnnotatedLine *> &Lines) {
  1810. const AnnotatedLine *NextNonCommentLine = nullptr;
  1811. for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
  1812. E = Lines.rend();
  1813. I != E; ++I) {
  1814. bool CommentLine = true;
  1815. for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
  1816. if (!Tok->is(tok::comment)) {
  1817. CommentLine = false;
  1818. break;
  1819. }
  1820. }
  1821. // If the comment is currently aligned with the line immediately following
  1822. // it, that's probably intentional and we should keep it.
  1823. if (NextNonCommentLine && CommentLine &&
  1824. NextNonCommentLine->First->NewlinesBefore <= 1 &&
  1825. NextNonCommentLine->First->OriginalColumn ==
  1826. (*I)->First->OriginalColumn) {
  1827. // Align comments for preprocessor lines with the # in column 0 if
  1828. // preprocessor lines are not indented. Otherwise, align with the next
  1829. // line.
  1830. (*I)->Level =
  1831. (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
  1832. (NextNonCommentLine->Type == LT_PreprocessorDirective ||
  1833. NextNonCommentLine->Type == LT_ImportStatement))
  1834. ? 0
  1835. : NextNonCommentLine->Level;
  1836. } else {
  1837. NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
  1838. }
  1839. setCommentLineLevels((*I)->Children);
  1840. }
  1841. }
  1842. static unsigned maxNestingDepth(const AnnotatedLine &Line) {
  1843. unsigned Result = 0;
  1844. for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
  1845. Result = std::max(Result, Tok->NestingLevel);
  1846. return Result;
  1847. }
  1848. void TokenAnnotator::annotate(AnnotatedLine &Line) {
  1849. for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
  1850. E = Line.Children.end();
  1851. I != E; ++I) {
  1852. annotate(**I);
  1853. }
  1854. AnnotatingParser Parser(Style, Line, Keywords);
  1855. Line.Type = Parser.parseLine();
  1856. // With very deep nesting, ExpressionParser uses lots of stack and the
  1857. // formatting algorithm is very slow. We're not going to do a good job here
  1858. // anyway - it's probably generated code being formatted by mistake.
  1859. // Just skip the whole line.
  1860. if (maxNestingDepth(Line) > 50)
  1861. Line.Type = LT_Invalid;
  1862. if (Line.Type == LT_Invalid)
  1863. return;
  1864. ExpressionParser ExprParser(Style, Keywords, Line);
  1865. ExprParser.parse();
  1866. if (Line.startsWith(TT_ObjCMethodSpecifier))
  1867. Line.Type = LT_ObjCMethodDecl;
  1868. else if (Line.startsWith(TT_ObjCDecl))
  1869. Line.Type = LT_ObjCDecl;
  1870. else if (Line.startsWith(TT_ObjCProperty))
  1871. Line.Type = LT_ObjCProperty;
  1872. Line.First->SpacesRequiredBefore = 1;
  1873. Line.First->CanBreakBefore = Line.First->MustBreakBefore;
  1874. }
  1875. // This function heuristically determines whether 'Current' starts the name of a
  1876. // function declaration.
  1877. static bool isFunctionDeclarationName(const FormatToken &Current,
  1878. const AnnotatedLine &Line) {
  1879. auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
  1880. for (; Next; Next = Next->Next) {
  1881. if (Next->is(TT_OverloadedOperatorLParen))
  1882. return Next;
  1883. if (Next->is(TT_OverloadedOperator))
  1884. continue;
  1885. if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
  1886. // For 'new[]' and 'delete[]'.
  1887. if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
  1888. Next->Next->Next->is(tok::r_square))
  1889. Next = Next->Next->Next;
  1890. continue;
  1891. }
  1892. break;
  1893. }
  1894. return nullptr;
  1895. };
  1896. // Find parentheses of parameter list.
  1897. const FormatToken *Next = Current.Next;
  1898. if (Current.is(tok::kw_operator)) {
  1899. if (Current.Previous && Current.Previous->is(tok::coloncolon))
  1900. return false;
  1901. Next = skipOperatorName(Next);
  1902. } else {
  1903. if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
  1904. return false;
  1905. for (; Next; Next = Next->Next) {
  1906. if (Next->is(TT_TemplateOpener)) {
  1907. Next = Next->MatchingParen;
  1908. } else if (Next->is(tok::coloncolon)) {
  1909. Next = Next->Next;
  1910. if (!Next)
  1911. return false;
  1912. if (Next->is(tok::kw_operator)) {
  1913. Next = skipOperatorName(Next->Next);
  1914. break;
  1915. }
  1916. if (!Next->is(tok::identifier))
  1917. return false;
  1918. } else if (Next->is(tok::l_paren)) {
  1919. break;
  1920. } else {
  1921. return false;
  1922. }
  1923. }
  1924. }
  1925. // Check whether parameter list can belong to a function declaration.
  1926. if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
  1927. return false;
  1928. // If the lines ends with "{", this is likely an function definition.
  1929. if (Line.Last->is(tok::l_brace))
  1930. return true;
  1931. if (Next->Next == Next->MatchingParen)
  1932. return true; // Empty parentheses.
  1933. // If there is an &/&& after the r_paren, this is likely a function.
  1934. if (Next->MatchingParen->Next &&
  1935. Next->MatchingParen->Next->is(TT_PointerOrReference))
  1936. return true;
  1937. for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
  1938. Tok = Tok->Next) {
  1939. if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
  1940. Tok = Tok->MatchingParen;
  1941. continue;
  1942. }
  1943. if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
  1944. Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
  1945. return true;
  1946. if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
  1947. Tok->Tok.isLiteral())
  1948. return false;
  1949. }
  1950. return false;
  1951. }
  1952. bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
  1953. assert(Line.MightBeFunctionDecl);
  1954. if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
  1955. Style.AlwaysBreakAfterReturnType ==
  1956. FormatStyle::RTBS_TopLevelDefinitions) &&
  1957. Line.Level > 0)
  1958. return false;
  1959. switch (Style.AlwaysBreakAfterReturnType) {
  1960. case FormatStyle::RTBS_None:
  1961. return false;
  1962. case FormatStyle::RTBS_All:
  1963. case FormatStyle::RTBS_TopLevel:
  1964. return true;
  1965. case FormatStyle::RTBS_AllDefinitions:
  1966. case FormatStyle::RTBS_TopLevelDefinitions:
  1967. return Line.mightBeFunctionDefinition();
  1968. }
  1969. return false;
  1970. }
  1971. void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
  1972. for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
  1973. E = Line.Children.end();
  1974. I != E; ++I) {
  1975. calculateFormattingInformation(**I);
  1976. }
  1977. Line.First->TotalLength =
  1978. Line.First->IsMultiline ? Style.ColumnLimit
  1979. : Line.FirstStartColumn + Line.First->ColumnWidth;
  1980. FormatToken *Current = Line.First->Next;
  1981. bool InFunctionDecl = Line.MightBeFunctionDecl;
  1982. while (Current) {
  1983. if (isFunctionDeclarationName(*Current, Line))
  1984. Current->Type = TT_FunctionDeclarationName;
  1985. if (Current->is(TT_LineComment)) {
  1986. if (Current->Previous->BlockKind == BK_BracedInit &&
  1987. Current->Previous->opensScope())
  1988. Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
  1989. else
  1990. Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
  1991. // If we find a trailing comment, iterate backwards to determine whether
  1992. // it seems to relate to a specific parameter. If so, break before that
  1993. // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
  1994. // to the previous line in:
  1995. // SomeFunction(a,
  1996. // b, // comment
  1997. // c);
  1998. if (!Current->HasUnescapedNewline) {
  1999. for (FormatToken *Parameter = Current->Previous; Parameter;
  2000. Parameter = Parameter->Previous) {
  2001. if (Parameter->isOneOf(tok::comment, tok::r_brace))
  2002. break;
  2003. if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
  2004. if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
  2005. Parameter->HasUnescapedNewline)
  2006. Parameter->MustBreakBefore = true;
  2007. break;
  2008. }
  2009. }
  2010. }
  2011. } else if (Current->SpacesRequiredBefore == 0 &&
  2012. spaceRequiredBefore(Line, *Current)) {
  2013. Current->SpacesRequiredBefore = 1;
  2014. }
  2015. Current->MustBreakBefore =
  2016. Current->MustBreakBefore || mustBreakBefore(Line, *Current);
  2017. if (!Current->MustBreakBefore && InFunctionDecl &&
  2018. Current->is(TT_FunctionDeclarationName))
  2019. Current->MustBreakBefore = mustBreakForReturnType(Line);
  2020. Current->CanBreakBefore =
  2021. Current->MustBreakBefore || canBreakBefore(Line, *Current);
  2022. unsigned ChildSize = 0;
  2023. if (Current->Previous->Children.size() == 1) {
  2024. FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
  2025. ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
  2026. : LastOfChild.TotalLength + 1;
  2027. }
  2028. const FormatToken *Prev = Current->Previous;
  2029. if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
  2030. (Prev->Children.size() == 1 &&
  2031. Prev->Children[0]->First->MustBreakBefore) ||
  2032. Current->IsMultiline)
  2033. Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
  2034. else
  2035. Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
  2036. ChildSize + Current->SpacesRequiredBefore;
  2037. if (Current->is(TT_CtorInitializerColon))
  2038. InFunctionDecl = false;
  2039. // FIXME: Only calculate this if CanBreakBefore is true once static
  2040. // initializers etc. are sorted out.
  2041. // FIXME: Move magic numbers to a better place.
  2042. // Reduce penalty for aligning ObjC method arguments using the colon
  2043. // alignment as this is the canonical way (still prefer fitting everything
  2044. // into one line if possible). Trying to fit a whole expression into one
  2045. // line should not force other line breaks (e.g. when ObjC method
  2046. // expression is a part of other expression).
  2047. Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
  2048. if (Style.Language == FormatStyle::LK_ObjC &&
  2049. Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
  2050. if (Current->ParameterIndex == 1)
  2051. Current->SplitPenalty += 5 * Current->BindingStrength;
  2052. } else {
  2053. Current->SplitPenalty += 20 * Current->BindingStrength;
  2054. }
  2055. Current = Current->Next;
  2056. }
  2057. calculateUnbreakableTailLengths(Line);
  2058. unsigned IndentLevel = Line.Level;
  2059. for (Current = Line.First; Current != nullptr; Current = Current->Next) {
  2060. if (Current->Role)
  2061. Current->Role->precomputeFormattingInfos(Current);
  2062. if (Current->MatchingParen &&
  2063. Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
  2064. assert(IndentLevel > 0);
  2065. --IndentLevel;
  2066. }
  2067. Current->IndentLevel = IndentLevel;
  2068. if (Current->opensBlockOrBlockTypeList(Style))
  2069. ++IndentLevel;
  2070. }
  2071. LLVM_DEBUG({ printDebugInfo(Line); });
  2072. }
  2073. void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
  2074. unsigned UnbreakableTailLength = 0;
  2075. FormatToken *Current = Line.Last;
  2076. while (Current) {
  2077. Current->UnbreakableTailLength = UnbreakableTailLength;
  2078. if (Current->CanBreakBefore ||
  2079. Current->isOneOf(tok::comment, tok::string_literal)) {
  2080. UnbreakableTailLength = 0;
  2081. } else {
  2082. UnbreakableTailLength +=
  2083. Current->ColumnWidth + Current->SpacesRequiredBefore;
  2084. }
  2085. Current = Current->Previous;
  2086. }
  2087. }
  2088. unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
  2089. const FormatToken &Tok,
  2090. bool InFunctionDecl) {
  2091. const FormatToken &Left = *Tok.Previous;
  2092. const FormatToken &Right = Tok;
  2093. if (Left.is(tok::semi))
  2094. return 0;
  2095. if (Style.Language == FormatStyle::LK_Java) {
  2096. if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
  2097. return 1;
  2098. if (Right.is(Keywords.kw_implements))
  2099. return 2;
  2100. if (Left.is(tok::comma) && Left.NestingLevel == 0)
  2101. return 3;
  2102. } else if (Style.Language == FormatStyle::LK_JavaScript) {
  2103. if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
  2104. return 100;
  2105. if (Left.is(TT_JsTypeColon))
  2106. return 35;
  2107. if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
  2108. (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
  2109. return 100;
  2110. // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
  2111. if (Left.opensScope() && Right.closesScope())
  2112. return 200;
  2113. }
  2114. if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
  2115. return 1;
  2116. if (Right.is(tok::l_square)) {
  2117. if (Style.Language == FormatStyle::LK_Proto)
  2118. return 1;
  2119. if (Left.is(tok::r_square))
  2120. return 200;
  2121. // Slightly prefer formatting local lambda definitions like functions.
  2122. if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
  2123. return 35;
  2124. if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
  2125. TT_ArrayInitializerLSquare,
  2126. TT_DesignatedInitializerLSquare, TT_AttributeSquare))
  2127. return 500;
  2128. }
  2129. if (Left.is(tok::coloncolon) ||
  2130. (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
  2131. return 500;
  2132. if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
  2133. Right.is(tok::kw_operator)) {
  2134. if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
  2135. return 3;
  2136. if (Left.is(TT_StartOfName))
  2137. return 110;
  2138. if (InFunctionDecl && Right.NestingLevel == 0)
  2139. return Style.PenaltyReturnTypeOnItsOwnLine;
  2140. return 200;
  2141. }
  2142. if (Right.is(TT_PointerOrReference))
  2143. return 190;
  2144. if (Right.is(TT_LambdaArrow))
  2145. return 110;
  2146. if (Left.is(tok::equal) && Right.is(tok::l_brace))
  2147. return 160;
  2148. if (Left.is(TT_CastRParen))
  2149. return 100;
  2150. if (Left.isOneOf(tok::kw_class, tok::kw_struct))
  2151. return 5000;
  2152. if (Left.is(tok::comment))
  2153. return 1000;
  2154. if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
  2155. TT_CtorInitializerColon))
  2156. return 2;
  2157. if (Right.isMemberAccess()) {
  2158. // Breaking before the "./->" of a chained call/member access is reasonably
  2159. // cheap, as formatting those with one call per line is generally
  2160. // desirable. In particular, it should be cheaper to break before the call
  2161. // than it is to break inside a call's parameters, which could lead to weird
  2162. // "hanging" indents. The exception is the very last "./->" to support this
  2163. // frequent pattern:
  2164. //
  2165. // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
  2166. // dddddddd);
  2167. //
  2168. // which might otherwise be blown up onto many lines. Here, clang-format
  2169. // won't produce "hanging" indents anyway as there is no other trailing
  2170. // call.
  2171. //
  2172. // Also apply higher penalty is not a call as that might lead to a wrapping
  2173. // like:
  2174. //
  2175. // aaaaaaa
  2176. // .aaaaaaaaa.bbbbbbbb(cccccccc);
  2177. return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
  2178. ? 150
  2179. : 35;
  2180. }
  2181. if (Right.is(TT_TrailingAnnotation) &&
  2182. (!Right.Next || Right.Next->isNot(tok::l_paren))) {
  2183. // Moving trailing annotations to the next line is fine for ObjC method
  2184. // declarations.
  2185. if (Line.startsWith(TT_ObjCMethodSpecifier))
  2186. return 10;
  2187. // Generally, breaking before a trailing annotation is bad unless it is
  2188. // function-like. It seems to be especially preferable to keep standard
  2189. // annotations (i.e. "const", "final" and "override") on the same line.
  2190. // Use a slightly higher penalty after ")" so that annotations like
  2191. // "const override" are kept together.
  2192. bool is_short_annotation = Right.TokenText.size() < 10;
  2193. return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
  2194. }
  2195. // In for-loops, prefer breaking at ',' and ';'.
  2196. if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
  2197. return 4;
  2198. // In Objective-C method expressions, prefer breaking before "param:" over
  2199. // breaking after it.
  2200. if (Right.is(TT_SelectorName))
  2201. return 0;
  2202. if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
  2203. return Line.MightBeFunctionDecl ? 50 : 500;
  2204. // In Objective-C type declarations, avoid breaking after the category's
  2205. // open paren (we'll prefer breaking after the protocol list's opening
  2206. // angle bracket, if present).
  2207. if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
  2208. Left.Previous->isOneOf(tok::identifier, tok::greater))
  2209. return 500;
  2210. if (Left.is(tok::l_paren) && InFunctionDecl &&
  2211. Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
  2212. return 100;
  2213. if (Left.is(tok::l_paren) && Left.Previous &&
  2214. (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
  2215. Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
  2216. return 1000;
  2217. if (Left.is(tok::equal) && InFunctionDecl)
  2218. return 110;
  2219. if (Right.is(tok::r_brace))
  2220. return 1;
  2221. if (Left.is(TT_TemplateOpener))
  2222. return 100;
  2223. if (Left.opensScope()) {
  2224. if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
  2225. return 0;
  2226. if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
  2227. return 19;
  2228. return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
  2229. : 19;
  2230. }
  2231. if (Left.is(TT_JavaAnnotation))
  2232. return 50;
  2233. if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
  2234. Left.Previous->isLabelString() &&
  2235. (Left.NextOperator || Left.OperatorIndex != 0))
  2236. return 50;
  2237. if (Right.is(tok::plus) && Left.isLabelString() &&
  2238. (Right.NextOperator || Right.OperatorIndex != 0))
  2239. return 25;
  2240. if (Left.is(tok::comma))
  2241. return 1;
  2242. if (Right.is(tok::lessless) && Left.isLabelString() &&
  2243. (Right.NextOperator || Right.OperatorIndex != 1))
  2244. return 25;
  2245. if (Right.is(tok::lessless)) {
  2246. // Breaking at a << is really cheap.
  2247. if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
  2248. // Slightly prefer to break before the first one in log-like statements.
  2249. return 2;
  2250. return 1;
  2251. }
  2252. if (Left.ClosesTemplateDeclaration)
  2253. return Style.PenaltyBreakTemplateDeclaration;
  2254. if (Left.is(TT_ConditionalExpr))
  2255. return prec::Conditional;
  2256. prec::Level Level = Left.getPrecedence();
  2257. if (Level == prec::Unknown)
  2258. Level = Right.getPrecedence();
  2259. if (Level == prec::Assignment)
  2260. return Style.PenaltyBreakAssignment;
  2261. if (Level != prec::Unknown)
  2262. return Level;
  2263. return 3;
  2264. }
  2265. bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
  2266. return Style.SpaceBeforeParens == FormatStyle::SBPO_Always ||
  2267. (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses &&
  2268. Right.ParameterCount > 0);
  2269. }
  2270. bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
  2271. const FormatToken &Left,
  2272. const FormatToken &Right) {
  2273. if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
  2274. return true;
  2275. if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
  2276. return true;
  2277. if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
  2278. Left.Tok.getObjCKeywordID() == tok::objc_property)
  2279. return true;
  2280. if (Right.is(tok::hashhash))
  2281. return Left.is(tok::hash);
  2282. if (Left.isOneOf(tok::hashhash, tok::hash))
  2283. return Right.is(tok::hash);
  2284. if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
  2285. return Style.SpaceInEmptyParentheses;
  2286. if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
  2287. return (Right.is(TT_CastRParen) ||
  2288. (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
  2289. ? Style.SpacesInCStyleCastParentheses
  2290. : Style.SpacesInParentheses;
  2291. if (Right.isOneOf(tok::semi, tok::comma))
  2292. return false;
  2293. if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
  2294. bool IsLightweightGeneric = Right.MatchingParen &&
  2295. Right.MatchingParen->Next &&
  2296. Right.MatchingParen->Next->is(tok::colon);
  2297. return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
  2298. }
  2299. if (Right.is(tok::less) && Left.is(tok::kw_template))
  2300. return Style.SpaceAfterTemplateKeyword;
  2301. if (Left.isOneOf(tok::exclaim, tok::tilde))
  2302. return false;
  2303. if (Left.is(tok::at) &&
  2304. Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
  2305. tok::numeric_constant, tok::l_paren, tok::l_brace,
  2306. tok::kw_true, tok::kw_false))
  2307. return false;
  2308. if (Left.is(tok::colon))
  2309. return !Left.is(TT_ObjCMethodExpr);
  2310. if (Left.is(tok::coloncolon))
  2311. return false;
  2312. if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
  2313. if (Style.Language == FormatStyle::LK_TextProto ||
  2314. (Style.Language == FormatStyle::LK_Proto &&
  2315. (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
  2316. // Format empty list as `<>`.
  2317. if (Left.is(tok::less) && Right.is(tok::greater))
  2318. return false;
  2319. return !Style.Cpp11BracedListStyle;
  2320. }
  2321. return false;
  2322. }
  2323. if (Right.is(tok::ellipsis))
  2324. return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
  2325. Left.Previous->is(tok::kw_case));
  2326. if (Left.is(tok::l_square) && Right.is(tok::amp))
  2327. return false;
  2328. if (Right.is(TT_PointerOrReference)) {
  2329. if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
  2330. if (!Left.MatchingParen)
  2331. return true;
  2332. FormatToken *TokenBeforeMatchingParen =
  2333. Left.MatchingParen->getPreviousNonComment();
  2334. if (!TokenBeforeMatchingParen ||
  2335. !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
  2336. return true;
  2337. }
  2338. return (Left.Tok.isLiteral() ||
  2339. (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
  2340. (Style.PointerAlignment != FormatStyle::PAS_Left ||
  2341. (Line.IsMultiVariableDeclStmt &&
  2342. (Left.NestingLevel == 0 ||
  2343. (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
  2344. }
  2345. if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
  2346. (!Left.is(TT_PointerOrReference) ||
  2347. (Style.PointerAlignment != FormatStyle::PAS_Right &&
  2348. !Line.IsMultiVariableDeclStmt)))
  2349. return true;
  2350. if (Left.is(TT_PointerOrReference))
  2351. return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
  2352. (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
  2353. !Right.is(TT_StartOfName)) ||
  2354. (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
  2355. (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
  2356. tok::l_paren) &&
  2357. (Style.PointerAlignment != FormatStyle::PAS_Right &&
  2358. !Line.IsMultiVariableDeclStmt) &&
  2359. Left.Previous &&
  2360. !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
  2361. if (Right.is(tok::star) && Left.is(tok::l_paren))
  2362. return false;
  2363. const auto SpaceRequiredForArrayInitializerLSquare =
  2364. [](const FormatToken &LSquareTok, const FormatStyle &Style) {
  2365. return Style.SpacesInContainerLiterals ||
  2366. ((Style.Language == FormatStyle::LK_Proto ||
  2367. Style.Language == FormatStyle::LK_TextProto) &&
  2368. !Style.Cpp11BracedListStyle &&
  2369. LSquareTok.endsSequence(tok::l_square, tok::colon,
  2370. TT_SelectorName));
  2371. };
  2372. if (Left.is(tok::l_square))
  2373. return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
  2374. SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
  2375. (Left.isOneOf(TT_ArraySubscriptLSquare,
  2376. TT_StructuredBindingLSquare) &&
  2377. Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
  2378. if (Right.is(tok::r_square))
  2379. return Right.MatchingParen &&
  2380. ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
  2381. SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
  2382. Style)) ||
  2383. (Style.SpacesInSquareBrackets &&
  2384. Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
  2385. TT_StructuredBindingLSquare)) ||
  2386. Right.MatchingParen->is(TT_AttributeParen));
  2387. if (Right.is(tok::l_square) &&
  2388. !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
  2389. TT_DesignatedInitializerLSquare,
  2390. TT_StructuredBindingLSquare, TT_AttributeSquare) &&
  2391. !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
  2392. return false;
  2393. if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
  2394. return !Left.Children.empty(); // No spaces in "{}".
  2395. if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
  2396. (Right.is(tok::r_brace) && Right.MatchingParen &&
  2397. Right.MatchingParen->BlockKind != BK_Block))
  2398. return !Style.Cpp11BracedListStyle;
  2399. if (Left.is(TT_BlockComment))
  2400. // No whitespace in x(/*foo=*/1), except for JavaScript.
  2401. return Style.Language == FormatStyle::LK_JavaScript ||
  2402. !Left.TokenText.endswith("=*/");
  2403. if (Right.is(tok::l_paren)) {
  2404. if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
  2405. (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
  2406. return true;
  2407. return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
  2408. (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
  2409. (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
  2410. tok::kw_switch, tok::kw_case, TT_ForEachMacro,
  2411. TT_ObjCForIn) ||
  2412. Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
  2413. (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
  2414. tok::kw_new, tok::kw_delete) &&
  2415. (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
  2416. (spaceRequiredBeforeParens(Right) &&
  2417. (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
  2418. Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier() ||
  2419. (Left.is(tok::r_square) && Left.MatchingParen &&
  2420. Left.MatchingParen->is(TT_LambdaLSquare))) &&
  2421. Line.Type != LT_PreprocessorDirective);
  2422. }
  2423. if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
  2424. return false;
  2425. if (Right.is(TT_UnaryOperator))
  2426. return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
  2427. (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
  2428. if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
  2429. tok::r_paren) ||
  2430. Left.isSimpleTypeSpecifier()) &&
  2431. Right.is(tok::l_brace) && Right.getNextNonComment() &&
  2432. Right.BlockKind != BK_Block)
  2433. return false;
  2434. if (Left.is(tok::period) || Right.is(tok::period))
  2435. return false;
  2436. if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
  2437. return false;
  2438. if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
  2439. Left.MatchingParen->Previous &&
  2440. (Left.MatchingParen->Previous->is(tok::period) ||
  2441. Left.MatchingParen->Previous->is(tok::coloncolon)))
  2442. // Java call to generic function with explicit type:
  2443. // A.<B<C<...>>>DoSomething();
  2444. // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference.
  2445. return false;
  2446. if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
  2447. return false;
  2448. if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
  2449. // Objective-C dictionary literal -> no space after opening brace.
  2450. return false;
  2451. if (Right.is(tok::r_brace) && Right.MatchingParen &&
  2452. Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
  2453. // Objective-C dictionary literal -> no space before closing brace.
  2454. return false;
  2455. return true;
  2456. }
  2457. bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
  2458. const FormatToken &Right) {
  2459. const FormatToken &Left = *Right.Previous;
  2460. if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
  2461. return true; // Never ever merge two identifiers.
  2462. if (Style.isCpp()) {
  2463. if (Left.is(tok::kw_operator))
  2464. return Right.is(tok::coloncolon);
  2465. if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
  2466. !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
  2467. return true;
  2468. } else if (Style.Language == FormatStyle::LK_Proto ||
  2469. Style.Language == FormatStyle::LK_TextProto) {
  2470. if (Right.is(tok::period) &&
  2471. Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
  2472. Keywords.kw_repeated, Keywords.kw_extend))
  2473. return true;
  2474. if (Right.is(tok::l_paren) &&
  2475. Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
  2476. return true;
  2477. if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
  2478. return true;
  2479. // Slashes occur in text protocol extension syntax: [type/type] { ... }.
  2480. if (Left.is(tok::slash) || Right.is(tok::slash))
  2481. return false;
  2482. if (Left.MatchingParen &&
  2483. Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
  2484. Right.isOneOf(tok::l_brace, tok::less))
  2485. return !Style.Cpp11BracedListStyle;
  2486. // A percent is probably part of a formatting specification, such as %lld.
  2487. if (Left.is(tok::percent))
  2488. return false;
  2489. // Preserve the existence of a space before a percent for cases like 0x%04x
  2490. // and "%d %d"
  2491. if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
  2492. return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
  2493. } else if (Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
  2494. if (Left.is(TT_JsFatArrow))
  2495. return true;
  2496. // for await ( ...
  2497. if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
  2498. Left.Previous->is(tok::kw_for))
  2499. return true;
  2500. if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
  2501. Right.MatchingParen) {
  2502. const FormatToken *Next = Right.MatchingParen->getNextNonComment();
  2503. // An async arrow function, for example: `x = async () => foo();`,
  2504. // as opposed to calling a function called async: `x = async();`
  2505. if (Next && Next->is(TT_JsFatArrow))
  2506. return true;
  2507. }
  2508. if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
  2509. (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
  2510. return false;
  2511. // In tagged template literals ("html`bar baz`"), there is no space between
  2512. // the tag identifier and the template string. getIdentifierInfo makes sure
  2513. // that the identifier is not a pseudo keyword like `yield`, either.
  2514. if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
  2515. Right.is(TT_TemplateString))
  2516. return false;
  2517. if (Right.is(tok::star) &&
  2518. Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
  2519. return false;
  2520. if (Right.isOneOf(tok::l_brace, tok::l_square) &&
  2521. Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
  2522. Keywords.kw_extends, Keywords.kw_implements))
  2523. return true;
  2524. if (Right.is(tok::l_paren)) {
  2525. // JS methods can use some keywords as names (e.g. `delete()`).
  2526. if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
  2527. return false;
  2528. // Valid JS method names can include keywords, e.g. `foo.delete()` or
  2529. // `bar.instanceof()`. Recognize call positions by preceding period.
  2530. if (Left.Previous && Left.Previous->is(tok::period) &&
  2531. Left.Tok.getIdentifierInfo())
  2532. return false;
  2533. // Additional unary JavaScript operators that need a space after.
  2534. if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
  2535. tok::kw_void))
  2536. return true;
  2537. }
  2538. if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
  2539. tok::kw_const) ||
  2540. // "of" is only a keyword if it appears after another identifier
  2541. // (e.g. as "const x of y" in a for loop), or after a destructuring
  2542. // operation (const [x, y] of z, const {a, b} of c).
  2543. (Left.is(Keywords.kw_of) && Left.Previous &&
  2544. (Left.Previous->Tok.is(tok::identifier) ||
  2545. Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
  2546. (!Left.Previous || !Left.Previous->is(tok::period)))
  2547. return true;
  2548. if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
  2549. Left.Previous->is(tok::period) && Right.is(tok::l_paren))
  2550. return false;
  2551. if (Left.is(Keywords.kw_as) &&
  2552. Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
  2553. return true;
  2554. if (Left.is(tok::kw_default) && Left.Previous &&
  2555. Left.Previous->is(tok::kw_export))
  2556. return true;
  2557. if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
  2558. return true;
  2559. if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
  2560. return false;
  2561. if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
  2562. return false;
  2563. if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
  2564. Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
  2565. return false;
  2566. if (Left.is(tok::ellipsis))
  2567. return false;
  2568. if (Left.is(TT_TemplateCloser) &&
  2569. !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
  2570. Keywords.kw_implements, Keywords.kw_extends))
  2571. // Type assertions ('<type>expr') are not followed by whitespace. Other
  2572. // locations that should have whitespace following are identified by the
  2573. // above set of follower tokens.
  2574. return false;
  2575. if (Right.is(TT_JsNonNullAssertion))
  2576. return false;
  2577. if (Left.is(TT_JsNonNullAssertion) &&
  2578. Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
  2579. return true; // "x! as string", "x! in y"
  2580. } else if (Style.Language == FormatStyle::LK_Java) {
  2581. if (Left.is(tok::r_square) && Right.is(tok::l_brace))
  2582. return true;
  2583. if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
  2584. return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
  2585. if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
  2586. tok::kw_protected) ||
  2587. Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
  2588. Keywords.kw_native)) &&
  2589. Right.is(TT_TemplateOpener))
  2590. return true;
  2591. }
  2592. if (Left.is(TT_ImplicitStringLiteral))
  2593. return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
  2594. if (Line.Type == LT_ObjCMethodDecl) {
  2595. if (Left.is(TT_ObjCMethodSpecifier))
  2596. return true;
  2597. if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
  2598. // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
  2599. // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
  2600. // method declaration.
  2601. return false;
  2602. }
  2603. if (Line.Type == LT_ObjCProperty &&
  2604. (Right.is(tok::equal) || Left.is(tok::equal)))
  2605. return false;
  2606. if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
  2607. Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
  2608. return true;
  2609. if (Right.is(TT_OverloadedOperatorLParen))
  2610. return spaceRequiredBeforeParens(Right);
  2611. if (Left.is(tok::comma))
  2612. return true;
  2613. if (Right.is(tok::comma))
  2614. return false;
  2615. if (Right.is(TT_ObjCBlockLParen))
  2616. return true;
  2617. if (Right.is(TT_CtorInitializerColon))
  2618. return Style.SpaceBeforeCtorInitializerColon;
  2619. if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
  2620. return false;
  2621. if (Right.is(TT_RangeBasedForLoopColon) &&
  2622. !Style.SpaceBeforeRangeBasedForLoopColon)
  2623. return false;
  2624. if (Right.is(tok::colon)) {
  2625. if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
  2626. !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
  2627. return false;
  2628. if (Right.is(TT_ObjCMethodExpr))
  2629. return false;
  2630. if (Left.is(tok::question))
  2631. return false;
  2632. if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
  2633. return false;
  2634. if (Right.is(TT_DictLiteral))
  2635. return Style.SpacesInContainerLiterals;
  2636. if (Right.is(TT_AttributeColon))
  2637. return false;
  2638. return true;
  2639. }
  2640. if (Left.is(TT_UnaryOperator))
  2641. return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
  2642. Right.is(TT_BinaryOperator);
  2643. // If the next token is a binary operator or a selector name, we have
  2644. // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
  2645. if (Left.is(TT_CastRParen))
  2646. return Style.SpaceAfterCStyleCast ||
  2647. Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
  2648. if (Left.is(tok::greater) && Right.is(tok::greater)) {
  2649. if (Style.Language == FormatStyle::LK_TextProto ||
  2650. (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
  2651. return !Style.Cpp11BracedListStyle;
  2652. return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
  2653. (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
  2654. }
  2655. if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
  2656. Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
  2657. (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
  2658. return false;
  2659. if (!Style.SpaceBeforeAssignmentOperators &&
  2660. Right.getPrecedence() == prec::Assignment)
  2661. return false;
  2662. if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
  2663. (Left.is(tok::identifier) || Left.is(tok::kw_this)))
  2664. return false;
  2665. if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
  2666. // Generally don't remove existing spaces between an identifier and "::".
  2667. // The identifier might actually be a macro name such as ALWAYS_INLINE. If
  2668. // this turns out to be too lenient, add analysis of the identifier itself.
  2669. return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
  2670. if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
  2671. return (Left.is(TT_TemplateOpener) &&
  2672. Style.Standard == FormatStyle::LS_Cpp03) ||
  2673. !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
  2674. tok::kw___super, TT_TemplateCloser,
  2675. TT_TemplateOpener)) ||
  2676. (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
  2677. if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
  2678. return Style.SpacesInAngles;
  2679. // Space before TT_StructuredBindingLSquare.
  2680. if (Right.is(TT_StructuredBindingLSquare))
  2681. return !Left.isOneOf(tok::amp, tok::ampamp) ||
  2682. Style.PointerAlignment != FormatStyle::PAS_Right;
  2683. // Space before & or && following a TT_StructuredBindingLSquare.
  2684. if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
  2685. Right.isOneOf(tok::amp, tok::ampamp))
  2686. return Style.PointerAlignment != FormatStyle::PAS_Left;
  2687. if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
  2688. (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
  2689. !Right.is(tok::r_paren)))
  2690. return true;
  2691. if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
  2692. Right.isNot(TT_FunctionTypeLParen))
  2693. return spaceRequiredBeforeParens(Right);
  2694. if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
  2695. Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
  2696. return false;
  2697. if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
  2698. Line.startsWith(tok::hash))
  2699. return true;
  2700. if (Right.is(TT_TrailingUnaryOperator))
  2701. return false;
  2702. if (Left.is(TT_RegexLiteral))
  2703. return false;
  2704. return spaceRequiredBetween(Line, Left, Right);
  2705. }
  2706. // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
  2707. static bool isAllmanBrace(const FormatToken &Tok) {
  2708. return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
  2709. !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
  2710. }
  2711. bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
  2712. const FormatToken &Right) {
  2713. const FormatToken &Left = *Right.Previous;
  2714. if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
  2715. return true;
  2716. if (Style.Language == FormatStyle::LK_JavaScript) {
  2717. // FIXME: This might apply to other languages and token kinds.
  2718. if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
  2719. Left.Previous->is(tok::string_literal))
  2720. return true;
  2721. if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
  2722. Left.Previous && Left.Previous->is(tok::equal) &&
  2723. Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
  2724. tok::kw_const) &&
  2725. // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
  2726. // above.
  2727. !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
  2728. // Object literals on the top level of a file are treated as "enum-style".
  2729. // Each key/value pair is put on a separate line, instead of bin-packing.
  2730. return true;
  2731. if (Left.is(tok::l_brace) && Line.Level == 0 &&
  2732. (Line.startsWith(tok::kw_enum) ||
  2733. Line.startsWith(tok::kw_const, tok::kw_enum) ||
  2734. Line.startsWith(tok::kw_export, tok::kw_enum) ||
  2735. Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
  2736. // JavaScript top-level enum key/value pairs are put on separate lines
  2737. // instead of bin-packing.
  2738. return true;
  2739. if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
  2740. !Left.Children.empty())
  2741. // Support AllowShortFunctionsOnASingleLine for JavaScript.
  2742. return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
  2743. Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
  2744. (Left.NestingLevel == 0 && Line.Level == 0 &&
  2745. Style.AllowShortFunctionsOnASingleLine &
  2746. FormatStyle::SFS_InlineOnly);
  2747. } else if (Style.Language == FormatStyle::LK_Java) {
  2748. if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
  2749. Right.Next->is(tok::string_literal))
  2750. return true;
  2751. } else if (Style.Language == FormatStyle::LK_Cpp ||
  2752. Style.Language == FormatStyle::LK_ObjC ||
  2753. Style.Language == FormatStyle::LK_Proto ||
  2754. Style.Language == FormatStyle::LK_TableGen ||
  2755. Style.Language == FormatStyle::LK_TextProto) {
  2756. if (Left.isStringLiteral() && Right.isStringLiteral())
  2757. return true;
  2758. }
  2759. // If the last token before a '}', ']', or ')' is a comma or a trailing
  2760. // comment, the intention is to insert a line break after it in order to make
  2761. // shuffling around entries easier. Import statements, especially in
  2762. // JavaScript, can be an exception to this rule.
  2763. if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
  2764. const FormatToken *BeforeClosingBrace = nullptr;
  2765. if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
  2766. (Style.Language == FormatStyle::LK_JavaScript &&
  2767. Left.is(tok::l_paren))) &&
  2768. Left.BlockKind != BK_Block && Left.MatchingParen)
  2769. BeforeClosingBrace = Left.MatchingParen->Previous;
  2770. else if (Right.MatchingParen &&
  2771. (Right.MatchingParen->isOneOf(tok::l_brace,
  2772. TT_ArrayInitializerLSquare) ||
  2773. (Style.Language == FormatStyle::LK_JavaScript &&
  2774. Right.MatchingParen->is(tok::l_paren))))
  2775. BeforeClosingBrace = &Left;
  2776. if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
  2777. BeforeClosingBrace->isTrailingComment()))
  2778. return true;
  2779. }
  2780. if (Right.is(tok::comment))
  2781. return Left.BlockKind != BK_BracedInit &&
  2782. Left.isNot(TT_CtorInitializerColon) &&
  2783. (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
  2784. if (Left.isTrailingComment())
  2785. return true;
  2786. if (Right.Previous->IsUnterminatedLiteral)
  2787. return true;
  2788. if (Right.is(tok::lessless) && Right.Next &&
  2789. Right.Previous->is(tok::string_literal) &&
  2790. Right.Next->is(tok::string_literal))
  2791. return true;
  2792. if (Right.Previous->ClosesTemplateDeclaration &&
  2793. Right.Previous->MatchingParen &&
  2794. Right.Previous->MatchingParen->NestingLevel == 0 &&
  2795. Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
  2796. return true;
  2797. if (Right.is(TT_CtorInitializerComma) &&
  2798. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
  2799. !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  2800. return true;
  2801. if (Right.is(TT_CtorInitializerColon) &&
  2802. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
  2803. !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  2804. return true;
  2805. // Break only if we have multiple inheritance.
  2806. if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
  2807. Right.is(TT_InheritanceComma))
  2808. return true;
  2809. if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
  2810. // Multiline raw string literals are special wrt. line breaks. The author
  2811. // has made a deliberate choice and might have aligned the contents of the
  2812. // string literal accordingly. Thus, we try keep existing line breaks.
  2813. return Right.IsMultiline && Right.NewlinesBefore > 0;
  2814. if ((Right.Previous->is(tok::l_brace) ||
  2815. (Right.Previous->is(tok::less) && Right.Previous->Previous &&
  2816. Right.Previous->Previous->is(tok::equal))) &&
  2817. Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
  2818. // Don't put enums or option definitions onto single lines in protocol
  2819. // buffers.
  2820. return true;
  2821. }
  2822. if (Right.is(TT_InlineASMBrace))
  2823. return Right.HasUnescapedNewline;
  2824. if (isAllmanBrace(Left) || isAllmanBrace(Right))
  2825. return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
  2826. (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
  2827. Style.BraceWrapping.AfterEnum) ||
  2828. (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
  2829. (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
  2830. if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
  2831. return true;
  2832. if (Left.is(TT_LambdaLBrace)) {
  2833. if (Left.MatchingParen && Left.MatchingParen->Next &&
  2834. Left.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren) &&
  2835. Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
  2836. return false;
  2837. if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
  2838. Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
  2839. (!Left.Children.empty() &&
  2840. Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty))
  2841. return true;
  2842. }
  2843. // Put multiple C# attributes on a new line.
  2844. if (Style.isCSharp() &&
  2845. ((Left.is(TT_AttributeSquare) && Left.is(tok::r_square)) ||
  2846. (Left.is(tok::r_square) && Right.is(TT_AttributeSquare) &&
  2847. Right.is(tok::l_square))))
  2848. return true;
  2849. // Put multiple Java annotation on a new line.
  2850. if ((Style.Language == FormatStyle::LK_Java ||
  2851. Style.Language == FormatStyle::LK_JavaScript) &&
  2852. Left.is(TT_LeadingJavaAnnotation) &&
  2853. Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
  2854. (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
  2855. return true;
  2856. if (Right.is(TT_ProtoExtensionLSquare))
  2857. return true;
  2858. // In text proto instances if a submessage contains at least 2 entries and at
  2859. // least one of them is a submessage, like A { ... B { ... } ... },
  2860. // put all of the entries of A on separate lines by forcing the selector of
  2861. // the submessage B to be put on a newline.
  2862. //
  2863. // Example: these can stay on one line:
  2864. // a { scalar_1: 1 scalar_2: 2 }
  2865. // a { b { key: value } }
  2866. //
  2867. // and these entries need to be on a new line even if putting them all in one
  2868. // line is under the column limit:
  2869. // a {
  2870. // scalar: 1
  2871. // b { key: value }
  2872. // }
  2873. //
  2874. // We enforce this by breaking before a submessage field that has previous
  2875. // siblings, *and* breaking before a field that follows a submessage field.
  2876. //
  2877. // Be careful to exclude the case [proto.ext] { ... } since the `]` is
  2878. // the TT_SelectorName there, but we don't want to break inside the brackets.
  2879. //
  2880. // Another edge case is @submessage { key: value }, which is a common
  2881. // substitution placeholder. In this case we want to keep `@` and `submessage`
  2882. // together.
  2883. //
  2884. // We ensure elsewhere that extensions are always on their own line.
  2885. if ((Style.Language == FormatStyle::LK_Proto ||
  2886. Style.Language == FormatStyle::LK_TextProto) &&
  2887. Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
  2888. // Keep `@submessage` together in:
  2889. // @submessage { key: value }
  2890. if (Right.Previous && Right.Previous->is(tok::at))
  2891. return false;
  2892. // Look for the scope opener after selector in cases like:
  2893. // selector { ...
  2894. // selector: { ...
  2895. // selector: @base { ...
  2896. FormatToken *LBrace = Right.Next;
  2897. if (LBrace && LBrace->is(tok::colon)) {
  2898. LBrace = LBrace->Next;
  2899. if (LBrace && LBrace->is(tok::at)) {
  2900. LBrace = LBrace->Next;
  2901. if (LBrace)
  2902. LBrace = LBrace->Next;
  2903. }
  2904. }
  2905. if (LBrace &&
  2906. // The scope opener is one of {, [, <:
  2907. // selector { ... }
  2908. // selector [ ... ]
  2909. // selector < ... >
  2910. //
  2911. // In case of selector { ... }, the l_brace is TT_DictLiteral.
  2912. // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
  2913. // so we check for immediately following r_brace.
  2914. ((LBrace->is(tok::l_brace) &&
  2915. (LBrace->is(TT_DictLiteral) ||
  2916. (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
  2917. LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
  2918. // If Left.ParameterCount is 0, then this submessage entry is not the
  2919. // first in its parent submessage, and we want to break before this entry.
  2920. // If Left.ParameterCount is greater than 0, then its parent submessage
  2921. // might contain 1 or more entries and we want to break before this entry
  2922. // if it contains at least 2 entries. We deal with this case later by
  2923. // detecting and breaking before the next entry in the parent submessage.
  2924. if (Left.ParameterCount == 0)
  2925. return true;
  2926. // However, if this submessage is the first entry in its parent
  2927. // submessage, Left.ParameterCount might be 1 in some cases.
  2928. // We deal with this case later by detecting an entry
  2929. // following a closing paren of this submessage.
  2930. }
  2931. // If this is an entry immediately following a submessage, it will be
  2932. // preceded by a closing paren of that submessage, like in:
  2933. // left---. .---right
  2934. // v v
  2935. // sub: { ... } key: value
  2936. // If there was a comment between `}` an `key` above, then `key` would be
  2937. // put on a new line anyways.
  2938. if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
  2939. return true;
  2940. }
  2941. // Deal with lambda arguments in C++ - we want consistent line breaks whether
  2942. // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
  2943. // as aggressive line breaks are placed when the lambda is not the last arg.
  2944. if ((Style.Language == FormatStyle::LK_Cpp ||
  2945. Style.Language == FormatStyle::LK_ObjC) &&
  2946. Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
  2947. !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
  2948. // Multiple lambdas in the same function call force line breaks.
  2949. if (Left.BlockParameterCount > 1)
  2950. return true;
  2951. // A lambda followed by another arg forces a line break.
  2952. if (!Left.Role)
  2953. return false;
  2954. auto Comma = Left.Role->lastComma();
  2955. if (!Comma)
  2956. return false;
  2957. auto Next = Comma->getNextNonComment();
  2958. if (!Next)
  2959. return false;
  2960. if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
  2961. return true;
  2962. }
  2963. return false;
  2964. }
  2965. bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
  2966. const FormatToken &Right) {
  2967. const FormatToken &Left = *Right.Previous;
  2968. // Language-specific stuff.
  2969. if (Style.Language == FormatStyle::LK_Java) {
  2970. if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
  2971. Keywords.kw_implements))
  2972. return false;
  2973. if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
  2974. Keywords.kw_implements))
  2975. return true;
  2976. } else if (Style.Language == FormatStyle::LK_JavaScript) {
  2977. const FormatToken *NonComment = Right.getPreviousNonComment();
  2978. if (NonComment &&
  2979. NonComment->isOneOf(
  2980. tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
  2981. tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
  2982. tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
  2983. Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
  2984. Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
  2985. return false; // Otherwise automatic semicolon insertion would trigger.
  2986. if (Right.NestingLevel == 0 &&
  2987. (Left.Tok.getIdentifierInfo() ||
  2988. Left.isOneOf(tok::r_square, tok::r_paren)) &&
  2989. Right.isOneOf(tok::l_square, tok::l_paren))
  2990. return false; // Otherwise automatic semicolon insertion would trigger.
  2991. if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
  2992. return false;
  2993. if (Left.is(TT_JsTypeColon))
  2994. return true;
  2995. // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
  2996. if (Left.is(tok::exclaim) && Right.is(tok::colon))
  2997. return false;
  2998. // Look for is type annotations like:
  2999. // function f(): a is B { ... }
  3000. // Do not break before is in these cases.
  3001. if (Right.is(Keywords.kw_is)) {
  3002. const FormatToken *Next = Right.getNextNonComment();
  3003. // If `is` is followed by a colon, it's likely that it's a dict key, so
  3004. // ignore it for this check.
  3005. // For example this is common in Polymer:
  3006. // Polymer({
  3007. // is: 'name',
  3008. // ...
  3009. // });
  3010. if (!Next || !Next->is(tok::colon))
  3011. return false;
  3012. }
  3013. if (Left.is(Keywords.kw_in))
  3014. return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
  3015. if (Right.is(Keywords.kw_in))
  3016. return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
  3017. if (Right.is(Keywords.kw_as))
  3018. return false; // must not break before as in 'x as type' casts
  3019. if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
  3020. // extends and infer can appear as keywords in conditional types:
  3021. // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
  3022. // do not break before them, as the expressions are subject to ASI.
  3023. return false;
  3024. }
  3025. if (Left.is(Keywords.kw_as))
  3026. return true;
  3027. if (Left.is(TT_JsNonNullAssertion))
  3028. return true;
  3029. if (Left.is(Keywords.kw_declare) &&
  3030. Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
  3031. Keywords.kw_function, tok::kw_class, tok::kw_enum,
  3032. Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
  3033. Keywords.kw_let, tok::kw_const))
  3034. // See grammar for 'declare' statements at:
  3035. // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
  3036. return false;
  3037. if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
  3038. Right.isOneOf(tok::identifier, tok::string_literal))
  3039. return false; // must not break in "module foo { ...}"
  3040. if (Right.is(TT_TemplateString) && Right.closesScope())
  3041. return false;
  3042. // Don't split tagged template literal so there is a break between the tag
  3043. // identifier and template string.
  3044. if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) {
  3045. return false;
  3046. }
  3047. if (Left.is(TT_TemplateString) && Left.opensScope())
  3048. return true;
  3049. }
  3050. if (Left.is(tok::at))
  3051. return false;
  3052. if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
  3053. return false;
  3054. if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
  3055. return !Right.is(tok::l_paren);
  3056. if (Right.is(TT_PointerOrReference))
  3057. return Line.IsMultiVariableDeclStmt ||
  3058. (Style.PointerAlignment == FormatStyle::PAS_Right &&
  3059. (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
  3060. if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
  3061. Right.is(tok::kw_operator))
  3062. return true;
  3063. if (Left.is(TT_PointerOrReference))
  3064. return false;
  3065. if (Right.isTrailingComment())
  3066. // We rely on MustBreakBefore being set correctly here as we should not
  3067. // change the "binding" behavior of a comment.
  3068. // The first comment in a braced lists is always interpreted as belonging to
  3069. // the first list element. Otherwise, it should be placed outside of the
  3070. // list.
  3071. return Left.BlockKind == BK_BracedInit ||
  3072. (Left.is(TT_CtorInitializerColon) &&
  3073. Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
  3074. if (Left.is(tok::question) && Right.is(tok::colon))
  3075. return false;
  3076. if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
  3077. return Style.BreakBeforeTernaryOperators;
  3078. if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
  3079. return !Style.BreakBeforeTernaryOperators;
  3080. if (Left.is(TT_InheritanceColon))
  3081. return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
  3082. if (Right.is(TT_InheritanceColon))
  3083. return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
  3084. if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
  3085. Left.isNot(TT_SelectorName))
  3086. return true;
  3087. if (Right.is(tok::colon) &&
  3088. !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
  3089. return false;
  3090. if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
  3091. if (Style.Language == FormatStyle::LK_Proto ||
  3092. Style.Language == FormatStyle::LK_TextProto) {
  3093. if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
  3094. return false;
  3095. // Prevent cases like:
  3096. //
  3097. // submessage:
  3098. // { key: valueeeeeeeeeeee }
  3099. //
  3100. // when the snippet does not fit into one line.
  3101. // Prefer:
  3102. //
  3103. // submessage: {
  3104. // key: valueeeeeeeeeeee
  3105. // }
  3106. //
  3107. // instead, even if it is longer by one line.
  3108. //
  3109. // Note that this allows allows the "{" to go over the column limit
  3110. // when the column limit is just between ":" and "{", but that does
  3111. // not happen too often and alternative formattings in this case are
  3112. // not much better.
  3113. //
  3114. // The code covers the cases:
  3115. //
  3116. // submessage: { ... }
  3117. // submessage: < ... >
  3118. // repeated: [ ... ]
  3119. if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
  3120. Right.is(TT_DictLiteral)) ||
  3121. Right.is(TT_ArrayInitializerLSquare))
  3122. return false;
  3123. }
  3124. return true;
  3125. }
  3126. if (Right.is(tok::r_square) && Right.MatchingParen &&
  3127. Right.MatchingParen->is(TT_ProtoExtensionLSquare))
  3128. return false;
  3129. if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
  3130. Right.Next->is(TT_ObjCMethodExpr)))
  3131. return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
  3132. if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
  3133. return true;
  3134. if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
  3135. return true;
  3136. if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
  3137. TT_OverloadedOperator))
  3138. return false;
  3139. if (Left.is(TT_RangeBasedForLoopColon))
  3140. return true;
  3141. if (Right.is(TT_RangeBasedForLoopColon))
  3142. return false;
  3143. if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
  3144. return true;
  3145. if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
  3146. Left.is(tok::kw_operator))
  3147. return false;
  3148. if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
  3149. Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
  3150. return false;
  3151. if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
  3152. !Style.Cpp11BracedListStyle)
  3153. return false;
  3154. if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
  3155. return false;
  3156. if (Left.is(tok::l_paren) && Left.Previous &&
  3157. (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
  3158. return false;
  3159. if (Right.is(TT_ImplicitStringLiteral))
  3160. return false;
  3161. if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
  3162. return false;
  3163. if (Right.is(tok::r_square) && Right.MatchingParen &&
  3164. Right.MatchingParen->is(TT_LambdaLSquare))
  3165. return false;
  3166. // We only break before r_brace if there was a corresponding break before
  3167. // the l_brace, which is tracked by BreakBeforeClosingBrace.
  3168. if (Right.is(tok::r_brace))
  3169. return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
  3170. // Allow breaking after a trailing annotation, e.g. after a method
  3171. // declaration.
  3172. if (Left.is(TT_TrailingAnnotation))
  3173. return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
  3174. tok::less, tok::coloncolon);
  3175. if (Right.is(tok::kw___attribute) ||
  3176. (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
  3177. return true;
  3178. if (Left.is(tok::identifier) && Right.is(tok::string_literal))
  3179. return true;
  3180. if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
  3181. return true;
  3182. if (Left.is(TT_CtorInitializerColon))
  3183. return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
  3184. if (Right.is(TT_CtorInitializerColon))
  3185. return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
  3186. if (Left.is(TT_CtorInitializerComma) &&
  3187. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
  3188. return false;
  3189. if (Right.is(TT_CtorInitializerComma) &&
  3190. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
  3191. return true;
  3192. if (Left.is(TT_InheritanceComma) &&
  3193. Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
  3194. return false;
  3195. if (Right.is(TT_InheritanceComma) &&
  3196. Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
  3197. return true;
  3198. if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
  3199. (Left.is(tok::less) && Right.is(tok::less)))
  3200. return false;
  3201. if (Right.is(TT_BinaryOperator) &&
  3202. Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
  3203. (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
  3204. Right.getPrecedence() != prec::Assignment))
  3205. return true;
  3206. if (Left.is(TT_ArrayInitializerLSquare))
  3207. return true;
  3208. if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
  3209. return true;
  3210. if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
  3211. !Left.isOneOf(tok::arrowstar, tok::lessless) &&
  3212. Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
  3213. (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
  3214. Left.getPrecedence() == prec::Assignment))
  3215. return true;
  3216. if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
  3217. (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
  3218. return false;
  3219. return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
  3220. tok::kw_class, tok::kw_struct, tok::comment) ||
  3221. Right.isMemberAccess() ||
  3222. Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
  3223. tok::colon, tok::l_square, tok::at) ||
  3224. (Left.is(tok::r_paren) &&
  3225. Right.isOneOf(tok::identifier, tok::kw_const)) ||
  3226. (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
  3227. (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
  3228. }
  3229. void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
  3230. llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
  3231. const FormatToken *Tok = Line.First;
  3232. while (Tok) {
  3233. llvm::errs() << " M=" << Tok->MustBreakBefore
  3234. << " C=" << Tok->CanBreakBefore
  3235. << " T=" << getTokenTypeName(Tok->Type)
  3236. << " S=" << Tok->SpacesRequiredBefore
  3237. << " B=" << Tok->BlockParameterCount
  3238. << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
  3239. << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
  3240. << " PPK=" << Tok->PackingKind << " FakeLParens=";
  3241. for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
  3242. llvm::errs() << Tok->FakeLParens[i] << "/";
  3243. llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
  3244. llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
  3245. llvm::errs() << " Text='" << Tok->TokenText << "'\n";
  3246. if (!Tok->Next)
  3247. assert(Tok == Line.Last);
  3248. Tok = Tok->Next;
  3249. }
  3250. llvm::errs() << "----\n";
  3251. }
  3252. } // namespace format
  3253. } // namespace clang