TokenAnnotator.cpp 138 KB

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