TokenAnnotator.cpp 144 KB

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